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
|
---|---|---|---|---|---|---|---|---|
10067550 | <NME> TextViewTests.cs
<BEF> using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.Rendering
{
[TestFixture]
internal class TextViewTests
{
[Test]
public void Visual_Line_Should_Create_Two_Text_Lines_When_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
window.Close();
}
[Test]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
window.Close();
}
}
}
<MSG> Update deps
<DFF> @@ -1,4 +1,5 @@
-using Avalonia.Controls;
+using Avalonia;
+using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
@@ -18,27 +19,23 @@ namespace AvaloniaEdit.Tests.Rendering
TextView textView = new TextView();
- TextDocument document = new TextDocument("hello world".ToCharArray());
+ TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
- textView.EnsureVisualLines();
+
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
- Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
- Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
+ Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Span));
+ Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Span));
}
- [Test]
+ [Test()]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
@@ -52,16 +49,12 @@ namespace AvaloniaEdit.Tests.Rendering
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
}
}
}
| 9 | Update deps | 16 | .cs | Tests/Rendering/TextViewTests | mit | AvaloniaUI/AvaloniaEdit |
10067551 | <NME> TextViewTests.cs
<BEF> using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.Rendering
{
[TestFixture]
internal class TextViewTests
{
[Test]
public void Visual_Line_Should_Create_Two_Text_Lines_When_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
window.Close();
}
[Test]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
window.Close();
}
}
}
<MSG> Update deps
<DFF> @@ -1,4 +1,5 @@
-using Avalonia.Controls;
+using Avalonia;
+using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
@@ -18,27 +19,23 @@ namespace AvaloniaEdit.Tests.Rendering
TextView textView = new TextView();
- TextDocument document = new TextDocument("hello world".ToCharArray());
+ TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
- textView.EnsureVisualLines();
+
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
- Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
- Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
+ Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Span));
+ Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Span));
}
- [Test]
+ [Test()]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
@@ -52,16 +49,12 @@ namespace AvaloniaEdit.Tests.Rendering
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
}
}
}
| 9 | Update deps | 16 | .cs | Tests/Rendering/TextViewTests | mit | AvaloniaUI/AvaloniaEdit |
10067552 | <NME> TextViewTests.cs
<BEF> using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.Rendering
{
[TestFixture]
internal class TextViewTests
{
[Test]
public void Visual_Line_Should_Create_Two_Text_Lines_When_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
window.Close();
}
[Test]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
window.Close();
}
}
}
<MSG> Update deps
<DFF> @@ -1,4 +1,5 @@
-using Avalonia.Controls;
+using Avalonia;
+using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
@@ -18,27 +19,23 @@ namespace AvaloniaEdit.Tests.Rendering
TextView textView = new TextView();
- TextDocument document = new TextDocument("hello world".ToCharArray());
+ TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
- textView.EnsureVisualLines();
+
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
- Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
- Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
+ Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Span));
+ Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Span));
}
- [Test]
+ [Test()]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
@@ -52,16 +49,12 @@ namespace AvaloniaEdit.Tests.Rendering
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
}
}
}
| 9 | Update deps | 16 | .cs | Tests/Rendering/TextViewTests | mit | AvaloniaUI/AvaloniaEdit |
10067553 | <NME> TextViewTests.cs
<BEF> using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.Rendering
{
[TestFixture]
internal class TextViewTests
{
[Test]
public void Visual_Line_Should_Create_Two_Text_Lines_When_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
window.Close();
}
[Test]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
window.Close();
}
}
}
<MSG> Update deps
<DFF> @@ -1,4 +1,5 @@
-using Avalonia.Controls;
+using Avalonia;
+using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
@@ -18,27 +19,23 @@ namespace AvaloniaEdit.Tests.Rendering
TextView textView = new TextView();
- TextDocument document = new TextDocument("hello world".ToCharArray());
+ TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
- textView.EnsureVisualLines();
+
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
- Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
- Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
+ Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Span));
+ Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Span));
}
- [Test]
+ [Test()]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
@@ -52,16 +49,12 @@ namespace AvaloniaEdit.Tests.Rendering
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
}
}
}
| 9 | Update deps | 16 | .cs | Tests/Rendering/TextViewTests | mit | AvaloniaUI/AvaloniaEdit |
10067554 | <NME> TextViewTests.cs
<BEF> using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.Rendering
{
[TestFixture]
internal class TextViewTests
{
[Test]
public void Visual_Line_Should_Create_Two_Text_Lines_When_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
window.Close();
}
[Test]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
window.Close();
}
}
}
<MSG> Update deps
<DFF> @@ -1,4 +1,5 @@
-using Avalonia.Controls;
+using Avalonia;
+using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
@@ -18,27 +19,23 @@ namespace AvaloniaEdit.Tests.Rendering
TextView textView = new TextView();
- TextDocument document = new TextDocument("hello world".ToCharArray());
+ TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
- textView.EnsureVisualLines();
+
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
- Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
- Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
+ Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Span));
+ Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Span));
}
- [Test]
+ [Test()]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
@@ -52,16 +49,12 @@ namespace AvaloniaEdit.Tests.Rendering
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
}
}
}
| 9 | Update deps | 16 | .cs | Tests/Rendering/TextViewTests | mit | AvaloniaUI/AvaloniaEdit |
10067555 | <NME> TextViewTests.cs
<BEF> using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.Rendering
{
[TestFixture]
internal class TextViewTests
{
[Test]
public void Visual_Line_Should_Create_Two_Text_Lines_When_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
window.Close();
}
[Test]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
window.Close();
}
}
}
<MSG> Update deps
<DFF> @@ -1,4 +1,5 @@
-using Avalonia.Controls;
+using Avalonia;
+using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
@@ -18,27 +19,23 @@ namespace AvaloniaEdit.Tests.Rendering
TextView textView = new TextView();
- TextDocument document = new TextDocument("hello world".ToCharArray());
+ TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
- textView.EnsureVisualLines();
+
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
- Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
- Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
+ Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Span));
+ Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Span));
}
- [Test]
+ [Test()]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
@@ -52,16 +49,12 @@ namespace AvaloniaEdit.Tests.Rendering
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
}
}
}
| 9 | Update deps | 16 | .cs | Tests/Rendering/TextViewTests | mit | AvaloniaUI/AvaloniaEdit |
10067556 | <NME> TextViewTests.cs
<BEF> using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.Rendering
{
[TestFixture]
internal class TextViewTests
{
[Test]
public void Visual_Line_Should_Create_Two_Text_Lines_When_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
window.Close();
}
[Test]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
TextView textView = new TextView();
TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
textView.EnsureVisualLines();
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
Window window = new Window();
window.Content = textView;
window.Show();
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
window.Close();
}
}
}
<MSG> Update deps
<DFF> @@ -1,4 +1,5 @@
-using Avalonia.Controls;
+using Avalonia;
+using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
@@ -18,27 +19,23 @@ namespace AvaloniaEdit.Tests.Rendering
TextView textView = new TextView();
- TextDocument document = new TextDocument("hello world".ToCharArray());
+ TextDocument document = new TextDocument("hello world".ToCharArray());
textView.Document = document;
- textView.EnsureVisualLines();
+
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 8;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(2, visualLine.TextLines.Count);
- Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
- Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
+ Assert.AreEqual("hello ", new string(visualLine.TextLines[0].TextRuns[0].Text.Span));
+ Assert.AreEqual("world", new string(visualLine.TextLines[1].TextRuns[0].Text.Span));
}
- [Test]
+ [Test()]
public void Visual_Line_Should_Create_One_Text_Lines_When_Not_Wrapping()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
@@ -52,16 +49,12 @@ namespace AvaloniaEdit.Tests.Rendering
((ILogicalScrollable)textView).CanHorizontallyScroll = false;
textView.Width = MockGlyphTypeface.GlyphAdvance * 500;
- Window window = new Window();
- window.Content = textView;
- window.Show();
+ textView.Measure(Size.Infinity);
VisualLine visualLine = textView.GetOrConstructVisualLine(document.Lines[0]);
Assert.AreEqual(1, visualLine.TextLines.Count);
Assert.AreEqual("hello world", new string(visualLine.TextLines[0].TextRuns[0].Text.Buffer.Span));
-
- window.Close();
}
}
}
| 9 | Update deps | 16 | .cs | Tests/Rendering/TextViewTests | mit | AvaloniaUI/AvaloniaEdit |
10067557 | <NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 1, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Added a new grid config option to allow configuring of where newly inserted rows appear (top or bottom) <DFF> @@ -1066,7 +1066,7 @@ $(function() { deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); - test("insert data", function() { + test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, @@ -1075,7 +1075,55 @@ $(function() { gridOptions = { inserting: true, - data: [], + data: [{field: "default"}], + fields: [ + { + name: "field", + insertTemplate: function() { + var result = this.insertControl = $("<input>").attr("type", "text"); + return result; + }, + insertValue: function() { + return this.insertControl.val(); + } + } + ], + onItemInserting: function(e) { + insertingArgs = $.extend(true, {}, e); + }, + onItemInserted: function(e) { + insertedArgs = $.extend(true, {}, e); + }, + controller: { + insertItem: function() { + inserted = true; + } + } + }, + + grid = new Grid($element, gridOptions); + + grid.fields[0].insertControl.val("test"); + grid.insertItem(); + + equal(insertingArgs.item.field, "test", "field is provided in inserting args"); + equal(grid.option("data").length, 2, "data is inserted"); + ok(inserted, "controller insertItem was called"); + deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); + equal(insertedArgs.item.field, "test", "field is provided in inserted args"); + }); + + test("insert data with specified insert location", function() { + var $element = $("#jsGrid"), + + inserted = false, + insertingArgs, + insertedArgs, + + gridOptions = { + inserting: | 52 | Added a new grid config option to allow configuring of where newly inserted rows appear (top or bottom) | 4 | .js | tests | mit | tabalinas/jsgrid |
10067558 | <NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 1, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Added a new grid config option to allow configuring of where newly inserted rows appear (top or bottom) <DFF> @@ -1066,7 +1066,7 @@ $(function() { deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); - test("insert data", function() { + test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, @@ -1075,7 +1075,55 @@ $(function() { gridOptions = { inserting: true, - data: [], + data: [{field: "default"}], + fields: [ + { + name: "field", + insertTemplate: function() { + var result = this.insertControl = $("<input>").attr("type", "text"); + return result; + }, + insertValue: function() { + return this.insertControl.val(); + } + } + ], + onItemInserting: function(e) { + insertingArgs = $.extend(true, {}, e); + }, + onItemInserted: function(e) { + insertedArgs = $.extend(true, {}, e); + }, + controller: { + insertItem: function() { + inserted = true; + } + } + }, + + grid = new Grid($element, gridOptions); + + grid.fields[0].insertControl.val("test"); + grid.insertItem(); + + equal(insertingArgs.item.field, "test", "field is provided in inserting args"); + equal(grid.option("data").length, 2, "data is inserted"); + ok(inserted, "controller insertItem was called"); + deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); + equal(insertedArgs.item.field, "test", "field is provided in inserted args"); + }); + + test("insert data with specified insert location", function() { + var $element = $("#jsGrid"), + + inserted = false, + insertingArgs, + insertedArgs, + + gridOptions = { + inserting: | 52 | Added a new grid config option to allow configuring of where newly inserted rows appear (top or bottom) | 4 | .js | tests | mit | tabalinas/jsgrid |
10067559 | <NME> fr.js
<BEF> (function(jsGrid) {
jsGrid.locales.ru = {
grid: {
noDataContent: "Pas de données",
deleteConfirm: "Êtes-vous sûr ?",
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} de {pageCount}",
pagePrevText: "<",
pageNextText: ">",
pageFirstText: "<<",
pageLastText: ">>",
loadMessage: "Chargement en cours...",
invalidMessage: "Des données incorrectes sont entrés !"
},
loadIndicator: {
message: "Chargement en cours..."
},
fields: {
control: {
searchModeButtonTooltip: "Recherche",
insertModeButtonTooltip: "Ajouter une entrée",
editButtonTooltip: "Changer",
deleteButtonTooltip: "Effacer",
searchButtonTooltip: "Trouve",
clearFilterButtonTooltip: "Effacer",
insertButtonTooltip: "Ajouter",
updateButtonTooltip: "Sauvegarder",
cancelEditButtonTooltip: "Annuler"
}
},
validators: {
required: { message: "Champ requis" },
rangeLength: { message: "Longueur de la valeur du champ est hors de la plage définie" },
minLength: { message: "La valeur du champ est trop court" },
maxLength: { message: "La valeur du champ est trop long" },
pattern: { message: "La valeur du champ ne correspond pas à la configuration définie" },
range: { message: "La valeur du champ est hors de la plage définie" },
min: { message: "La valeur du champ est trop petit" },
max: { message: "La valeur du champ est trop grande" }
}
};
}(jsGrid, jQuery));
<MSG> i18n: Correct French localization name
<DFF> @@ -1,6 +1,6 @@
(function(jsGrid) {
- jsGrid.locales.ru = {
+ jsGrid.locales.fr = {
grid: {
noDataContent: "Pas de données",
deleteConfirm: "Êtes-vous sûr ?",
| 1 | i18n: Correct French localization name | 1 | .js | js | mit | tabalinas/jsgrid |
10067560 | <NME> fr.js
<BEF> (function(jsGrid) {
jsGrid.locales.ru = {
grid: {
noDataContent: "Pas de données",
deleteConfirm: "Êtes-vous sûr ?",
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} de {pageCount}",
pagePrevText: "<",
pageNextText: ">",
pageFirstText: "<<",
pageLastText: ">>",
loadMessage: "Chargement en cours...",
invalidMessage: "Des données incorrectes sont entrés !"
},
loadIndicator: {
message: "Chargement en cours..."
},
fields: {
control: {
searchModeButtonTooltip: "Recherche",
insertModeButtonTooltip: "Ajouter une entrée",
editButtonTooltip: "Changer",
deleteButtonTooltip: "Effacer",
searchButtonTooltip: "Trouve",
clearFilterButtonTooltip: "Effacer",
insertButtonTooltip: "Ajouter",
updateButtonTooltip: "Sauvegarder",
cancelEditButtonTooltip: "Annuler"
}
},
validators: {
required: { message: "Champ requis" },
rangeLength: { message: "Longueur de la valeur du champ est hors de la plage définie" },
minLength: { message: "La valeur du champ est trop court" },
maxLength: { message: "La valeur du champ est trop long" },
pattern: { message: "La valeur du champ ne correspond pas à la configuration définie" },
range: { message: "La valeur du champ est hors de la plage définie" },
min: { message: "La valeur du champ est trop petit" },
max: { message: "La valeur du champ est trop grande" }
}
};
}(jsGrid, jQuery));
<MSG> i18n: Correct French localization name
<DFF> @@ -1,6 +1,6 @@
(function(jsGrid) {
- jsGrid.locales.ru = {
+ jsGrid.locales.fr = {
grid: {
noDataContent: "Pas de données",
deleteConfirm: "Êtes-vous sûr ?",
| 1 | i18n: Correct French localization name | 1 | .js | js | mit | tabalinas/jsgrid |
10067561 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067562 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067563 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067564 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067565 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067566 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067567 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067568 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067569 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067570 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067571 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067572 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067573 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067574 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067575 | <NME> TextView.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
private bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(_scrollViewport)
&& extent.IsClose(_scrollExtent)
&& offset.IsClose(_scrollOffset)))
{
_scrollViewport = viewport;
_scrollExtent = extent;
SetScrollOffset(offset);
OnScrollChange();
return true;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Use better defaults for NonPrintableCharacterBrushProperty
50% gray with alpha of 145 looks good in both light and dark themes
<DFF> @@ -545,7 +545,7 @@ namespace AvaloniaEdit.Rendering
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
- AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", Brushes.LightGray);
+ AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
| 1 | Use better defaults for NonPrintableCharacterBrushProperty | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067576 | <NME> chai-3.2.0.js <BEF> ADDFILE <MSG> set up mocha tests <DFF> @@ -0,0 +1,5332 @@ + +;(function(){ + +/** + * Require the module at `name`. + * + * @param {String} name + * @return {Object} exports + * @api public + */ + +function require(name) { + var module = require.modules[name]; + if (!module) throw new Error('failed to require "' + name + '"'); + + if (!('exports' in module) && typeof module.definition === 'function') { + module.client = module.component = true; + module.definition.call(this, module.exports = {}, module); + delete module.definition; + } + + return module.exports; +} + +/** + * Meta info, accessible in the global scope unless you use AMD option. + */ + +require.loader = 'component'; + +/** + * Internal helper object, contains a sorting function for semantiv versioning + */ +require.helper = {}; +require.helper.semVerSort = function(a, b) { + var aArray = a.version.split('.'); + var bArray = b.version.split('.'); + for (var i=0; i<aArray.length; ++i) { + var aInt = parseInt(aArray[i], 10); + var bInt = parseInt(bArray[i], 10); + if (aInt === bInt) { + var aLex = aArray[i].substr((""+aInt).length); + var bLex = bArray[i].substr((""+bInt).length); + if (aLex === '' && bLex !== '') return 1; + if (aLex !== '' && bLex === '') return -1; + if (aLex !== '' && bLex !== '') return aLex > bLex ? 1 : -1; + continue; + } else if (aInt > bInt) { + return 1; + } else { + return -1; + } + } + return 0; +} + +/** + * Find and require a module which name starts with the provided name. + * If multiple modules exists, the highest semver is used. + * This function can only be used for remote dependencies. + + * @param {String} name - module name: `user~repo` + * @param {Boolean} returnPath - returns the canonical require path if true, + * otherwise it returns the epxorted module + */ +require.latest = function (name, returnPath) { + function showError(name) { + throw new Error('failed to find latest module of "' + name + '"'); + } + // only remotes with semvers, ignore local files conataining a '/' + var versionRegexp = /(.*)~(.*)@v?(\d+\.\d+\.\d+[^\/]*)$/; + var remoteRegexp = /(.*)~(.*)/; + if (!remoteRegexp.test(name)) showError(name); + var moduleNames = Object.keys(require.modules); + var semVerCandidates = []; + var otherCandidates = []; // for instance: name of the git branch + for (var i=0; i<moduleNames.length; i++) { + var moduleName = moduleNames[i]; + if (new RegExp(name + '@').test(moduleName)) { + var version = moduleName.substr(name.length+1); + var semVerMatch = versionRegexp.exec(moduleName); + if (semVerMatch != null) { + semVerCandidates.push({version: version, name: moduleName}); + } else { + otherCandidates.push({version: version, name: moduleName}); + } + } + } + if (semVerCandidates.concat(otherCandidates).length === 0) { + showError(name); + } + if (semVerCandidates.length > 0) { + var module = semVerCandidates.sort(require.helper.semVerSort).pop().name; + if (returnPath === true) { + return module; + } + return require(module); + } + // if the build contains more than one branch of the same module + // you should not use this funciton + var module = otherCandidates.sort(function(a, b) {return a.name > b.name})[0].name; + if (returnPath === true) { + return module; + } + return require(module); +} + +/** + * Registered modules. + */ + +require.modules = {}; + +/** + * Register module at `name` with callback `definition`. + * + * @param {String} name + * @param {Function} definition + * @api private + */ + +require.register = function (name, definition) { + require.modules[name] = { + definition: definition + }; +}; + +/** + * Define a module's exports immediately with `exports`. + * + * @param {String} name + * @param {Generic} exports + * @api private + */ + +require.define = function (name, exports) { + require.modules[name] = { + exports: exports + }; +}; +require.register("[email protected]", function (exports, module) { +/*! + * assertion-error + * Copyright(c) 2013 Jake Luer <[email protected]> + * MIT Licensed + */ + +/*! + * Return a function that will copy properties from + * one object to another excluding any originally + * listed. Returned function will create a new `{}`. + * + * @param {String} excluded properties ... + * @return {Function} + */ + +function exclude () { + var excludes = [].slice.call(arguments); + + function excludeProps (res, obj) { + Object.keys(obj).forEach(function (key) { + if (!~excludes.indexOf(key)) res[key] = obj[key]; + }); + } + + return function extendExclude () { + var args = [].slice.call(arguments) + , i = 0 + , res = {}; + + for (; i < args.length; i++) { + excludeProps(res, args[i]); + } + + return res; + }; +}; + +/*! + * Primary Exports + */ + +module.exports = AssertionError; + +/** + * ### AssertionError + * + * An extension of the JavaScript `Error` constructor for + * assertion and validation scenarios. + * + * @param {String} message + * @param {Object} properties to include (optional) + * @param {callee} start stack function (optional) + */ + +function AssertionError (message, _props, ssf) { + var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON') + , props = extend(_props || {}); + + // default values + this.message = message || 'Unspecified AssertionError'; + this.showDiff = false; + + // copy from properties + for (var key in props) { + this[key] = props[key]; + } + + // capture stack trace + ssf = ssf || arguments.callee; + if (ssf && Error.captureStackTrace) { + Error.captureStackTrace(this, ssf); + } +} + +/*! + * Inherit from Error.prototype + */ + +AssertionError.prototype = Object.create(Error.prototype); + +/*! + * Statically set name + */ + +AssertionError.prototype.name = 'AssertionError'; + +/*! + * Ensure correct constructor + */ + +AssertionError.prototype.constructor = AssertionError; + +/** + * Allow errors to be converted to JSON for static transfer. + * + * @param {Boolean} include stack (default: `true`) + * @return {Object} object that can be `JSON.stringify` + */ + +AssertionError.prototype.toJSON = function (stack) { + var extend = exclude('constructor', 'toJSON', 'stack') + , props = extend({ name: this.name }, this); + + // include stack if exists and not turned off + if (false !== stack && this.stack) { + props.stack = this.stack; + } + + return props; +}; + +}); + +require.register("[email protected]", function (exports, module) { +/*! + * type-detect + * Copyright(c) 2013 jake luer <[email protected]> + * MIT Licensed + */ + +/*! + * Primary Exports + */ + +var exports = module.exports = getType; + +/*! + * Detectable javascript natives + */ + +var natives = { + '[object Array]': 'array' + , '[object RegExp]': 'regexp' + , '[object Function]': 'function' + , '[object Arguments]': 'arguments' + , '[object Date]': 'date' +}; + +/** + * ### typeOf (obj) + * + * Use several different techniques to determine + * the type of object being tested. + * + * + * @param {Mixed} object + * @return {String} object type + * @api public + */ + +function getType (obj) { + var str = Object.prototype.toString.call(obj); + if (natives[str]) return natives[str]; + if (obj === null) return 'null'; + if (obj === undefined) return 'undefined'; + if (obj === Object(obj)) return 'object'; + return typeof obj; +} + +exports.Library = Library; + +/** + * ### Library + * + * Create a repository for custom type detection. + * + * ```js + * var lib = new type.Library; + * ``` + * + */ + +function Library () { + this.tests = {}; +} + +/** + * #### .of (obj) + * + * Expose replacement `typeof` detection to the library. + * + * ```js + * if ('string' === lib.of('hello world')) { + * // ... + * } + * ``` + * + * @param {Mixed} object to test + * @return {String} type + */ + +Library.prototype.of = getType; + +/** + * #### .define (type, test) + * + * Add a test to for the `.test()` assertion. + * + * Can be defined as a regular expression: + * + * ```js + * lib.define('int', /^[0-9]+$/); + * ``` + * + * ... or as a function: + * + * ```js + * lib.define('bln', function (obj) { + * if ('boolean' === lib.of(obj)) return true; + * var blns = [ 'yes', 'no', 'true', 'false', 1, 0 ]; + * if ('string' === lib.of(obj)) obj = obj.toLowerCase(); + * return !! ~blns.indexOf(obj); + * }); + * ``` + * + * @param {String} type + * @param {RegExp|Function} test + * @api public + */ + +Library.prototype.define = function (type, test) { + if (arguments.length === 1) return this.tests[type]; + this.tests[type] = test; + return this; +}; + +/** + * #### .test (obj, test) + * + * Assert that an object is of type. Will first + * check natives, and if that does not pass it will + * use the user defined custom tests. + * + * ```js + * assert(lib.test('1', 'int')); + * assert(lib.test('yes', 'bln')); + * ``` + * + * @param {Mixed} object + * @param {String} type + * @return {Boolean} result + * @api public + */ + +Library.prototype.test = function (obj, type) { + if (type === getType(obj)) return true; + var test = this.tests[type]; + + if (test && 'regexp' === getType(test)) { + return test.test(obj); + } else if (test && 'function' === getType(test)) { + return test(obj); + } else { + throw new ReferenceError('Type test "' + type + '" not defined or invalid.'); + } +}; + +}); + +require.register("[email protected]", function (exports, module) { +/*! + * deep-eql + * Copyright(c) 2013 Jake Luer <[email protected]> + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var type = require('[email protected]'); + +/*! + * Buffer.isBuffer browser shim + */ + +var Buffer; +try { Buffer = require('buffer').Buffer; } +catch(ex) { + Buffer = {}; + Buffer.isBuffer = function() { return false; } +} + +/*! + * Primary Export + */ + +module.exports = deepEqual; + +/** + * Assert super-strict (egal) equality between + * two objects of any type. + * + * @param {Mixed} a + * @param {Mixed} b + * @param {Array} memoised (optional) + * @return {Boolean} equal match + */ + +function deepEqual(a, b, m) { + if (sameValue(a, b)) { + return true; + } else if ('date' === type(a)) { + return dateEqual(a, b); + } else if ('regexp' === type(a)) { + return regexpEqual(a, b); + } else if (Buffer.isBuffer(a)) { + return bufferEqual(a, b); + } else if ('arguments' === type(a)) { + return argumentsEqual(a, b, m); + } else if (!typeEqual(a, b)) { + return false; + } else if (('object' !== type(a) && 'object' !== type(b)) + && ('array' !== type(a) && 'array' !== type(b))) { + return sameValue(a, b); + } else { + return objectEqual(a, b, m); + } +} + +/*! + * Strict (egal) equality test. Ensures that NaN always + * equals NaN and `-0` does not equal `+0`. + * + * @param {Mixed} a + * @param {Mixed} b + * @return {Boolean} equal match + */ + +function sameValue(a, b) { + if (a === b) return a !== 0 || 1 / a === 1 / b; + return a !== a && b !== b; +} + +/*! + * Compare the types of two given objects and + * return if they are equal. Note that an Array + * has a type of `array` (not `object`) and arguments + * have a type of `arguments` (not `array`/`object`). + * + * @param {Mixed} a + * @param {Mixed} b + * @return {Boolean} result + */ + +function typeEqual(a, b) { + return type(a) === type(b); +} + +/*! + * Compare two Date objects by asserting that + * the time values are equal using `saveValue`. + * + * @param {Date} a + * @param {Date} b + * @return {Boolean} result + */ + +function dateEqual(a, b) { + if ('date' !== type(b)) return false; + return sameValue(a.getTime(), b.getTime()); +} + +/*! + * Compare two regular expressions by converting them + * to string and checking for `sameValue`. + * + * @param {RegExp} a + * @param {RegExp} b + * @return {Boolean} result + */ + +function regexpEqual(a, b) { + if ('regexp' !== type(b)) return false; + return sameValue(a.toString(), b.toString()); +} + +/*! + * Assert deep equality of two `arguments` objects. + * Unfortunately, these must be sliced to arrays + * prior to test to ensure no bad behavior. + * + * @param {Arguments} a + * @param {Arguments} b + * @param {Array} memoize (optional) + * @return {Boolean} result + */ + +function argumentsEqual(a, b, m) { + if ('arguments' !== type(b)) return false; + a = [].slice.call(a); + b = [].slice.call(b); + return deepEqual(a, b, m); +} + +/*! + * Get enumerable properties of a given object. + * + * @param {Object} a + * @return {Array} property names + */ + +function enumerable(a) { + var res = []; + for (var key in a) res.push(key); + return res; +} + +/*! + * Simple equality for flat iterable objects + * such as Arrays or Node.js buffers. + * + * @param {Iterable} a + * @param {Iterable} b + * @return {Boolean} result + */ + +function iterableEqual(a, b) { + if (a.length !== b.length) return false; + + var i = 0; + var match = true; + + for (; i < a.length; i++) { + if (a[i] !== b[i]) { + match = false; + break; + } + } + + return match; +} + +/*! + * Extension to `iterableEqual` specifically + * for Node.js Buffers. + * + * @param {Buffer} a + * @param {Mixed} b + * @return {Boolean} result + */ + +function bufferEqual(a, b) { + if (!Buffer.isBuffer(b)) return false; + return iterableEqual(a, b); +} + +/*! + * Block for `objectEqual` ensuring non-existing + * values don't get in. + * + * @param {Mixed} object + * @return {Boolean} result + */ + +function isValue(a) { + return a !== null && a !== undefined; +} + +/*! + * Recursively check the equality of two objects. + * Once basic sameness has been established it will + * defer to `deepEqual` for each enumerable key + * in the object. + * + * @param {Mixed} a + * @param {Mixed} b + * @return {Boolean} result + */ + +function objectEqual(a, b, m) { + if (!isValue(a) || !isValue(b)) { + return false; + } + + if (a.prototype !== b.prototype) { + return false; + } + + var i; + if (m) { + for (i = 0; i < m.length; i++) { + if ((m[i][0] === a && m[i][1] === b) + || (m[i][0] === b && m[i][1] === a)) { + return true; + } + } + } else { + m = []; + } + + try { + var ka = enumerable(a); + var kb = enumerable(b); + } catch (ex) { + return false; + } + + ka.sort(); + kb.sort(); + + if (!iterableEqual(ka, kb)) { + return false; + } + + m.push([ a, b ]); + + var key; + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!deepEqual(a[key], b[key], m)) { + return false; + } + } + + return true; +} + +}); + +require.register("chai", function (exports, module) { +module.exports = require('chai/lib/chai.js'); + +}); + +require.register("chai/lib/chai.js", function (exports, module) { +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer <[email protected]> + * MIT Licensed + */ + +var used = [] + , exports = module.exports = {}; + +/*! + * Chai version + */ + +exports.version = '2.1.0'; + +/*! + * Assertion Error + */ + +exports.AssertionError = require('[email protected]'); + +/*! + * Utils for plugins (not exported) + */ + +var util = require('chai/lib/chai/utils/index.js'); + +/** + * # .use(function) + * + * Provides a way to extend the internals of Chai + * + * @param {Function} + * @returns {this} for chaining + * @api public + */ + +exports.use = function (fn) { + if (!~used.indexOf(fn)) { + fn(this, util); + used.push(fn); + } + + return this; +}; + +/*! + * Utility Functions + */ + +exports.util = util; + +/*! + * Configuration + */ + +var config = require('chai/lib/chai/config.js'); +exports.config = config; + +/*! + * Primary `Assertion` prototype + */ + +var assertion = require('chai/lib/chai/assertion.js'); +exports.use(assertion); + +/*! + * Core Assertions + */ + +var core = require('chai/lib/chai/core/assertions.js'); +exports.use(core); + +/*! + * Expect interface + */ + +var expect = require('chai/lib/chai/interface/expect.js'); +exports.use(expect); + +/*! + * Should interface + */ + +var should = require('chai/lib/chai/interface/should.js'); +exports.use(should); + +/*! + * Assert interface + */ + +var assert = require('chai/lib/chai/interface/assert.js'); +exports.use(assert); + +}); + +require.register("chai/lib/chai/assertion.js", function (exports, module) { +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer <[email protected]> + * MIT Licensed + */ + +var config = require('chai/lib/chai/config.js'); + +module.exports = function (_chai, util) { + /*! + * Module dependencies. + */ + + var AssertionError = _chai.AssertionError + , flag = util.flag; + + /*! + * Module export. + */ + + _chai.Assertion = Assertion; + + /*! + * Assertion Constructor + * + * Creates object for chaining. + * + * @api private + */ + + function Assertion (obj, msg, stack) { + flag(this, 'ssfi', stack || arguments.callee); + flag(this, 'object', obj); + flag(this, 'message', msg); + } + + Object.defineProperty(Assertion, 'includeStack', { + get: function() { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + return config.includeStack; + }, + set: function(value) { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + config.includeStack = value; + } + }); + + Object.defineProperty(Assertion, 'showDiff', { + get: function() { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + return config.showDiff; + }, + set: function(value) { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + config.showDiff = value; + } + }); + + Assertion.addProperty = function (name, fn) { + util.addProperty(this.prototype, name, fn); + }; + + Assertion.addMethod = function (name, fn) { + util.addMethod(this.prototype, name, fn); + }; + + Assertion.addChainableMethod = function (name, fn, chainingBehavior) { + util.addChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + Assertion.overwriteProperty = function (name, fn) { + util.overwriteProperty(this.prototype, name, fn); + }; + + Assertion.overwriteMethod = function (name, fn) { + util.overwriteMethod(this.prototype, name, fn); + }; + + Assertion.overwriteChainableMethod = function (name, fn, chainingBehavior) { + util.overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + /*! + * ### .assert(expression, message, negateMessage, expected, actual) + * + * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. + * + * @name assert + * @param {Philosophical} expression to be tested + * @param {String or Function} message or function that returns message to display if fails + * @param {String or Function} negatedMessage or function that returns negatedMessage to display if negated expression fails + * @param {Mixed} expected value (remember to check for negation) + * @param {Mixed} actual (optional) will default to `this.obj` + * @api private + */ + + Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { + var ok = util.test(this, arguments); + if (true !== showDiff) showDiff = false; + if (true !== config.showDiff) showDiff = false; + + if (!ok) { + var msg = util.getMessage(this, arguments) + , actual = util.getActual(this, arguments); + throw new AssertionError(msg, { + actual: actual + , expected: expected + , showDiff: showDiff + }, (config.includeStack) ? this.assert : flag(this, 'ssfi')); + } + }; + + /*! + * ### ._obj + * + * Quick reference to stored `actual` value for plugin developers. + * + * @api private + */ + + Object.defineProperty(Assertion.prototype, '_obj', + { get: function () { + return flag(this, 'object'); + } + , set: function (val) { + flag(this, 'object', val); + } + }); +}; + +}); + +require.register("chai/lib/chai/config.js", function (exports, module) { +module.exports = { + + /** + * ### config.includeStack + * + * User configurable property, influences whether stack trace + * is included in Assertion error message. Default of false + * suppresses stack trace in the error message. + * + * chai.config.includeStack = true; // enable stack on error + * + * @param {Boolean} + * @api public + */ + + includeStack: false, + + /** + * ### config.showDiff + * + * User configurable property, influences whether or not + * the `showDiff` flag should be included in the thrown + * AssertionErrors. `false` will always be `false`; `true` + * will be true when the assertion has requested a diff + * be shown. + * + * @param {Boolean} + * @api public + */ + + showDiff: true, + + /** + * ### config.truncateThreshold + * + * User configurable property, sets length threshold for actual and + * expected values in assertion errors. If this threshold is exceeded, + * the value is truncated. + * + * Set it to zero if you want to disable truncating altogether. + * + * chai.config.truncateThreshold = 0; // disable truncating + * + * @param {Number} + * @api public + */ + + truncateThreshold: 40 + +}; + +}); + +require.register("chai/lib/chai/core/assertions.js", function (exports, module) { +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer <[email protected]> + * MIT Licensed + */ + +module.exports = function (chai, _) { + var Assertion = chai.Assertion + , toString = Object.prototype.toString + , flag = _.flag; + + /** + * ### Language Chains + * + * The following are provided as chainable getters to + * improve the readability of your assertions. They + * do not provide testing capabilities unless they + * have been overwritten by a plugin. + * + * **Chains** + * + * - to + * - be + * - been + * - is + * - that + * - which + * - and + * - has + * - have + * - with + * - at + * - of + * - same + * + * @name language chains + * @api public + */ + + [ 'to', 'be', 'been' + , 'is', 'and', 'has', 'have' + , 'with', 'that', 'which', 'at' + , 'of', 'same' ].forEach(function (chain) { + Assertion.addProperty(chain, function () { + return this; + }); + }); + + /** + * ### .not + * + * Negates any of assertions following in the chain. + * + * expect(foo).to.not.equal('bar'); + * expect(goodFn).to.not.throw(Error); + * expect({ foo: 'baz' }).to.have.property('foo') + * .and.not.equal('bar'); + * + * @name not + * @api public + */ + + Assertion.addProperty('not', function () { + flag(this, 'negate', true); + }); + + /** + * ### .deep + * + * Sets the `deep` flag, later used by the `equal` and + * `property` assertions. + * + * expect(foo).to.deep.equal({ bar: 'baz' }); + * expect({ foo: { bar: { baz: 'quux' } } }) + * .to.have.deep.property('foo.bar.baz', 'quux'); + * + * @name deep + * @api public + */ + + Assertion.addProperty('deep', function () { + flag(this, 'deep', true); + }); + + /** + * ### .any + * + * Sets the `any` flag, (opposite of the `all` flag) + * later used in the `keys` assertion. + * + * expect(foo).to.have.any.keys('bar', 'baz'); + * + * @name any + * @api public + */ + + Assertion.addProperty('any', function () { + flag(this, 'any', true); + flag(this, 'all', false) + }); + + + /** + * ### .all + * + * Sets the `all` flag (opposite of the `any` flag) + * later used by the `keys` assertion. + * + * expect(foo).to.have.all.keys('bar', 'baz'); + * + * @name all + * @api public + */ + + Assertion.addProperty('all', function () { + flag(this, 'all', true); + flag(this, 'any', false); + }); + + /** + * ### .a(type) + * + * The `a` and `an` assertions are aliases that can be + * used either as language chains or to assert a value's + * type. + * + * // typeof + * expect('test').to.be.a('string'); + * expect({ foo: 'bar' }).to.be.an('object'); + * expect(null).to.be.a('null'); + * expect(undefined).to.be.an('undefined'); + * + * // language chain + * expect(foo).to.be.an.instanceof(Foo); + * + * @name a + * @alias an + * @param {String} type + * @param {String} message _optional_ + * @api public + */ + + function an (type, msg) { + if (msg) flag(this, 'message', msg); + type = type.toLowerCase(); + var obj = flag(this, 'object') + , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; + + this.assert( + type === _.type(obj) + , 'expected #{this} to be ' + article + type + , 'expected #{this} not to be ' + article + type + ); + } + + Assertion.addChainableMethod('an', an); + Assertion.addChainableMethod('a', an); + + /** + * ### .include(value) + * + * The `include` and `contain` assertions can be used as either property + * based language chains or as methods to assert the inclusion of an object + * in an array or a substring in a string. When used as language chains, + * they toggle the `contains` flag for the `keys` assertion. + * + * expect([1,2,3]).to.include(2); + * expect('foobar').to.contain('foo'); + * expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo'); + * + * @name include + * @alias contain + * @alias includes + * @alias contains + * @param {Object|String|Number} obj + * @param {String} message _optional_ + * @api public + */ + + function includeChainingBehavior () { + flag(this, 'contains', true); + } + + function include (val, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var expected = false; + if (_.type(obj) === 'array' && _.type(val) === 'object') { + for (var i in obj) { + if (_.eql(obj[i], val)) { + expected = true; + break; + } + } + } else if (_.type(val) === 'object') { + if (!flag(this, 'negate')) { + for (var k in val) new Assertion(obj).property(k, val[k]); + return; + } + var subset = {}; + for (var k in val) subset[k] = obj[k]; + expected = _.eql(subset, val); + } else { + expected = obj && ~obj.indexOf(val); + } + this.assert( + expected + , 'expected #{this} to include ' + _.inspect(val) + , 'expected #{this} to not include ' + _.inspect(val)); + } + + Assertion.addChainableMethod('include', include, includeChainingBehavior); + Assertion.addChainableMethod('contain', include, includeChainingBehavior); + Assertion.addChainableMethod('contains', include, includeChainingBehavior); + Assertion.addChainableMethod('includes', include, includeChainingBehavior); + + /** + * ### .ok + * + * Asserts that the target is truthy. + * + * expect('everthing').to.be.ok; + * expect(1).to.be.ok; + * expect(false).to.not.be.ok; + * expect(undefined).to.not.be.ok; + * expect(null).to.not.be.ok; + * + * @name ok + * @api public + */ + + Assertion.addProperty('ok', function () { + this.assert( + flag(this, 'object') + , 'expected #{this} to be truthy' + , 'expected #{this} to be falsy'); + }); + + /** + * ### .true + * + * Asserts that the target is `true`. + * + * expect(true).to.be.true; + * expect(1).to.not.be.true; + * + * @name true + * @api public + */ + + Assertion.addProperty('true', function () { + this.assert( + true === flag(this, 'object') + , 'expected #{this} to be true' + , 'expected #{this} to be false' + , this.negate ? false : true + ); + }); + + /** + * ### .false + * + * Asserts that the target is `false`. + * + * expect(false).to.be.false; + * expect(0).to.not.be.false; + * + * @name false + * @api public + */ + + Assertion.addProperty('false', function () { + this.assert( + false === flag(this, 'object') + , 'expected #{this} to be false' + , 'expected #{this} to be true' + , this.negate ? true : false + ); + }); + + /** + * ### .null + * + * Asserts that the target is `null`. + * + * expect(null).to.be.null; + * expect(undefined).not.to.be.null; + * + * @name null + * @api public + */ + + Assertion.addProperty('null', function () { + this.assert( + null === flag(this, 'object') + , 'expected #{this} to be null' + , 'expected #{this} not to be null' + ); + }); + + /** + * ### .undefined + * + * Asserts that the target is `undefined`. + * + * expect(undefined).to.be.undefined; + * expect(null).to.not.be.undefined; + * + * @name undefined + * @api public + */ + + Assertion.addProperty('undefined', function () { + this.assert( + undefined === flag(this, 'object') + , 'expected #{this} to be undefined' + , 'expected #{this} not to be undefined' + ); + }); + + /** + * ### .exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi' + * , bar = null + * , baz; + * + * expect(foo).to.exist; + * expect(bar).to.not.exist; + * expect(baz).to.not.exist; + * + * @name exist + * @api public + */ + + Assertion.addProperty('exist', function () { + this.assert( + null != flag(this, 'object') + , 'expected #{this} to exist' + , 'expected #{this} to not exist' + ); + }); + + + /** + * ### .empty + * + * Asserts that the target's length is `0`. For arrays, it checks + * the `length` property. For objects, it gets the count of + * enumerable keys. + * + * expect([]).to.be.empty; + * expect('').to.be.empty; + * expect({}).to.be.empty; + * + * @name empty + * @api public + */ + + Assertion.addProperty('empty', function () { + var obj = flag(this, 'object') + , expected = obj; + + if (Array.isArray(obj) || 'string' === typeof object) { + expected = obj.length; + } else if (typeof obj === 'object') { + expected = Object.keys(obj).length; + } + + this.assert( + !expected + , 'expected #{this} to be empty' + , 'expected #{this} not to be empty' + ); + }); + + /** + * ### .arguments + * + * Asserts that the target is an arguments object. + * + * function test () { + * expect(arguments).to.be.arguments; + * } + * + * @name arguments + * @alias Arguments + * @api public + */ + + function checkArguments () { + var obj = flag(this, 'object') + , type = Object.prototype.toString.call(obj); + this.assert( + '[object Arguments]' === type + , 'expected #{this} to be arguments but got ' + type + , 'expected #{this} to not be arguments' + ); + } + + Assertion.addProperty('arguments', checkArguments); + Assertion.addProperty('Arguments', checkArguments); + + /** + * ### .equal(value) + * + * Asserts that the target is strictly equal (`===`) to `value`. + * Alternately, if the `deep` flag is set, asserts that + * the target is deeply equal to `value`. + * + * expect('hello').to.equal('hello'); + * expect(42).to.equal(42); + * expect(1).to.not.equal(true); + * expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' }); + * expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' }); + * + * @name equal + * @alias equals + * @alias eq + * @alias deep.equal + * @param {Mixed} value + * @param {String} message _optional_ + * @api public + */ + + function assertEqual (val, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'deep')) { + return this.eql(val); + } else { + this.assert( + val === obj + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{exp}' + , val + , this._obj + , true + ); + } + } + + Assertion.addMethod('equal', assertEqual); + Assertion.addMethod('equals', assertEqual); + Assertion.addMethod('eq', assertEqual); + + /** + * ### .eql(value) + * + * Asserts that the target is deeply equal to `value`. + * + * expect({ foo: 'bar' }).to.eql({ foo: 'bar' }); + * expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]); + * + * @name eql + * @alias eqls + * @param {Mixed} value + * @param {String} message _optional_ + * @api public + */ + + function assertEql(obj, msg) { + if (msg) flag(this, 'message', msg); + this.assert( + _.eql(obj, flag(this, 'object')) + , 'expected #{this} to deeply equal #{exp}' + , 'expected #{this} to not deeply equal #{exp}' + , obj + , this._obj + , true + ); + } + + Assertion.addMethod('eql', assertEql); + Assertion.addMethod('eqls', assertEql); + + /** + * ### .above(value) + * + * Asserts that the target is greater than `value`. + * + * expect(10).to.be.above(5); + * + * Can also be used in conjunction with `length` to + * assert a minimum length. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.above(2); + * expect([ 1, 2, 3 ]).to.have.length.above(2); + * + * @name above + * @alias gt + * @alias greaterThan + * @param {Number} value + * @param {String} message _optional_ + * @api public + */ + + function assertAbove (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len > n + , 'expected #{this} to have a length above #{exp} but got #{act}' + , 'expected #{this} to not have a length above #{exp}' + , n + , len + ); + } else { + this.assert( + obj > n + , 'expected #{this} to be above ' + n + , 'expected #{this} to be at most ' + n + ); + } + } + + Assertion.addMethod('above', assertAbove); + Assertion.addMethod('gt', assertAbove); + Assertion.addMethod('greaterThan', assertAbove); + + /** + * ### .least(value) + * + * Asserts that the target is greater than or equal to `value`. + * + * expect(10).to.be.at.least(10); + * + * Can also be used in conjunction with `length` to + * assert a minimum length. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.of.at.least(2); + * expect([ 1, 2, 3 ]).to.have.length.of.at.least(3); + * + * @name least + * @alias gte + * @param {Number} value + * @param {String} message _optional_ + * @api public + */ + + function assertLeast (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len >= n + , 'expected #{this} to have a length at least #{exp} but got #{act}' + , 'expected #{this} to have a length below #{exp}' + , n + , len + ); + } else { + this.assert( + obj >= n + , 'expected #{this} to be at least ' + n + , 'expected #{this} to be below ' + n + ); + } + } + + Assertion.addMethod('least', assertLeast); + Assertion.addMethod('gte', assertLeast); + + /** + * ### .below(value) + * + * Asserts that the target is less than `value`. + * + * expect(5).to.be.below(10); + * + * Can also be used in conjunction with `length` to + * assert a maximum length. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.below(4); + * expect([ 1, 2, 3 ]).to.have.length.below(4); + * + * @name below + * @alias lt + * @alias lessThan + * @param {Number} value + * @param {String} message _optional_ + * @api public + */ + + function assertBelow (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len < n + , 'expected #{this} to have a length below #{exp} but got #{act}' + , 'expected #{this} to not have a length below #{exp}' + , n + , len + ); + } else { + this.assert( + obj < n + , 'expected #{this} to be below ' + n + , 'expected #{this} to be at least ' + n + ); + } + } + + Assertion.addMethod('below', assertBelow); + Assertion.addMethod('lt', assertBelow); + Assertion.addMethod('lessThan', assertBelow); + + /** + * ### .most(value) + * + * Asserts that the target is less than or equal to `value`. + * + * expect(5).to.be.at.most(5); + * + * Can also be used in conjunction with `length` to + * assert a maximum length. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.of.at.most(4); + * expect([ 1, 2, 3 ]).to.have.length.of.at.most(3); + * + * @name most + * @alias lte + * @param {Number} value + * @param {String} message _optional_ + * @api public + */ + + function assertMost (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len <= n + , 'expected #{this} to have a length at most #{exp} but got #{act}' + , 'expected #{this} to have a length above #{exp}' + , n + , len + ); + } else { + this.assert( + obj <= n + , 'expected #{this} to be at most ' + n + , 'expected #{this} to be above ' + n + ); + } + } + + Assertion.addMethod('most', assertMost); + Assertion.addMethod('lte', assertMost); + + /** + * ### .within(start, finish) + * + * Asserts that the target is within a range. + * + * expect(7).to.be.within(5,10); + * + * Can also be used in conjunction with `length` to + * assert a length range. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.within(2,4); + * expect([ 1, 2, 3 ]).to.have.length.within(2,4); + * + * @name within + * @param {Number} start lowerbound inclusive + * @param {Number} finish upperbound inclusive + * @param {String} message _optional_ + * @api public + */ + + Assertion.addMethod('within', function (start, finish, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , range = start + '..' + finish; + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len >= start && len <= finish + , 'expected #{this} to have a length within ' + range + , 'expected #{this} to not have a length within ' + range + ); + } else { + this.assert( + obj >= start && obj <= finish + , 'expected #{this} to be within ' + range + , 'expected #{this} to not be within ' + range + ); + } + }); + + /** + * ### .instanceof(constructor) + * + * Asserts that the target is an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , Chai = new Tea('chai'); + * + * expect(Chai).to.be.an.instanceof(Tea); + * expect([ 1, 2, 3 ]).to.be.instanceof(Array); + * + * @name instanceof + * @param {Constructor} constructor + * @param {String} message _optional_ + * @alias instanceOf + * @api public + */ + + function assertInstanceOf (constructor, msg) { + if (msg) flag(this, 'message', msg); + var name = _.getName(constructor); + this.assert( + flag(this, 'object') instanceof constructor + , 'expected #{this} to be an instance of ' + name + , 'expected #{this} to not be an instance of ' + name + ); + }; + + Assertion.addMethod('instanceof', assertInstanceOf); + Assertion.addMethod('instanceOf', assertInstanceOf); + + /** + * ### .property(name, [value]) + * + * Asserts that the target has a property `name`, optionally asserting that + * the value of that property is strictly equal to `value`. + * If the `deep` flag is set, you can use dot- and bracket-notation for deep + * references into objects and arrays. + * + * // simple referencing + * var obj = { foo: 'bar' }; + * expect(obj).to.have.property('foo'); + * expect(obj).to.have.property('foo', 'bar'); + * + * // deep referencing + * var deepObj = { + * green: { tea: 'matcha' } + * , teas: [ 'chai', 'matcha', { tea: 'konacha' } ] + * }; + + * expect(deepObj).to.have.deep.property('green.tea', 'matcha'); + * expect(deepObj).to.have.deep.property('teas[1]', 'matcha'); + * expect(deepObj).to.have.deep.property('teas[2].tea', 'konacha'); + * + * You can also use an array as the starting point of a `deep.property` + * assertion, or traverse nested arrays. + * + * var arr = [ + * [ 'chai', 'matcha', 'konacha' ] + * , [ { tea: 'chai' } + * , { tea: 'matcha' } + * , { tea: 'konacha' } ] + * ]; + * + * expect(arr).to.have.deep.property('[0][1]', 'matcha'); + * expect(arr).to.have.deep.property('[1][2].tea', 'konacha'); + * + * Furthermore, `property` changes the subject of the assertion + * to be the value of that property from the original object. This + * permits for further chainable assertions on that property. + * + * expect(obj).to.have.property('foo') + * .that.is.a('string'); + * expect(deepObj).to.have.property('green') + * .that.is.an('object') + * .that.deep.equals({ tea: 'matcha' }); + * expect(deepObj).to.have.property('teas') + * .that.is.an('array') + * .with.deep.property('[2]') + * .that.deep.equals({ tea: 'konacha' }); + * + * @name property + * @alias deep.property + * @param {String} name + * @param {Mixed} value (optional) + * @param {String} message _optional_ + * @returns value of property for chaining + * @api public + */ + + Assertion.addMethod('property', function (name, val, msg) { + if (msg) flag(this, 'message', msg); + + var isDeep = !!flag(this, 'deep') + , descriptor = isDeep ? 'deep property ' : 'property ' + , negate = flag(this, 'negate') + , obj = flag(this, 'object') + , pathInfo = isDeep ? _.getPathInfo(name, obj) : null + , hasProperty = isDeep + ? pathInfo.exists + : _.hasProperty(name, obj) + , value = isDeep + ? pathInfo.value + : obj[name]; + + if (negate && undefined !== val) { + if (undefined === value) { + msg = (msg != null) ? msg + ': ' : ''; + throw new Error(msg + _.inspect(obj) + ' has no ' + descriptor + _.inspect(name)); + } + } else { + this.assert( + hasProperty + , 'expected #{this} to have a ' + descriptor + _.inspect(name) + , 'expected #{this} to not have ' + descriptor + _.inspect(name)); + } + + if (undefined !== val) { + this.assert( + val === value + , 'expected #{this} to have a ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' + , 'expected #{this} to not have a ' + descriptor + _.inspect(name) + ' of #{act}' + , val + , value + ); + } + + flag(this, 'object', value); + }); + + + /** + * ### .ownProperty(name) + * + * Asserts that the target has an own property `name`. + * + * expect('test').to.have.ownProperty('length'); + * + * @name ownProperty + * @alias haveOwnProperty + * @param {String} name + * @param {String} message _optional_ + * @api public + */ + + function assertOwnProperty (name, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + this.assert( + obj.hasOwnProperty(name) + , 'expected #{this} to have own property ' + _.inspect(name) + , 'expected #{this} to not have own property ' + _.inspect(name) + ); + } + + Assertion.addMethod('ownProperty', assertOwnProperty); + Assertion.addMethod('haveOwnProperty', assertOwnProperty); + + /** + * ### .length(value) + * + * Asserts that the target's `length` property has + * the expected value. + * + * expect([ 1, 2, 3]).to.have.length(3); + * expect('foobar').to.have.length(6); + * + * Can also be used as a chain precursor to a value + * comparison for the length property. + * + * expect('foo').to.have.length.above(2); + * expect([ 1, 2, 3 ]).to.have.length.above(2); + * expect('foo').to.have.length.below(4); + * expect([ 1, 2, 3 ]).to.have.length.below(4); + * expect('foo').to.have.length.within(2,4); + * expect([ 1, 2, 3 ]).to.have.length.within(2,4); + * + * @name length + * @alias lengthOf + * @param {Number} length + * @param {String} message _optional_ + * @api public + */ + + function assertLengthChain () { + flag(this, 'doLength', true); + } + + function assertLength (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + + this.assert( + len == n + , 'expected #{this} to have a length of #{exp} but got #{act}' + , 'expected #{this} to not have a length of #{act}' + , n + , len + ); + } + + Assertion.addChainableMethod('length', assertLength, assertLengthChain); + Assertion.addMethod('lengthOf', assertLength); + + /** + * ### .match(regexp) + * + * Asserts that the target matches a regular expression. + * + * expect('foobar').to.match(/^foo/); + * + * @name match + * @param {RegExp} RegularExpression + * @param {String} message _optional_ + * @api public + */ + + Assertion.addMethod('match', function (re, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + this.assert( + re.exec(obj) + , 'expected #{this} to match ' + re + , 'expected #{this} not to match ' + re + ); + }); + + /** + * ### .string(string) + * + * Asserts that the string target contains another string. + * + * expect('foobar').to.have.string('bar'); + * + * @name string + * @param {String} string + * @param {String} message _optional_ + * @api public + */ + + Assertion.addMethod('string', function (str, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + new Assertion(obj, msg).is.a('string'); + + this.assert( + ~obj.indexOf(str) + , 'expected #{this} to contain ' + _.inspect(str) + , 'expected #{this} to not contain ' + _.inspect(str) + ); + }); + + + /** + * ### .keys(key1, [key2], [...]) + * + * Asserts that the target contains any or all of the passed-in keys. + * Use in combination with `any`, `all`, `contains`, or `have` will affect + * what will pass. + * + * When used in conjunction with `any`, at least one key that is passed + * in must exist in the target object. This is regardless whether or not + * the `have` or `contain` qualifiers are used. Note, either `any` or `all` + * should be used in the assertion. If neither are used, the assertion is + * defaulted to `all`. + * + * When both `all` and `contain` are used, the target object must have at + * least all of the passed-in keys but may have more keys not listed. + * + * When both `all` and `have` are used, the target object must both contain + * all of the passed-in keys AND the number of keys in the target object must + * match the number of keys passed in (in other words, a target object must + * have all and only all of the passed-in keys). + * + * expect({ foo: 1, bar: 2 }).to.have.any.keys('foo', 'baz'); + * expect({ foo: 1, bar: 2 }).to.have.any.keys('foo'); + * expect({ foo: 1, bar: 2 }).to.contain.any.keys('bar', 'baz'); + * expect({ foo: 1, bar: 2 }).to.contain.any.keys(['foo']); + * expect({ foo: 1, bar: 2 }).to.contain.any.keys({'foo': 6}); + * expect({ foo: 1, bar: 2 }).to.have.all.keys(['bar', 'foo']); + * expect({ foo: 1, bar: 2 }).to.have.all.keys({'bar': 6, 'foo', 7}); + * expect({ foo: 1, bar: 2, baz: 3 }).to.contain.all.keys(['bar', 'foo']); + * expect({ foo: 1, bar: 2, baz: 3 }).to.contain.all.keys([{'bar': 6}}]); + * + * + * @name keys + * @alias key + * @param {String...|Array|Object} keys + * @api public + */ + + function assertKeys (keys) { + var obj = flag(this, 'object') + , str + , ok = true + , | 5,332 | set up mocha tests | 0 | .js | 2 | mit | muicss/loadjs |
10067577 | <NME> chai-3.2.0.js <BEF> ADDFILE <MSG> set up mocha tests <DFF> @@ -0,0 +1,5332 @@ + +;(function(){ + +/** + * Require the module at `name`. + * + * @param {String} name + * @return {Object} exports + * @api public + */ + +function require(name) { + var module = require.modules[name]; + if (!module) throw new Error('failed to require "' + name + '"'); + + if (!('exports' in module) && typeof module.definition === 'function') { + module.client = module.component = true; + module.definition.call(this, module.exports = {}, module); + delete module.definition; + } + + return module.exports; +} + +/** + * Meta info, accessible in the global scope unless you use AMD option. + */ + +require.loader = 'component'; + +/** + * Internal helper object, contains a sorting function for semantiv versioning + */ +require.helper = {}; +require.helper.semVerSort = function(a, b) { + var aArray = a.version.split('.'); + var bArray = b.version.split('.'); + for (var i=0; i<aArray.length; ++i) { + var aInt = parseInt(aArray[i], 10); + var bInt = parseInt(bArray[i], 10); + if (aInt === bInt) { + var aLex = aArray[i].substr((""+aInt).length); + var bLex = bArray[i].substr((""+bInt).length); + if (aLex === '' && bLex !== '') return 1; + if (aLex !== '' && bLex === '') return -1; + if (aLex !== '' && bLex !== '') return aLex > bLex ? 1 : -1; + continue; + } else if (aInt > bInt) { + return 1; + } else { + return -1; + } + } + return 0; +} + +/** + * Find and require a module which name starts with the provided name. + * If multiple modules exists, the highest semver is used. + * This function can only be used for remote dependencies. + + * @param {String} name - module name: `user~repo` + * @param {Boolean} returnPath - returns the canonical require path if true, + * otherwise it returns the epxorted module + */ +require.latest = function (name, returnPath) { + function showError(name) { + throw new Error('failed to find latest module of "' + name + '"'); + } + // only remotes with semvers, ignore local files conataining a '/' + var versionRegexp = /(.*)~(.*)@v?(\d+\.\d+\.\d+[^\/]*)$/; + var remoteRegexp = /(.*)~(.*)/; + if (!remoteRegexp.test(name)) showError(name); + var moduleNames = Object.keys(require.modules); + var semVerCandidates = []; + var otherCandidates = []; // for instance: name of the git branch + for (var i=0; i<moduleNames.length; i++) { + var moduleName = moduleNames[i]; + if (new RegExp(name + '@').test(moduleName)) { + var version = moduleName.substr(name.length+1); + var semVerMatch = versionRegexp.exec(moduleName); + if (semVerMatch != null) { + semVerCandidates.push({version: version, name: moduleName}); + } else { + otherCandidates.push({version: version, name: moduleName}); + } + } + } + if (semVerCandidates.concat(otherCandidates).length === 0) { + showError(name); + } + if (semVerCandidates.length > 0) { + var module = semVerCandidates.sort(require.helper.semVerSort).pop().name; + if (returnPath === true) { + return module; + } + return require(module); + } + // if the build contains more than one branch of the same module + // you should not use this funciton + var module = otherCandidates.sort(function(a, b) {return a.name > b.name})[0].name; + if (returnPath === true) { + return module; + } + return require(module); +} + +/** + * Registered modules. + */ + +require.modules = {}; + +/** + * Register module at `name` with callback `definition`. + * + * @param {String} name + * @param {Function} definition + * @api private + */ + +require.register = function (name, definition) { + require.modules[name] = { + definition: definition + }; +}; + +/** + * Define a module's exports immediately with `exports`. + * + * @param {String} name + * @param {Generic} exports + * @api private + */ + +require.define = function (name, exports) { + require.modules[name] = { + exports: exports + }; +}; +require.register("[email protected]", function (exports, module) { +/*! + * assertion-error + * Copyright(c) 2013 Jake Luer <[email protected]> + * MIT Licensed + */ + +/*! + * Return a function that will copy properties from + * one object to another excluding any originally + * listed. Returned function will create a new `{}`. + * + * @param {String} excluded properties ... + * @return {Function} + */ + +function exclude () { + var excludes = [].slice.call(arguments); + + function excludeProps (res, obj) { + Object.keys(obj).forEach(function (key) { + if (!~excludes.indexOf(key)) res[key] = obj[key]; + }); + } + + return function extendExclude () { + var args = [].slice.call(arguments) + , i = 0 + , res = {}; + + for (; i < args.length; i++) { + excludeProps(res, args[i]); + } + + return res; + }; +}; + +/*! + * Primary Exports + */ + +module.exports = AssertionError; + +/** + * ### AssertionError + * + * An extension of the JavaScript `Error` constructor for + * assertion and validation scenarios. + * + * @param {String} message + * @param {Object} properties to include (optional) + * @param {callee} start stack function (optional) + */ + +function AssertionError (message, _props, ssf) { + var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON') + , props = extend(_props || {}); + + // default values + this.message = message || 'Unspecified AssertionError'; + this.showDiff = false; + + // copy from properties + for (var key in props) { + this[key] = props[key]; + } + + // capture stack trace + ssf = ssf || arguments.callee; + if (ssf && Error.captureStackTrace) { + Error.captureStackTrace(this, ssf); + } +} + +/*! + * Inherit from Error.prototype + */ + +AssertionError.prototype = Object.create(Error.prototype); + +/*! + * Statically set name + */ + +AssertionError.prototype.name = 'AssertionError'; + +/*! + * Ensure correct constructor + */ + +AssertionError.prototype.constructor = AssertionError; + +/** + * Allow errors to be converted to JSON for static transfer. + * + * @param {Boolean} include stack (default: `true`) + * @return {Object} object that can be `JSON.stringify` + */ + +AssertionError.prototype.toJSON = function (stack) { + var extend = exclude('constructor', 'toJSON', 'stack') + , props = extend({ name: this.name }, this); + + // include stack if exists and not turned off + if (false !== stack && this.stack) { + props.stack = this.stack; + } + + return props; +}; + +}); + +require.register("[email protected]", function (exports, module) { +/*! + * type-detect + * Copyright(c) 2013 jake luer <[email protected]> + * MIT Licensed + */ + +/*! + * Primary Exports + */ + +var exports = module.exports = getType; + +/*! + * Detectable javascript natives + */ + +var natives = { + '[object Array]': 'array' + , '[object RegExp]': 'regexp' + , '[object Function]': 'function' + , '[object Arguments]': 'arguments' + , '[object Date]': 'date' +}; + +/** + * ### typeOf (obj) + * + * Use several different techniques to determine + * the type of object being tested. + * + * + * @param {Mixed} object + * @return {String} object type + * @api public + */ + +function getType (obj) { + var str = Object.prototype.toString.call(obj); + if (natives[str]) return natives[str]; + if (obj === null) return 'null'; + if (obj === undefined) return 'undefined'; + if (obj === Object(obj)) return 'object'; + return typeof obj; +} + +exports.Library = Library; + +/** + * ### Library + * + * Create a repository for custom type detection. + * + * ```js + * var lib = new type.Library; + * ``` + * + */ + +function Library () { + this.tests = {}; +} + +/** + * #### .of (obj) + * + * Expose replacement `typeof` detection to the library. + * + * ```js + * if ('string' === lib.of('hello world')) { + * // ... + * } + * ``` + * + * @param {Mixed} object to test + * @return {String} type + */ + +Library.prototype.of = getType; + +/** + * #### .define (type, test) + * + * Add a test to for the `.test()` assertion. + * + * Can be defined as a regular expression: + * + * ```js + * lib.define('int', /^[0-9]+$/); + * ``` + * + * ... or as a function: + * + * ```js + * lib.define('bln', function (obj) { + * if ('boolean' === lib.of(obj)) return true; + * var blns = [ 'yes', 'no', 'true', 'false', 1, 0 ]; + * if ('string' === lib.of(obj)) obj = obj.toLowerCase(); + * return !! ~blns.indexOf(obj); + * }); + * ``` + * + * @param {String} type + * @param {RegExp|Function} test + * @api public + */ + +Library.prototype.define = function (type, test) { + if (arguments.length === 1) return this.tests[type]; + this.tests[type] = test; + return this; +}; + +/** + * #### .test (obj, test) + * + * Assert that an object is of type. Will first + * check natives, and if that does not pass it will + * use the user defined custom tests. + * + * ```js + * assert(lib.test('1', 'int')); + * assert(lib.test('yes', 'bln')); + * ``` + * + * @param {Mixed} object + * @param {String} type + * @return {Boolean} result + * @api public + */ + +Library.prototype.test = function (obj, type) { + if (type === getType(obj)) return true; + var test = this.tests[type]; + + if (test && 'regexp' === getType(test)) { + return test.test(obj); + } else if (test && 'function' === getType(test)) { + return test(obj); + } else { + throw new ReferenceError('Type test "' + type + '" not defined or invalid.'); + } +}; + +}); + +require.register("[email protected]", function (exports, module) { +/*! + * deep-eql + * Copyright(c) 2013 Jake Luer <[email protected]> + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var type = require('[email protected]'); + +/*! + * Buffer.isBuffer browser shim + */ + +var Buffer; +try { Buffer = require('buffer').Buffer; } +catch(ex) { + Buffer = {}; + Buffer.isBuffer = function() { return false; } +} + +/*! + * Primary Export + */ + +module.exports = deepEqual; + +/** + * Assert super-strict (egal) equality between + * two objects of any type. + * + * @param {Mixed} a + * @param {Mixed} b + * @param {Array} memoised (optional) + * @return {Boolean} equal match + */ + +function deepEqual(a, b, m) { + if (sameValue(a, b)) { + return true; + } else if ('date' === type(a)) { + return dateEqual(a, b); + } else if ('regexp' === type(a)) { + return regexpEqual(a, b); + } else if (Buffer.isBuffer(a)) { + return bufferEqual(a, b); + } else if ('arguments' === type(a)) { + return argumentsEqual(a, b, m); + } else if (!typeEqual(a, b)) { + return false; + } else if (('object' !== type(a) && 'object' !== type(b)) + && ('array' !== type(a) && 'array' !== type(b))) { + return sameValue(a, b); + } else { + return objectEqual(a, b, m); + } +} + +/*! + * Strict (egal) equality test. Ensures that NaN always + * equals NaN and `-0` does not equal `+0`. + * + * @param {Mixed} a + * @param {Mixed} b + * @return {Boolean} equal match + */ + +function sameValue(a, b) { + if (a === b) return a !== 0 || 1 / a === 1 / b; + return a !== a && b !== b; +} + +/*! + * Compare the types of two given objects and + * return if they are equal. Note that an Array + * has a type of `array` (not `object`) and arguments + * have a type of `arguments` (not `array`/`object`). + * + * @param {Mixed} a + * @param {Mixed} b + * @return {Boolean} result + */ + +function typeEqual(a, b) { + return type(a) === type(b); +} + +/*! + * Compare two Date objects by asserting that + * the time values are equal using `saveValue`. + * + * @param {Date} a + * @param {Date} b + * @return {Boolean} result + */ + +function dateEqual(a, b) { + if ('date' !== type(b)) return false; + return sameValue(a.getTime(), b.getTime()); +} + +/*! + * Compare two regular expressions by converting them + * to string and checking for `sameValue`. + * + * @param {RegExp} a + * @param {RegExp} b + * @return {Boolean} result + */ + +function regexpEqual(a, b) { + if ('regexp' !== type(b)) return false; + return sameValue(a.toString(), b.toString()); +} + +/*! + * Assert deep equality of two `arguments` objects. + * Unfortunately, these must be sliced to arrays + * prior to test to ensure no bad behavior. + * + * @param {Arguments} a + * @param {Arguments} b + * @param {Array} memoize (optional) + * @return {Boolean} result + */ + +function argumentsEqual(a, b, m) { + if ('arguments' !== type(b)) return false; + a = [].slice.call(a); + b = [].slice.call(b); + return deepEqual(a, b, m); +} + +/*! + * Get enumerable properties of a given object. + * + * @param {Object} a + * @return {Array} property names + */ + +function enumerable(a) { + var res = []; + for (var key in a) res.push(key); + return res; +} + +/*! + * Simple equality for flat iterable objects + * such as Arrays or Node.js buffers. + * + * @param {Iterable} a + * @param {Iterable} b + * @return {Boolean} result + */ + +function iterableEqual(a, b) { + if (a.length !== b.length) return false; + + var i = 0; + var match = true; + + for (; i < a.length; i++) { + if (a[i] !== b[i]) { + match = false; + break; + } + } + + return match; +} + +/*! + * Extension to `iterableEqual` specifically + * for Node.js Buffers. + * + * @param {Buffer} a + * @param {Mixed} b + * @return {Boolean} result + */ + +function bufferEqual(a, b) { + if (!Buffer.isBuffer(b)) return false; + return iterableEqual(a, b); +} + +/*! + * Block for `objectEqual` ensuring non-existing + * values don't get in. + * + * @param {Mixed} object + * @return {Boolean} result + */ + +function isValue(a) { + return a !== null && a !== undefined; +} + +/*! + * Recursively check the equality of two objects. + * Once basic sameness has been established it will + * defer to `deepEqual` for each enumerable key + * in the object. + * + * @param {Mixed} a + * @param {Mixed} b + * @return {Boolean} result + */ + +function objectEqual(a, b, m) { + if (!isValue(a) || !isValue(b)) { + return false; + } + + if (a.prototype !== b.prototype) { + return false; + } + + var i; + if (m) { + for (i = 0; i < m.length; i++) { + if ((m[i][0] === a && m[i][1] === b) + || (m[i][0] === b && m[i][1] === a)) { + return true; + } + } + } else { + m = []; + } + + try { + var ka = enumerable(a); + var kb = enumerable(b); + } catch (ex) { + return false; + } + + ka.sort(); + kb.sort(); + + if (!iterableEqual(ka, kb)) { + return false; + } + + m.push([ a, b ]); + + var key; + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!deepEqual(a[key], b[key], m)) { + return false; + } + } + + return true; +} + +}); + +require.register("chai", function (exports, module) { +module.exports = require('chai/lib/chai.js'); + +}); + +require.register("chai/lib/chai.js", function (exports, module) { +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer <[email protected]> + * MIT Licensed + */ + +var used = [] + , exports = module.exports = {}; + +/*! + * Chai version + */ + +exports.version = '2.1.0'; + +/*! + * Assertion Error + */ + +exports.AssertionError = require('[email protected]'); + +/*! + * Utils for plugins (not exported) + */ + +var util = require('chai/lib/chai/utils/index.js'); + +/** + * # .use(function) + * + * Provides a way to extend the internals of Chai + * + * @param {Function} + * @returns {this} for chaining + * @api public + */ + +exports.use = function (fn) { + if (!~used.indexOf(fn)) { + fn(this, util); + used.push(fn); + } + + return this; +}; + +/*! + * Utility Functions + */ + +exports.util = util; + +/*! + * Configuration + */ + +var config = require('chai/lib/chai/config.js'); +exports.config = config; + +/*! + * Primary `Assertion` prototype + */ + +var assertion = require('chai/lib/chai/assertion.js'); +exports.use(assertion); + +/*! + * Core Assertions + */ + +var core = require('chai/lib/chai/core/assertions.js'); +exports.use(core); + +/*! + * Expect interface + */ + +var expect = require('chai/lib/chai/interface/expect.js'); +exports.use(expect); + +/*! + * Should interface + */ + +var should = require('chai/lib/chai/interface/should.js'); +exports.use(should); + +/*! + * Assert interface + */ + +var assert = require('chai/lib/chai/interface/assert.js'); +exports.use(assert); + +}); + +require.register("chai/lib/chai/assertion.js", function (exports, module) { +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer <[email protected]> + * MIT Licensed + */ + +var config = require('chai/lib/chai/config.js'); + +module.exports = function (_chai, util) { + /*! + * Module dependencies. + */ + + var AssertionError = _chai.AssertionError + , flag = util.flag; + + /*! + * Module export. + */ + + _chai.Assertion = Assertion; + + /*! + * Assertion Constructor + * + * Creates object for chaining. + * + * @api private + */ + + function Assertion (obj, msg, stack) { + flag(this, 'ssfi', stack || arguments.callee); + flag(this, 'object', obj); + flag(this, 'message', msg); + } + + Object.defineProperty(Assertion, 'includeStack', { + get: function() { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + return config.includeStack; + }, + set: function(value) { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + config.includeStack = value; + } + }); + + Object.defineProperty(Assertion, 'showDiff', { + get: function() { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + return config.showDiff; + }, + set: function(value) { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + config.showDiff = value; + } + }); + + Assertion.addProperty = function (name, fn) { + util.addProperty(this.prototype, name, fn); + }; + + Assertion.addMethod = function (name, fn) { + util.addMethod(this.prototype, name, fn); + }; + + Assertion.addChainableMethod = function (name, fn, chainingBehavior) { + util.addChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + Assertion.overwriteProperty = function (name, fn) { + util.overwriteProperty(this.prototype, name, fn); + }; + + Assertion.overwriteMethod = function (name, fn) { + util.overwriteMethod(this.prototype, name, fn); + }; + + Assertion.overwriteChainableMethod = function (name, fn, chainingBehavior) { + util.overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + /*! + * ### .assert(expression, message, negateMessage, expected, actual) + * + * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. + * + * @name assert + * @param {Philosophical} expression to be tested + * @param {String or Function} message or function that returns message to display if fails + * @param {String or Function} negatedMessage or function that returns negatedMessage to display if negated expression fails + * @param {Mixed} expected value (remember to check for negation) + * @param {Mixed} actual (optional) will default to `this.obj` + * @api private + */ + + Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { + var ok = util.test(this, arguments); + if (true !== showDiff) showDiff = false; + if (true !== config.showDiff) showDiff = false; + + if (!ok) { + var msg = util.getMessage(this, arguments) + , actual = util.getActual(this, arguments); + throw new AssertionError(msg, { + actual: actual + , expected: expected + , showDiff: showDiff + }, (config.includeStack) ? this.assert : flag(this, 'ssfi')); + } + }; + + /*! + * ### ._obj + * + * Quick reference to stored `actual` value for plugin developers. + * + * @api private + */ + + Object.defineProperty(Assertion.prototype, '_obj', + { get: function () { + return flag(this, 'object'); + } + , set: function (val) { + flag(this, 'object', val); + } + }); +}; + +}); + +require.register("chai/lib/chai/config.js", function (exports, module) { +module.exports = { + + /** + * ### config.includeStack + * + * User configurable property, influences whether stack trace + * is included in Assertion error message. Default of false + * suppresses stack trace in the error message. + * + * chai.config.includeStack = true; // enable stack on error + * + * @param {Boolean} + * @api public + */ + + includeStack: false, + + /** + * ### config.showDiff + * + * User configurable property, influences whether or not + * the `showDiff` flag should be included in the thrown + * AssertionErrors. `false` will always be `false`; `true` + * will be true when the assertion has requested a diff + * be shown. + * + * @param {Boolean} + * @api public + */ + + showDiff: true, + + /** + * ### config.truncateThreshold + * + * User configurable property, sets length threshold for actual and + * expected values in assertion errors. If this threshold is exceeded, + * the value is truncated. + * + * Set it to zero if you want to disable truncating altogether. + * + * chai.config.truncateThreshold = 0; // disable truncating + * + * @param {Number} + * @api public + */ + + truncateThreshold: 40 + +}; + +}); + +require.register("chai/lib/chai/core/assertions.js", function (exports, module) { +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer <[email protected]> + * MIT Licensed + */ + +module.exports = function (chai, _) { + var Assertion = chai.Assertion + , toString = Object.prototype.toString + , flag = _.flag; + + /** + * ### Language Chains + * + * The following are provided as chainable getters to + * improve the readability of your assertions. They + * do not provide testing capabilities unless they + * have been overwritten by a plugin. + * + * **Chains** + * + * - to + * - be + * - been + * - is + * - that + * - which + * - and + * - has + * - have + * - with + * - at + * - of + * - same + * + * @name language chains + * @api public + */ + + [ 'to', 'be', 'been' + , 'is', 'and', 'has', 'have' + , 'with', 'that', 'which', 'at' + , 'of', 'same' ].forEach(function (chain) { + Assertion.addProperty(chain, function () { + return this; + }); + }); + + /** + * ### .not + * + * Negates any of assertions following in the chain. + * + * expect(foo).to.not.equal('bar'); + * expect(goodFn).to.not.throw(Error); + * expect({ foo: 'baz' }).to.have.property('foo') + * .and.not.equal('bar'); + * + * @name not + * @api public + */ + + Assertion.addProperty('not', function () { + flag(this, 'negate', true); + }); + + /** + * ### .deep + * + * Sets the `deep` flag, later used by the `equal` and + * `property` assertions. + * + * expect(foo).to.deep.equal({ bar: 'baz' }); + * expect({ foo: { bar: { baz: 'quux' } } }) + * .to.have.deep.property('foo.bar.baz', 'quux'); + * + * @name deep + * @api public + */ + + Assertion.addProperty('deep', function () { + flag(this, 'deep', true); + }); + + /** + * ### .any + * + * Sets the `any` flag, (opposite of the `all` flag) + * later used in the `keys` assertion. + * + * expect(foo).to.have.any.keys('bar', 'baz'); + * + * @name any + * @api public + */ + + Assertion.addProperty('any', function () { + flag(this, 'any', true); + flag(this, 'all', false) + }); + + + /** + * ### .all + * + * Sets the `all` flag (opposite of the `any` flag) + * later used by the `keys` assertion. + * + * expect(foo).to.have.all.keys('bar', 'baz'); + * + * @name all + * @api public + */ + + Assertion.addProperty('all', function () { + flag(this, 'all', true); + flag(this, 'any', false); + }); + + /** + * ### .a(type) + * + * The `a` and `an` assertions are aliases that can be + * used either as language chains or to assert a value's + * type. + * + * // typeof + * expect('test').to.be.a('string'); + * expect({ foo: 'bar' }).to.be.an('object'); + * expect(null).to.be.a('null'); + * expect(undefined).to.be.an('undefined'); + * + * // language chain + * expect(foo).to.be.an.instanceof(Foo); + * + * @name a + * @alias an + * @param {String} type + * @param {String} message _optional_ + * @api public + */ + + function an (type, msg) { + if (msg) flag(this, 'message', msg); + type = type.toLowerCase(); + var obj = flag(this, 'object') + , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; + + this.assert( + type === _.type(obj) + , 'expected #{this} to be ' + article + type + , 'expected #{this} not to be ' + article + type + ); + } + + Assertion.addChainableMethod('an', an); + Assertion.addChainableMethod('a', an); + + /** + * ### .include(value) + * + * The `include` and `contain` assertions can be used as either property + * based language chains or as methods to assert the inclusion of an object + * in an array or a substring in a string. When used as language chains, + * they toggle the `contains` flag for the `keys` assertion. + * + * expect([1,2,3]).to.include(2); + * expect('foobar').to.contain('foo'); + * expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo'); + * + * @name include + * @alias contain + * @alias includes + * @alias contains + * @param {Object|String|Number} obj + * @param {String} message _optional_ + * @api public + */ + + function includeChainingBehavior () { + flag(this, 'contains', true); + } + + function include (val, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var expected = false; + if (_.type(obj) === 'array' && _.type(val) === 'object') { + for (var i in obj) { + if (_.eql(obj[i], val)) { + expected = true; + break; + } + } + } else if (_.type(val) === 'object') { + if (!flag(this, 'negate')) { + for (var k in val) new Assertion(obj).property(k, val[k]); + return; + } + var subset = {}; + for (var k in val) subset[k] = obj[k]; + expected = _.eql(subset, val); + } else { + expected = obj && ~obj.indexOf(val); + } + this.assert( + expected + , 'expected #{this} to include ' + _.inspect(val) + , 'expected #{this} to not include ' + _.inspect(val)); + } + + Assertion.addChainableMethod('include', include, includeChainingBehavior); + Assertion.addChainableMethod('contain', include, includeChainingBehavior); + Assertion.addChainableMethod('contains', include, includeChainingBehavior); + Assertion.addChainableMethod('includes', include, includeChainingBehavior); + + /** + * ### .ok + * + * Asserts that the target is truthy. + * + * expect('everthing').to.be.ok; + * expect(1).to.be.ok; + * expect(false).to.not.be.ok; + * expect(undefined).to.not.be.ok; + * expect(null).to.not.be.ok; + * + * @name ok + * @api public + */ + + Assertion.addProperty('ok', function () { + this.assert( + flag(this, 'object') + , 'expected #{this} to be truthy' + , 'expected #{this} to be falsy'); + }); + + /** + * ### .true + * + * Asserts that the target is `true`. + * + * expect(true).to.be.true; + * expect(1).to.not.be.true; + * + * @name true + * @api public + */ + + Assertion.addProperty('true', function () { + this.assert( + true === flag(this, 'object') + , 'expected #{this} to be true' + , 'expected #{this} to be false' + , this.negate ? false : true + ); + }); + + /** + * ### .false + * + * Asserts that the target is `false`. + * + * expect(false).to.be.false; + * expect(0).to.not.be.false; + * + * @name false + * @api public + */ + + Assertion.addProperty('false', function () { + this.assert( + false === flag(this, 'object') + , 'expected #{this} to be false' + , 'expected #{this} to be true' + , this.negate ? true : false + ); + }); + + /** + * ### .null + * + * Asserts that the target is `null`. + * + * expect(null).to.be.null; + * expect(undefined).not.to.be.null; + * + * @name null + * @api public + */ + + Assertion.addProperty('null', function () { + this.assert( + null === flag(this, 'object') + , 'expected #{this} to be null' + , 'expected #{this} not to be null' + ); + }); + + /** + * ### .undefined + * + * Asserts that the target is `undefined`. + * + * expect(undefined).to.be.undefined; + * expect(null).to.not.be.undefined; + * + * @name undefined + * @api public + */ + + Assertion.addProperty('undefined', function () { + this.assert( + undefined === flag(this, 'object') + , 'expected #{this} to be undefined' + , 'expected #{this} not to be undefined' + ); + }); + + /** + * ### .exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi' + * , bar = null + * , baz; + * + * expect(foo).to.exist; + * expect(bar).to.not.exist; + * expect(baz).to.not.exist; + * + * @name exist + * @api public + */ + + Assertion.addProperty('exist', function () { + this.assert( + null != flag(this, 'object') + , 'expected #{this} to exist' + , 'expected #{this} to not exist' + ); + }); + + + /** + * ### .empty + * + * Asserts that the target's length is `0`. For arrays, it checks + * the `length` property. For objects, it gets the count of + * enumerable keys. + * + * expect([]).to.be.empty; + * expect('').to.be.empty; + * expect({}).to.be.empty; + * + * @name empty + * @api public + */ + + Assertion.addProperty('empty', function () { + var obj = flag(this, 'object') + , expected = obj; + + if (Array.isArray(obj) || 'string' === typeof object) { + expected = obj.length; + } else if (typeof obj === 'object') { + expected = Object.keys(obj).length; + } + + this.assert( + !expected + , 'expected #{this} to be empty' + , 'expected #{this} not to be empty' + ); + }); + + /** + * ### .arguments + * + * Asserts that the target is an arguments object. + * + * function test () { + * expect(arguments).to.be.arguments; + * } + * + * @name arguments + * @alias Arguments + * @api public + */ + + function checkArguments () { + var obj = flag(this, 'object') + , type = Object.prototype.toString.call(obj); + this.assert( + '[object Arguments]' === type + , 'expected #{this} to be arguments but got ' + type + , 'expected #{this} to not be arguments' + ); + } + + Assertion.addProperty('arguments', checkArguments); + Assertion.addProperty('Arguments', checkArguments); + + /** + * ### .equal(value) + * + * Asserts that the target is strictly equal (`===`) to `value`. + * Alternately, if the `deep` flag is set, asserts that + * the target is deeply equal to `value`. + * + * expect('hello').to.equal('hello'); + * expect(42).to.equal(42); + * expect(1).to.not.equal(true); + * expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' }); + * expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' }); + * + * @name equal + * @alias equals + * @alias eq + * @alias deep.equal + * @param {Mixed} value + * @param {String} message _optional_ + * @api public + */ + + function assertEqual (val, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'deep')) { + return this.eql(val); + } else { + this.assert( + val === obj + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{exp}' + , val + , this._obj + , true + ); + } + } + + Assertion.addMethod('equal', assertEqual); + Assertion.addMethod('equals', assertEqual); + Assertion.addMethod('eq', assertEqual); + + /** + * ### .eql(value) + * + * Asserts that the target is deeply equal to `value`. + * + * expect({ foo: 'bar' }).to.eql({ foo: 'bar' }); + * expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]); + * + * @name eql + * @alias eqls + * @param {Mixed} value + * @param {String} message _optional_ + * @api public + */ + + function assertEql(obj, msg) { + if (msg) flag(this, 'message', msg); + this.assert( + _.eql(obj, flag(this, 'object')) + , 'expected #{this} to deeply equal #{exp}' + , 'expected #{this} to not deeply equal #{exp}' + , obj + , this._obj + , true + ); + } + + Assertion.addMethod('eql', assertEql); + Assertion.addMethod('eqls', assertEql); + + /** + * ### .above(value) + * + * Asserts that the target is greater than `value`. + * + * expect(10).to.be.above(5); + * + * Can also be used in conjunction with `length` to + * assert a minimum length. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.above(2); + * expect([ 1, 2, 3 ]).to.have.length.above(2); + * + * @name above + * @alias gt + * @alias greaterThan + * @param {Number} value + * @param {String} message _optional_ + * @api public + */ + + function assertAbove (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len > n + , 'expected #{this} to have a length above #{exp} but got #{act}' + , 'expected #{this} to not have a length above #{exp}' + , n + , len + ); + } else { + this.assert( + obj > n + , 'expected #{this} to be above ' + n + , 'expected #{this} to be at most ' + n + ); + } + } + + Assertion.addMethod('above', assertAbove); + Assertion.addMethod('gt', assertAbove); + Assertion.addMethod('greaterThan', assertAbove); + + /** + * ### .least(value) + * + * Asserts that the target is greater than or equal to `value`. + * + * expect(10).to.be.at.least(10); + * + * Can also be used in conjunction with `length` to + * assert a minimum length. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.of.at.least(2); + * expect([ 1, 2, 3 ]).to.have.length.of.at.least(3); + * + * @name least + * @alias gte + * @param {Number} value + * @param {String} message _optional_ + * @api public + */ + + function assertLeast (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len >= n + , 'expected #{this} to have a length at least #{exp} but got #{act}' + , 'expected #{this} to have a length below #{exp}' + , n + , len + ); + } else { + this.assert( + obj >= n + , 'expected #{this} to be at least ' + n + , 'expected #{this} to be below ' + n + ); + } + } + + Assertion.addMethod('least', assertLeast); + Assertion.addMethod('gte', assertLeast); + + /** + * ### .below(value) + * + * Asserts that the target is less than `value`. + * + * expect(5).to.be.below(10); + * + * Can also be used in conjunction with `length` to + * assert a maximum length. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.below(4); + * expect([ 1, 2, 3 ]).to.have.length.below(4); + * + * @name below + * @alias lt + * @alias lessThan + * @param {Number} value + * @param {String} message _optional_ + * @api public + */ + + function assertBelow (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len < n + , 'expected #{this} to have a length below #{exp} but got #{act}' + , 'expected #{this} to not have a length below #{exp}' + , n + , len + ); + } else { + this.assert( + obj < n + , 'expected #{this} to be below ' + n + , 'expected #{this} to be at least ' + n + ); + } + } + + Assertion.addMethod('below', assertBelow); + Assertion.addMethod('lt', assertBelow); + Assertion.addMethod('lessThan', assertBelow); + + /** + * ### .most(value) + * + * Asserts that the target is less than or equal to `value`. + * + * expect(5).to.be.at.most(5); + * + * Can also be used in conjunction with `length` to + * assert a maximum length. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.of.at.most(4); + * expect([ 1, 2, 3 ]).to.have.length.of.at.most(3); + * + * @name most + * @alias lte + * @param {Number} value + * @param {String} message _optional_ + * @api public + */ + + function assertMost (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len <= n + , 'expected #{this} to have a length at most #{exp} but got #{act}' + , 'expected #{this} to have a length above #{exp}' + , n + , len + ); + } else { + this.assert( + obj <= n + , 'expected #{this} to be at most ' + n + , 'expected #{this} to be above ' + n + ); + } + } + + Assertion.addMethod('most', assertMost); + Assertion.addMethod('lte', assertMost); + + /** + * ### .within(start, finish) + * + * Asserts that the target is within a range. + * + * expect(7).to.be.within(5,10); + * + * Can also be used in conjunction with `length` to + * assert a length range. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.within(2,4); + * expect([ 1, 2, 3 ]).to.have.length.within(2,4); + * + * @name within + * @param {Number} start lowerbound inclusive + * @param {Number} finish upperbound inclusive + * @param {String} message _optional_ + * @api public + */ + + Assertion.addMethod('within', function (start, finish, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , range = start + '..' + finish; + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len >= start && len <= finish + , 'expected #{this} to have a length within ' + range + , 'expected #{this} to not have a length within ' + range + ); + } else { + this.assert( + obj >= start && obj <= finish + , 'expected #{this} to be within ' + range + , 'expected #{this} to not be within ' + range + ); + } + }); + + /** + * ### .instanceof(constructor) + * + * Asserts that the target is an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , Chai = new Tea('chai'); + * + * expect(Chai).to.be.an.instanceof(Tea); + * expect([ 1, 2, 3 ]).to.be.instanceof(Array); + * + * @name instanceof + * @param {Constructor} constructor + * @param {String} message _optional_ + * @alias instanceOf + * @api public + */ + + function assertInstanceOf (constructor, msg) { + if (msg) flag(this, 'message', msg); + var name = _.getName(constructor); + this.assert( + flag(this, 'object') instanceof constructor + , 'expected #{this} to be an instance of ' + name + , 'expected #{this} to not be an instance of ' + name + ); + }; + + Assertion.addMethod('instanceof', assertInstanceOf); + Assertion.addMethod('instanceOf', assertInstanceOf); + + /** + * ### .property(name, [value]) + * + * Asserts that the target has a property `name`, optionally asserting that + * the value of that property is strictly equal to `value`. + * If the `deep` flag is set, you can use dot- and bracket-notation for deep + * references into objects and arrays. + * + * // simple referencing + * var obj = { foo: 'bar' }; + * expect(obj).to.have.property('foo'); + * expect(obj).to.have.property('foo', 'bar'); + * + * // deep referencing + * var deepObj = { + * green: { tea: 'matcha' } + * , teas: [ 'chai', 'matcha', { tea: 'konacha' } ] + * }; + + * expect(deepObj).to.have.deep.property('green.tea', 'matcha'); + * expect(deepObj).to.have.deep.property('teas[1]', 'matcha'); + * expect(deepObj).to.have.deep.property('teas[2].tea', 'konacha'); + * + * You can also use an array as the starting point of a `deep.property` + * assertion, or traverse nested arrays. + * + * var arr = [ + * [ 'chai', 'matcha', 'konacha' ] + * , [ { tea: 'chai' } + * , { tea: 'matcha' } + * , { tea: 'konacha' } ] + * ]; + * + * expect(arr).to.have.deep.property('[0][1]', 'matcha'); + * expect(arr).to.have.deep.property('[1][2].tea', 'konacha'); + * + * Furthermore, `property` changes the subject of the assertion + * to be the value of that property from the original object. This + * permits for further chainable assertions on that property. + * + * expect(obj).to.have.property('foo') + * .that.is.a('string'); + * expect(deepObj).to.have.property('green') + * .that.is.an('object') + * .that.deep.equals({ tea: 'matcha' }); + * expect(deepObj).to.have.property('teas') + * .that.is.an('array') + * .with.deep.property('[2]') + * .that.deep.equals({ tea: 'konacha' }); + * + * @name property + * @alias deep.property + * @param {String} name + * @param {Mixed} value (optional) + * @param {String} message _optional_ + * @returns value of property for chaining + * @api public + */ + + Assertion.addMethod('property', function (name, val, msg) { + if (msg) flag(this, 'message', msg); + + var isDeep = !!flag(this, 'deep') + , descriptor = isDeep ? 'deep property ' : 'property ' + , negate = flag(this, 'negate') + , obj = flag(this, 'object') + , pathInfo = isDeep ? _.getPathInfo(name, obj) : null + , hasProperty = isDeep + ? pathInfo.exists + : _.hasProperty(name, obj) + , value = isDeep + ? pathInfo.value + : obj[name]; + + if (negate && undefined !== val) { + if (undefined === value) { + msg = (msg != null) ? msg + ': ' : ''; + throw new Error(msg + _.inspect(obj) + ' has no ' + descriptor + _.inspect(name)); + } + } else { + this.assert( + hasProperty + , 'expected #{this} to have a ' + descriptor + _.inspect(name) + , 'expected #{this} to not have ' + descriptor + _.inspect(name)); + } + + if (undefined !== val) { + this.assert( + val === value + , 'expected #{this} to have a ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' + , 'expected #{this} to not have a ' + descriptor + _.inspect(name) + ' of #{act}' + , val + , value + ); + } + + flag(this, 'object', value); + }); + + + /** + * ### .ownProperty(name) + * + * Asserts that the target has an own property `name`. + * + * expect('test').to.have.ownProperty('length'); + * + * @name ownProperty + * @alias haveOwnProperty + * @param {String} name + * @param {String} message _optional_ + * @api public + */ + + function assertOwnProperty (name, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + this.assert( + obj.hasOwnProperty(name) + , 'expected #{this} to have own property ' + _.inspect(name) + , 'expected #{this} to not have own property ' + _.inspect(name) + ); + } + + Assertion.addMethod('ownProperty', assertOwnProperty); + Assertion.addMethod('haveOwnProperty', assertOwnProperty); + + /** + * ### .length(value) + * + * Asserts that the target's `length` property has + * the expected value. + * + * expect([ 1, 2, 3]).to.have.length(3); + * expect('foobar').to.have.length(6); + * + * Can also be used as a chain precursor to a value + * comparison for the length property. + * + * expect('foo').to.have.length.above(2); + * expect([ 1, 2, 3 ]).to.have.length.above(2); + * expect('foo').to.have.length.below(4); + * expect([ 1, 2, 3 ]).to.have.length.below(4); + * expect('foo').to.have.length.within(2,4); + * expect([ 1, 2, 3 ]).to.have.length.within(2,4); + * + * @name length + * @alias lengthOf + * @param {Number} length + * @param {String} message _optional_ + * @api public + */ + + function assertLengthChain () { + flag(this, 'doLength', true); + } + + function assertLength (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + + this.assert( + len == n + , 'expected #{this} to have a length of #{exp} but got #{act}' + , 'expected #{this} to not have a length of #{act}' + , n + , len + ); + } + + Assertion.addChainableMethod('length', assertLength, assertLengthChain); + Assertion.addMethod('lengthOf', assertLength); + + /** + * ### .match(regexp) + * + * Asserts that the target matches a regular expression. + * + * expect('foobar').to.match(/^foo/); + * + * @name match + * @param {RegExp} RegularExpression + * @param {String} message _optional_ + * @api public + */ + + Assertion.addMethod('match', function (re, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + this.assert( + re.exec(obj) + , 'expected #{this} to match ' + re + , 'expected #{this} not to match ' + re + ); + }); + + /** + * ### .string(string) + * + * Asserts that the string target contains another string. + * + * expect('foobar').to.have.string('bar'); + * + * @name string + * @param {String} string + * @param {String} message _optional_ + * @api public + */ + + Assertion.addMethod('string', function (str, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + new Assertion(obj, msg).is.a('string'); + + this.assert( + ~obj.indexOf(str) + , 'expected #{this} to contain ' + _.inspect(str) + , 'expected #{this} to not contain ' + _.inspect(str) + ); + }); + + + /** + * ### .keys(key1, [key2], [...]) + * + * Asserts that the target contains any or all of the passed-in keys. + * Use in combination with `any`, `all`, `contains`, or `have` will affect + * what will pass. + * + * When used in conjunction with `any`, at least one key that is passed + * in must exist in the target object. This is regardless whether or not + * the `have` or `contain` qualifiers are used. Note, either `any` or `all` + * should be used in the assertion. If neither are used, the assertion is + * defaulted to `all`. + * + * When both `all` and `contain` are used, the target object must have at + * least all of the passed-in keys but may have more keys not listed. + * + * When both `all` and `have` are used, the target object must both contain + * all of the passed-in keys AND the number of keys in the target object must + * match the number of keys passed in (in other words, a target object must + * have all and only all of the passed-in keys). + * + * expect({ foo: 1, bar: 2 }).to.have.any.keys('foo', 'baz'); + * expect({ foo: 1, bar: 2 }).to.have.any.keys('foo'); + * expect({ foo: 1, bar: 2 }).to.contain.any.keys('bar', 'baz'); + * expect({ foo: 1, bar: 2 }).to.contain.any.keys(['foo']); + * expect({ foo: 1, bar: 2 }).to.contain.any.keys({'foo': 6}); + * expect({ foo: 1, bar: 2 }).to.have.all.keys(['bar', 'foo']); + * expect({ foo: 1, bar: 2 }).to.have.all.keys({'bar': 6, 'foo', 7}); + * expect({ foo: 1, bar: 2, baz: 3 }).to.contain.all.keys(['bar', 'foo']); + * expect({ foo: 1, bar: 2, baz: 3 }).to.contain.all.keys([{'bar': 6}}]); + * + * + * @name keys + * @alias key + * @param {String...|Array|Object} keys + * @api public + */ + + function assertKeys (keys) { + var obj = flag(this, 'object') + , str + , ok = true + , | 5,332 | set up mocha tests | 0 | .js | 2 | mit | muicss/loadjs |
10067578 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067579 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067580 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067581 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067582 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067583 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067584 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067585 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067586 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067587 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067588 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067589 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067590 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067591 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067592 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<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> embed search panel icons.
<DFF> @@ -8,6 +8,20 @@
<EmbeddedResource Include="**\*.xshd;**\*.resx;**\*.xaml;Assets\*;**\*.paml" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Search\Assets\FindNext.png" />
+ <None Remove="Search\Assets\FindPrevious.png" />
+ <None Remove="Search\Assets\ReplaceAll.png" />
+ <None Remove="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Search\Assets\FindNext.png" />
+ <EmbeddedResource Include="Search\Assets\FindPrevious.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
+ <EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
| 14 | embed search panel icons. | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067593 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067594 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067595 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067596 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067597 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067598 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067599 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067600 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067601 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067602 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067603 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067604 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067605 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067606 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067607 | <NME> SearchCommands.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Threading;
using AvaloniaEdit.Editing;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Search commands for AvalonEdit.
/// </summary>
public static class SearchCommands
{
/// <summary>
/// Finds the next occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3));
/// <summary>
/// Finds the previous occurrence in the file.
/// </summary>
public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift));
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape));
/// <summary>
/// Replaces the next occurrence in the document.
/// </summary>
public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt));
/// <summary>
/// Replaces all the occurrences in the document.
/// </summary>
public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt));
}
/// <summary>
/// TextAreaInputHandler that registers all search-related commands.
/// </summary>
internal class SearchInputHandler : TextAreaInputHandler
{
public SearchInputHandler(TextArea textArea, SearchPanel panel)
: base(textArea)
{
RegisterCommands(CommandBindings);
_panel = panel;
}
internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
}
private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel));
commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
}
private readonly SearchPanel _panel;
private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: false);
}
private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e)
{
FindOrReplace(isReplaceMode: true);
}
private void FindOrReplace(bool isReplaceMode)
{
_panel.IsReplaceMode = isReplaceMode;
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
{
if (_panel.IsClosed)
{
e.CanExecute = false;
// Continue routing so that the key gesture can be consumed by another component.
//e.ContinueRouting = true;
}
else
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindNext();
e.Handled = true;
}
}
private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.FindPrevious();
e.Handled = true;
}
}
private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceNext();
e.Handled = true;
}
}
private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.ReplaceAll();
e.Handled = true;
}
}
private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
{
if (!_panel.IsClosed)
{
_panel.Close();
e.Handled = true;
}
}
/// <summary>
/// Fired when SearchOptions are modified inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged
{
add => _panel.SearchOptionsChanged += value;
remove => _panel.SearchOptionsChanged -= value;
}
}
}
<MSG> Merge branch 'master' into fix-scroll
<DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search
_panel.Open();
if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
_panel.SearchPattern = TextArea.Selection.GetText();
- Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input);
+ Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input);
}
private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
| 1 | Merge branch 'master' into fix-scroll | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067608 | <NME> README.md
<BEF> # FruitMachine [](https://travis-ci.com/ftlabs/fruitmachine) [](https://coveralls.io/r/ftlabs/fruitmachine)
A lightweight component layout engine for client and server.
FruitMachine is designed to build rich interactive layouts from modular, reusable components. It's light and unopinionated so that it can be applied to almost any layout problem. FruitMachine is currently powering the [FT Web App](http://apps.ft.com/ftwebapp/).
```js
// Define a module
var Apple = fruitmachine.define({
name: 'apple',
template: function(){ return 'hello' }
});
// Create a module
var apple = new Apple();
// Render it
apple.render();
apple.el.outerHTML;
//=> <div class="apple">hello</div>
```
## Installation
```
$ npm install fruitmachine
```
or
```
$ bower install fruitmachine
```
or
Download the [pre-built version][built] (~2k gzipped).
[built]: http://wzrd.in/standalone/fruitmachine@latest
## Examples
- [Article viewer](http://ftlabs.github.io/fruitmachine/examples/article-viewer/)
- [TODO](http://ftlabs.github.io/fruitmachine/examples/todo/)
## Documentation
- [Introduction](docs/introduction.md)
- [Getting started](docs/getting-started.md)
- [Defining modules](docs/defining-modules.md)
- [Slots](docs/slots.md)
- [View assembly](docs/layout-assembly.md)
- [Instantiation](docs/module-instantiation.md)
- [Templates](docs/templates.md)
- [Template markup](docs/template-markup.md)
- [Rendering](docs/rendering.md)
- [DOM injection](docs/injection.md)
- [The module element](docs/module-el.md)
- [Queries](docs/queries.md)
- [Helpers](docs/module-helpers.md)
- [Removing & destroying](docs/removing-and-destroying.md)
- [Extending](docs/extending-modules.md)
- [Server-side rendering](docs/server-side-rendering.md)
- [API](docs/api.md)
- [Events](docs/events.md)
## Tests
#### With PhantomJS
```
$ npm install
$ npm test
```
#### Without PhantomJS
```
$ node_modules/.bin/buster-static
```
...then visit http://localhost:8282/ in browser
## Author
- **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage)
## Contributors
- **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage)
- **Matt Andrews** - [@matthew-andrews](http://github.com/matthew-andrews)
## License
Copyright (c) 2018 The Financial Times Limited
Licensed under the MIT license.
## Credits and collaboration
FruitMachine is largely unmaintained/finished. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request.
Your custom `destroy` method is
called and a `destroy` event is fired.
Options:
- `fromDOM` Whether the view should be removed from DOM (default `true`)
<MSG> New build
<DFF> @@ -266,6 +266,9 @@ 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`)
| 3 | New build | 0 | .md | md | mit | ftlabs/fruitmachine |
10067609 | <NME> module.appendTo.js
<BEF> ADDFILE
<MSG> Add second param for appendTo to specify sibling
<DFF> @@ -0,0 +1,50 @@
+
+buster.testCase('View#appendTo()', {
+ setUp: helpers.createView,
+
+ "Should append the view element as a child of the given element.": function() {
+ var sandbox = document.createElement('div');
+
+ this.view
+ .render()
+ .appendTo(sandbox);
+
+ assert.equals(this.view.el, sandbox.firstElementChild);
+ },
+
+ "Should not destroy existing element contents.": function() {
+ var sandbox = document.createElement('div'),
+ existing = document.createElement('div');
+
+ sandbox.appendChild(existing);
+
+ this.view
+ .render()
+ .appendTo(sandbox);
+
+ assert.equals(existing, sandbox.firstElementChild);
+ assert.equals(this.view.el, sandbox.lastElementChild);
+ },
+
+ "Should insert before specified element.": function() {
+ var sandbox = document.createElement('div'),
+ existing1 = document.createElement('div'),
+ existing2 = document.createElement('div');
+
+ sandbox.appendChild(existing1);
+ sandbox.appendChild(existing2);
+
+ this.view
+ .render()
+ .appendTo(sandbox, existing2);
+
+ assert.equals(existing1, sandbox.firstElementChild);
+ assert.equals(this.view.el, existing1.nextSibling);
+ assert.equals(existing2, this.view.el.nextSibling);
+ },
+
+ tearDown: function() {
+ helpers.emptySandbox();
+ helpers.destroyView.call(this);
+ }
+});
\ No newline at end of file
| 50 | Add second param for appendTo to specify sibling | 0 | .js | appendTo | mit | ftlabs/fruitmachine |
10067610 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067611 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067612 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067613 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067614 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067615 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067616 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067617 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067618 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067619 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067620 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067621 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067622 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067623 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067624 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,7 +1,4 @@
# AvaloniaEdit
-[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
-[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
-
This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia).
| 0 | Update README.md | 3 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10067625 | <NME> fruitmachine.js
<BEF> /*jslint browser:true, node:true*/
/**
* FruitMachine
*
* Renders layouts/modules from a basic layout definition.
* If views require custom interactions devs can extend
* the basic functionality.
*
* @version 0.3.3
* @copyright The Financial Times Limited [All Rights Reserved]
* @author Wilson Page <[email protected]>
*/
'use strict';
/**
* Module Dependencies
*/
var mod = require('./module');
var define = require('./define');
var utils = require('utils');
var events = require('evt');
/**
* Creates a fruitmachine
*
* Options:
*
(function() {
'use strict';
/**
* VIEW
*/
}
options = options || {};
if (options.module) return create(options);
this._configure(options);
this.add(options.views || this.views);
this.onInitialize(options);
};
// Current Version
FruitMachine.VERSION = '0.0.1';
// Global data store
var store = {
modules: {},
templates: {},
helpers: {}
};
// Utilities
var util = FruitMachine.util = {
return events(fm);
};
}())
};
// Create local references to some methods
var slice = Array.prototype.slice;
var concat = Array.prototype.concat;
var has = Object.prototype.hasOwnProperty;
var mixin = util.mixin;
var splitter = /\s+/;
var Events = FruitMachine.Events = {
}
};
FruitMachine.helper = function(name, helper) {
store.helpers[name] = helper(FruitMachine);
};
var getTemplate = function(module) {
return store.templates[module];
};
/**
* Registers templates, or overwrites
* the `getTemplate` method with a
* custom template getter function.
*
* @param {Object|Function} templates
* @return void
*/
FruitMachine.templates = function(templates) {
var type = typeof templates;
if ('object' === type) mixin(store.templates, templates);
else if ('function' === type) getTemplate = templates;
};
// Manages helpers
}
};
// Factory method
function create(options) {
var Module = store.modules[options.module] || FruitMachine;
options._module = options.module;
return new Module(options);
}
// Extend the prototype
mixin(FruitMachine.prototype, Events, {
_configure: function(options) {
this.module = this.module || options._module;
this._lookup = {};
this._views = [];
//this._data = options.data || {};
this.model = options.model || new Model(options.data || {});
// Use the template defined on
// the custom view, or use the
// template getter.
this.template = this.template || getTemplate(this.module);
// Upgrade helpers
add: function(views, options) {
var at = options && options.at;
var insert = options && options.insert;
var view;
if (!views) return;
// We append the child to the parent view if there is a view
// element and the users hasn't flagged `append` false.
if (insert) this.insertChildEl(view.el(), options);
}
return this;
},
insertChildEl: function(el, options) {
var at = options && options.at;
var parent = this.el();
if (!el || !parent) return;
if (typeof at !== 'undefined') {
}
},
addLookup: function(view) {
this._lookup[view.id()] = view;
this._lookup[view.module] = this._lookup[view.module] || [];
this._lookup[view.module].push(view);
},
id: function(id) {
return id ? this._lookup[id] : this._id;
},
this._el = this.model = this.module = this._id = this._lookup = null;
},
remove: function() {
var el = this.el();
if (el && el.parentNode) el.parentNode.removeChild(el);
},
_detach: function(options) {
return this;
},
parentEl: function() {
var view = this.parent;
while (view && !view._el && view.parent) view = view.parent;
},
el: function() {
if (typeof document === 'undefined') return;
//var parentEl = this.parentEl();
//if (parentEl) parentEl.querySelector(this.fmid());
return this._el = (this._el || document.getElementById(this.fmid()));
},
/**
toNode: function() {
var el = document.createElement('div');
el.innerHTML = this.toHTML();
return el.firstElementChild;
},
inject: function(dest) {
*/
var Model = FruitMachine.Model = function(options) {
this._data = mixin({}, options);
};
mixin(Model.prototype, Events, {
get: function(key) {
set: function(key, value) {
var _key;
if ('string' === typeof key && value) {
_key = {};
_key[key] = value;
key = _key;
}
if ('object' === key) {
mixin(this._data, key);
this.trigger('change');
for (var prop in key) {
<MSG> Progress
<DFF> @@ -31,6 +31,19 @@
(function() {
'use strict';
+ // Create local references to some methods
+ var slice = Array.prototype.slice;
+ var concat = Array.prototype.concat;
+ var has = Object.prototype.hasOwnProperty;
+ var hasDom = (typeof document !== 'undefined');
+
+ // Global data store
+ var store = {
+ modules: {},
+ templates: {},
+ helpers: {}
+ };
+
/**
* VIEW
*/
@@ -39,20 +52,13 @@
options = options || {};
if (options.module) return create(options);
this._configure(options);
- this.add(options.views || this.views);
+ this.add(options.views);
this.onInitialize(options);
};
// Current Version
FruitMachine.VERSION = '0.0.1';
- // Global data store
- var store = {
- modules: {},
- templates: {},
- helpers: {}
- };
-
// Utilities
var util = FruitMachine.util = {
@@ -106,12 +112,13 @@
}())
};
- // Create local references to some methods
- var slice = Array.prototype.slice;
- var concat = Array.prototype.concat;
- var has = Object.prototype.hasOwnProperty;
+ // Alias frequently used utils
var mixin = util.mixin;
+ /**
+ * Events
+ */
+
var splitter = /\s+/;
var Events = FruitMachine.Events = {
@@ -209,28 +216,19 @@
}
};
-
- FruitMachine.helper = function(name, helper) {
- store.helpers[name] = helper(FruitMachine);
- };
-
-
- var getTemplate = function(module) {
- return store.templates[module];
- };
+ /**
+ * Helpers
+ */
/**
- * Registers templates, or overwrites
- * the `getTemplate` method with a
- * custom template getter function.
+ * Registers a helper
*
- * @param {Object|Function} templates
+ * @param {String} name
+ * @param {Function} helper
* @return void
*/
- FruitMachine.templates = function(templates) {
- var type = typeof templates;
- if ('object' === type) mixin(store.templates, templates);
- else if ('function' === type) getTemplate = templates;
+ FruitMachine.helper = function(name, helper) {
+ store.helpers[name] = helper(FruitMachine);
};
// Manages helpers
@@ -256,7 +254,49 @@
}
};
- // Factory method
+ /**
+ * Templates
+ */
+
+ /**
+ * Registers templates, or overwrites
+ * the `getTemplate` method with a
+ * custom template getter function.
+ *
+ * @param {Object|Function} templates
+ * @return void
+ */
+ FruitMachine.templates = function(templates) {
+ var type = typeof templates;
+ if ('object' === type) mixin(store.templates, templates);
+ else if ('function' === type) getTemplate = templates;
+ };
+
+ /**
+ * The default get template method
+ * if FruitMachine.template is passed
+ * a function, this gets overwritten
+ * by that.
+ *
+ * @param {String} module
+ * @return {Template}
+ */
+ var getTemplate = function(module) {
+ return store.templates[module];
+ };
+
+ /**
+ * Creates a new FruitMachine view
+ * using the options passed.
+ *
+ * If a module parameter is passed
+ * we attempt to find a registered
+ * module of that name to intantiate,
+ * else we use a default view instance.
+ *
+ * @param {Object} options
+ * @return {FruitMachine}
+ */
function create(options) {
var Module = store.modules[options.module] || FruitMachine;
options._module = options.module;
@@ -264,7 +304,7 @@
return new Module(options);
}
- // Extend the prototype
+ // Mixin Events and extend the prototype
mixin(FruitMachine.prototype, Events, {
_configure: function(options) {
@@ -273,12 +313,13 @@
this.module = this.module || options._module;
this._lookup = {};
this._views = [];
- //this._data = options.data || {};
+
+ // Use the model passed in, or create
+ // a model from the data passed in.
this.model = options.model || new Model(options.data || {});
- // Use the template defined on
- // the custom view, or use the
- // template getter.
+ // Use the template defined on the
+ // custom view, or use the template getter.
this.template = this.template || getTemplate(this.module);
// Upgrade helpers
@@ -292,7 +333,7 @@
add: function(views, options) {
var at = options && options.at;
- var insert = options && options.insert;
+ var inject = options && options.inject;
var view;
if (!views) return;
@@ -310,16 +351,21 @@
// We append the child to the parent view if there is a view
// element and the users hasn't flagged `append` false.
- if (insert) this.insertChildEl(view.el(), options);
+ if (inject) this.injectChildEl(view.el(), options);
}
return this;
},
- insertChildEl: function(el, options) {
+ addLookup: function(view) {
+ this._lookup[view.id()] = view;
+ this._lookup[view.module] = this._lookup[view.module] || [];
+ this._lookup[view.module].push(view);
+ },
+
+ injectChildEl: function(el, options) {
var at = options && options.at;
var parent = this.el();
-
if (!el || !parent) return;
if (typeof at !== 'undefined') {
@@ -329,12 +375,6 @@
}
},
- addLookup: function(view) {
- this._lookup[view.id()] = view;
- this._lookup[view.module] = this._lookup[view.module] || [];
- this._lookup[view.module].push(view);
- },
-
id: function(id) {
return id ? this._lookup[id] : this._id;
},
@@ -467,9 +507,16 @@
this._el = this.model = this.module = this._id = this._lookup = null;
},
+ /**
+ * Removes the View's element
+ * from the DOM.
+ *
+ * @return {FruitMachine}
+ */
remove: function() {
var el = this.el();
if (el && el.parentNode) el.parentNode.removeChild(el);
+ return this;
},
_detach: function(options) {
@@ -495,6 +542,7 @@
return this;
},
+ // @depricated?
parentEl: function() {
var view = this.parent;
while (view && !view._el && view.parent) view = view.parent;
@@ -502,10 +550,8 @@
},
el: function() {
- if (typeof document === 'undefined') return;
- //var parentEl = this.parentEl();
- //if (parentEl) parentEl.querySelector(this.fmid());
- return this._el = (this._el || document.getElementById(this.fmid()));
+ if (!hasDom) return;
+ return this._el = this._el || document.getElementById(this.fmid());
},
/**
@@ -578,7 +624,7 @@
toNode: function() {
var el = document.createElement('div');
el.innerHTML = this.toHTML();
- return el.firstElementChild;
+ return el.removeChild(el.firstElementChild);
},
inject: function(dest) {
@@ -612,9 +658,11 @@
*/
var Model = FruitMachine.Model = function(options) {
+ this.fmid = util.uniqueId('model');
this._data = mixin({}, options);
};
+ // Merge in Events and extend with:
mixin(Model.prototype, Events, {
get: function(key) {
@@ -624,13 +672,17 @@
set: function(key, value) {
var _key;
+ // If a string key is passed
+ // convert it to an object ready
+ // for the next step.
if ('string' === typeof key && value) {
_key = {};
_key[key] = value;
key = _key;
}
- if ('object' === key) {
+ // Merge the object into the data store
+ if ('object' === typeof key) {
mixin(this._data, key);
this.trigger('change');
for (var prop in key) {
| 103 | Progress | 51 | .js | js | mit | ftlabs/fruitmachine |
10067626 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067627 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067628 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067629 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067630 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067631 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067632 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067633 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067634 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067635 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067636 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067637 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067638 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067639 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067640 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.0-preview5</Version>
</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" />
</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> bump version.
<DFF> @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.0-preview5</Version>
+ <Version>0.10.0-preview6</Version>
</PropertyGroup>
<ItemGroup>
| 1 | bump version. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067641 | <NME> tests.js
<BEF> /**
* loadjs tests
* @module test/tests.js
*/
var pathsLoaded = null, // file register
testEl = null,
assert = chai.assert,
expect = chai.expect;
describe('LoadJS tests', function() {
beforeEach(function() {
// reset register
pathsLoaded = {};
});
// ==========================================================================
// JavaScript file loading tests
// ==========================================================================
describe('JavaScript file loading tests', function() {
it('should call success callback on valid path', function(done) {
loadjs(['assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
}
});
});
it('should call error callback on invalid path', function(done) {
loadjs(['assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should call before callback before embedding into document', function(done) {
var scriptTags = [];
loadjs(['assets/file1.js', 'assets/file2.js'], {
before: function(path, el) {
scriptTags.push({
path: path,
el: el
});
// add cross origin script for file2
if (path === 'assets/file2.js') {
el.crossOrigin = 'anonymous';
}
},
success: function() {
assert.equal(scriptTags[0].path, 'assets/file1.js');
assert.equal(scriptTags[1].path, 'assets/file2.js');
assert.equal(scriptTags[0].el.crossOrigin, undefined);
assert.equal(scriptTags[1].el.crossOrigin, 'anonymous');
done();
}
});
});
it('should bypass insertion if before returns `false`', function(done) {
loadjs(['assets/file1.js'], {
before: function(path, el) {
// append to body (instead of head)
document.body.appendChild(el);
// return `false` to bypass default DOM insertion
return false;
},
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
// verify that file was added to body
var els = document.body.querySelectorAll('script'),
el;
for (var i=0; i < els.length; i++) {
el = els[i];
if (el.src.indexOf('assets/file1.js') !== -1) done();
}
}
});
});
it('should call success callback on two valid paths', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should support async false', function(done) {
this.timeout(5000);
var numCompleted = 0,
numTests = 20,
paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js'];
// run tests sequentially
var testFn = function(paths) {
// add cache busters
var pathsUncached = paths.slice(0);
pathsUncached[0] += '?_=' + Math.random();
pathsUncached[1] += '?_=' + Math.random();
loadjs(pathsUncached, {
success: function() {
var f1 = paths[0].replace('assets/', '');
var f2 = paths[1].replace('assets/', '');
// check load order
assert.isTrue(pathsLoaded[f1]);
assert.isFalse(pathsLoaded[f2]);
// increment tests
numCompleted += 1;
if (numCompleted === numTests) {
// exit
done();
} else {
// reset register
pathsLoaded = {};
// run test again
paths.reverse();
testFn(paths);
}
},
async: false
});
};
// run tests
testFn(paths);
});
it('should support multiple tries', function(done) {
loadjs('assets/file-numretries.js', {
error: function() {
// check number of scripts in document
var selector = 'script[src="assets/file-numretries.js"]',
scripts = document.querySelectorAll(selector);
if (scripts.length === 2) done();
},
numRetries: 1
});
});
// Un-'x' this for testing ad blocked scripts.
// Ghostery: Disallow "Google Adservices"
// AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a
// custom filter under Options
//
xit('it should report ad blocked scripts as missing', function(done) {
var s1 = 'https://www.googletagservices.com/tag/js/gpt.js',
s2 = 'https://munchkin.marketo.net/munchkin-beta.js';
loadjs([s1, s2, 'assets/file1.js'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 2);
assert.equal(pathsNotFound[0], s1);
assert.equal(pathsNotFound[1], s2);
done();
}
});
});
});
// ==========================================================================
// CSS file loading tests
// ==========================================================================
describe('CSS file loading tests', function() {
before(function() {
// add test div to body for css tests
testEl = document.createElement('div');
testEl.className = 'test-div mui-container';
testEl.style.display = 'inline-block';
document.body.appendChild(testEl);
});
afterEach(function() {
var els = document.getElementsByTagName('link'),
i = els.length,
el;
// iteratete through stylesheets
while (i--) {
el = els[i];
// remove test stylesheets
if (el.href.indexOf('mocha.css') === -1) {
el.parentNode.removeChild(el);
}
}
});
it('should load one file', function(done) {
loadjs(['assets/file1.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/file1.css', 'assets/file2.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 200);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
done();
}
});
});
it('should support mix of css and js', function(done) {
loadjs(['assets/file1.css', 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should support forced "css!" files', function(done) {
loadjs(['css!assets/file1.css'], {
success: function() {
// loop through files
var els = document.getElementsByTagName('link'),
i = els.length,
el;
while (i--) {
if (els[i].href.indexOf('file1.css') !== -1) done();
}
}
});
});
it('should throw an error if bundle is already defined', function() {
// define bundle
loadjs(['assets/file1.js'], 'bundle3');
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'bundle3');
};
expect(fn).to.throw(Error, "LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle4', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
it('supports urls with query arguments and anchor tags', function(done) {
loadjs(['assets/file1.css?x=x#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
}
// define bundles
loadjs('assets/file1.js', 'bundle5');
loadjs('assets/file2.js', 'bundle6');
loadjs
.ready('bundle5', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
.ready('bundle6', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
it('should call error on missing external file', function(done) {
this.timeout(0);
it('should handle multiple dependencies', function(done) {
loadjs('assets/file1.js', 'bundle7');
loadjs('assets/file2.js', 'bundle8');
loadjs.ready(['bundle7', 'bundle8'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
}
});
});
it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle9');
loadjs('assets/file-doesntexist.js', 'bundle10');
loadjs.ready(['bundle9', 'bundle10'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle10');
done();
}
});
var imgs = document.getElementsByTagName('img');
it('should execute callbacks on .done()', function(done) {
// add handler
loadjs.ready('plugin1', {
success: function() {
done();
}
});
// execute done
loadjs.done('plugin1');
});
it('should execute callbacks created after .done()', function(done) {
// execute done
loadjs.done('plugin2');
// add handler
loadjs.ready('plugin2', {
success: function() {
done();
}
}
});
});
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle1');
// use 1 second delay to let files load
setTimeout(function() {
loadjs.ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
it('detects png|gif|jpg|svg|webp extensions', function(done) {
let files = [
'assets/flash.png',
'assets/flash.gif',
it('should allow bundle callbacks before definitions', function(done) {
// define callback
loadjs.ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
});
});
// use 1 second delay
setTimeout(function() {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle2');
}, 1000);
});
assertLoaded(src);
done();
}
});
});
loadjs(['assets/file1.js'], 'cleared');
};
expect(fn).not.to.throw(Error, "LoadJS");
});
});
});
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
var src = 'assets/flash.png';
src += '?' + Math.random();
src += '#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should support forced "img!" files', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
var src1 = 'assets/flash.png?' + Math.random(),
src2 = 'assets/flash-doesntexist.png?' + Math.random();
loadjs(['img!' + src1, 'img!' + src2], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assertLoaded(src1);
assertNotLoaded(src2);
done();
}
});
});
it('should support mix of img and js', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src, 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assertLoaded(src);
done();
}
});
});
it('should load external img files', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/mui-logo.png?';
src += Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/';
src += 'mui-logo-doesntexist.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assertNotLoaded(src);
done();
}
});
});
});
// ==========================================================================
// API tests
// ==========================================================================
describe('API tests', function() {
it('should throw an error if bundle is already defined', function() {
// define bundle
loadjs(['assets/file1.js'], 'bundle');
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'bundle');
};
expect(fn).to.throw("LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should chain loadjs object', function(done) {
function bothDone() {
if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done();
}
// define bundles
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs
.ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
.ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
}
});
});
it('should handle multiple dependencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file-doesntexist.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle2');
done();
}
});
});
it('should execute callbacks on .done()', function(done) {
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
// execute done
loadjs.done('plugin');
});
it('should execute callbacks created after .done()', function(done) {
// execute done
loadjs.done('plugin');
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
});
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
// use 1 second delay to let files load
setTimeout(function() {
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
}, 1000);
});
it('should allow bundle callbacks before definitions', function(done) {
// define callback
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
// use 1 second delay
setTimeout(function() {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
}, 1000);
});
it('should reset dependencies statuses', function() {
loadjs(['assets/file1.js'], 'cleared');
loadjs.reset();
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'cleared');
};
expect(fn).not.to.throw("LoadJS");
});
it('should indicate if bundle has already been defined', function() {
loadjs(['assets/file1/js'], 'bundle1');
assert.equal(loadjs.isDefined('bundle1'), true);
assert.equal(loadjs.isDefined('bundleXX'), false);
});
it('should accept success callback functions to loadjs()', function(done) {
loadjs('assets/file1.js', function() {
done();
});
});
it('should accept success callback functions to .ready()', function(done) {
loadjs.done('plugin');
loadjs.ready('plugin', function() {
done();
});
});
it('should return Promise object if returnPromise is true', function() {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
// verify that response object is a Promise
assert.equal(prom instanceof Promise, true);
});
it('Promise object should support resolutions', function(done) {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
prom.then(function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
});
});
it('Promise object should support rejections', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom.then(
function(){},
function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
);
});
it('Promise object should support catches', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom
.catch(function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
it('supports Promises and success callbacks', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
var prom = loadjs('assets/file1.js', {
success: completedFn,
returnPromise: true
});
prom.then(completedFn);
});
it('supports Promises and bundle ready events', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
loadjs('assets/file1.js', 'bundle1', {returnPromise: true})
.then(completedFn);
loadjs.ready('bundle1', completedFn);
});
});
});
<MSG> shaved off some bytes by throwing error string, updated tests and documentation
<DFF> @@ -14,6 +14,9 @@ describe('LoadJS tests', function() {
beforeEach(function() {
// reset register
pathsLoaded = {};
+
+ // reset loadjs dependencies
+ loadjs.reset();
});
// ==========================================================================
@@ -307,19 +310,19 @@ describe('LoadJS tests', function() {
it('should throw an error if bundle is already defined', function() {
// define bundle
- loadjs(['assets/file1.js'], 'bundle3');
+ loadjs(['assets/file1.js'], 'bundle');
// define bundle again
var fn = function() {
- loadjs(['assets/file1.js'], 'bundle3');
+ loadjs(['assets/file1.js'], 'bundle');
};
- expect(fn).to.throw(Error, "LoadJS");
+ expect(fn).to.throw("LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
- loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle4', {
+ loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
@@ -335,16 +338,16 @@ describe('LoadJS tests', function() {
}
// define bundles
- loadjs('assets/file1.js', 'bundle5');
- loadjs('assets/file2.js', 'bundle6');
+ loadjs('assets/file1.js', 'bundle1');
+ loadjs('assets/file2.js', 'bundle2');
loadjs
- .ready('bundle5', {
+ .ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
- .ready('bundle6', {
+ .ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
@@ -354,10 +357,10 @@ describe('LoadJS tests', function() {
it('should handle multiple dependencies', function(done) {
- loadjs('assets/file1.js', 'bundle7');
- loadjs('assets/file2.js', 'bundle8');
+ loadjs('assets/file1.js', 'bundle1');
+ loadjs('assets/file2.js', 'bundle2');
- loadjs.ready(['bundle7', 'bundle8'], {
+ loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
@@ -368,17 +371,17 @@ describe('LoadJS tests', function() {
it('should error on missing depdendencies', function(done) {
- loadjs('assets/file1.js', 'bundle9');
- loadjs('assets/file-doesntexist.js', 'bundle10');
+ loadjs('assets/file1.js', 'bundle1');
+ loadjs('assets/file-doesntexist.js', 'bundle2');
- loadjs.ready(['bundle9', 'bundle10'], {
+ loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
- assert.equal(depsNotFound[0], 'bundle10');
+ assert.equal(depsNotFound[0], 'bundle2');
done();
}
});
@@ -387,23 +390,23 @@ describe('LoadJS tests', function() {
it('should execute callbacks on .done()', function(done) {
// add handler
- loadjs.ready('plugin1', {
+ loadjs.ready('plugin', {
success: function() {
done();
}
});
// execute done
- loadjs.done('plugin1');
+ loadjs.done('plugin');
});
it('should execute callbacks created after .done()', function(done) {
// execute done
- loadjs.done('plugin2');
+ loadjs.done('plugin');
// add handler
- loadjs.ready('plugin2', {
+ loadjs.ready('plugin', {
success: function() {
done();
}
@@ -413,11 +416,11 @@ describe('LoadJS tests', function() {
it('should define bundles', function(done) {
// define bundle
- loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle1');
+ loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
// use 1 second delay to let files load
setTimeout(function() {
- loadjs.ready('bundle1', {
+ loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
@@ -430,7 +433,7 @@ describe('LoadJS tests', function() {
it('should allow bundle callbacks before definitions', function(done) {
// define callback
- loadjs.ready('bundle2', {
+ loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
@@ -440,7 +443,7 @@ describe('LoadJS tests', function() {
// use 1 second delay
setTimeout(function() {
- loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle2');
+ loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
}, 1000);
});
@@ -454,7 +457,7 @@ describe('LoadJS tests', function() {
loadjs(['assets/file1.js'], 'cleared');
};
- expect(fn).not.to.throw(Error, "LoadJS");
+ expect(fn).not.to.throw("LoadJS");
});
});
});
| 27 | shaved off some bytes by throwing error string, updated tests and documentation | 24 | .js | js | mit | muicss/loadjs |
10067642 | <NME> tests.js
<BEF> /**
* loadjs tests
* @module test/tests.js
*/
var pathsLoaded = null, // file register
testEl = null,
assert = chai.assert,
expect = chai.expect;
describe('LoadJS tests', function() {
beforeEach(function() {
// reset register
pathsLoaded = {};
});
// ==========================================================================
// JavaScript file loading tests
// ==========================================================================
describe('JavaScript file loading tests', function() {
it('should call success callback on valid path', function(done) {
loadjs(['assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
}
});
});
it('should call error callback on invalid path', function(done) {
loadjs(['assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should call before callback before embedding into document', function(done) {
var scriptTags = [];
loadjs(['assets/file1.js', 'assets/file2.js'], {
before: function(path, el) {
scriptTags.push({
path: path,
el: el
});
// add cross origin script for file2
if (path === 'assets/file2.js') {
el.crossOrigin = 'anonymous';
}
},
success: function() {
assert.equal(scriptTags[0].path, 'assets/file1.js');
assert.equal(scriptTags[1].path, 'assets/file2.js');
assert.equal(scriptTags[0].el.crossOrigin, undefined);
assert.equal(scriptTags[1].el.crossOrigin, 'anonymous');
done();
}
});
});
it('should bypass insertion if before returns `false`', function(done) {
loadjs(['assets/file1.js'], {
before: function(path, el) {
// append to body (instead of head)
document.body.appendChild(el);
// return `false` to bypass default DOM insertion
return false;
},
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
// verify that file was added to body
var els = document.body.querySelectorAll('script'),
el;
for (var i=0; i < els.length; i++) {
el = els[i];
if (el.src.indexOf('assets/file1.js') !== -1) done();
}
}
});
});
it('should call success callback on two valid paths', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should support async false', function(done) {
this.timeout(5000);
var numCompleted = 0,
numTests = 20,
paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js'];
// run tests sequentially
var testFn = function(paths) {
// add cache busters
var pathsUncached = paths.slice(0);
pathsUncached[0] += '?_=' + Math.random();
pathsUncached[1] += '?_=' + Math.random();
loadjs(pathsUncached, {
success: function() {
var f1 = paths[0].replace('assets/', '');
var f2 = paths[1].replace('assets/', '');
// check load order
assert.isTrue(pathsLoaded[f1]);
assert.isFalse(pathsLoaded[f2]);
// increment tests
numCompleted += 1;
if (numCompleted === numTests) {
// exit
done();
} else {
// reset register
pathsLoaded = {};
// run test again
paths.reverse();
testFn(paths);
}
},
async: false
});
};
// run tests
testFn(paths);
});
it('should support multiple tries', function(done) {
loadjs('assets/file-numretries.js', {
error: function() {
// check number of scripts in document
var selector = 'script[src="assets/file-numretries.js"]',
scripts = document.querySelectorAll(selector);
if (scripts.length === 2) done();
},
numRetries: 1
});
});
// Un-'x' this for testing ad blocked scripts.
// Ghostery: Disallow "Google Adservices"
// AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a
// custom filter under Options
//
xit('it should report ad blocked scripts as missing', function(done) {
var s1 = 'https://www.googletagservices.com/tag/js/gpt.js',
s2 = 'https://munchkin.marketo.net/munchkin-beta.js';
loadjs([s1, s2, 'assets/file1.js'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 2);
assert.equal(pathsNotFound[0], s1);
assert.equal(pathsNotFound[1], s2);
done();
}
});
});
});
// ==========================================================================
// CSS file loading tests
// ==========================================================================
describe('CSS file loading tests', function() {
before(function() {
// add test div to body for css tests
testEl = document.createElement('div');
testEl.className = 'test-div mui-container';
testEl.style.display = 'inline-block';
document.body.appendChild(testEl);
});
afterEach(function() {
var els = document.getElementsByTagName('link'),
i = els.length,
el;
// iteratete through stylesheets
while (i--) {
el = els[i];
// remove test stylesheets
if (el.href.indexOf('mocha.css') === -1) {
el.parentNode.removeChild(el);
}
}
});
it('should load one file', function(done) {
loadjs(['assets/file1.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/file1.css', 'assets/file2.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 200);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
done();
}
});
});
it('should support mix of css and js', function(done) {
loadjs(['assets/file1.css', 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should support forced "css!" files', function(done) {
loadjs(['css!assets/file1.css'], {
success: function() {
// loop through files
var els = document.getElementsByTagName('link'),
i = els.length,
el;
while (i--) {
if (els[i].href.indexOf('file1.css') !== -1) done();
}
}
});
});
it('should throw an error if bundle is already defined', function() {
// define bundle
loadjs(['assets/file1.js'], 'bundle3');
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'bundle3');
};
expect(fn).to.throw(Error, "LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle4', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
it('supports urls with query arguments and anchor tags', function(done) {
loadjs(['assets/file1.css?x=x#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
}
// define bundles
loadjs('assets/file1.js', 'bundle5');
loadjs('assets/file2.js', 'bundle6');
loadjs
.ready('bundle5', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
.ready('bundle6', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
it('should call error on missing external file', function(done) {
this.timeout(0);
it('should handle multiple dependencies', function(done) {
loadjs('assets/file1.js', 'bundle7');
loadjs('assets/file2.js', 'bundle8');
loadjs.ready(['bundle7', 'bundle8'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
}
});
});
it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle9');
loadjs('assets/file-doesntexist.js', 'bundle10');
loadjs.ready(['bundle9', 'bundle10'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle10');
done();
}
});
var imgs = document.getElementsByTagName('img');
it('should execute callbacks on .done()', function(done) {
// add handler
loadjs.ready('plugin1', {
success: function() {
done();
}
});
// execute done
loadjs.done('plugin1');
});
it('should execute callbacks created after .done()', function(done) {
// execute done
loadjs.done('plugin2');
// add handler
loadjs.ready('plugin2', {
success: function() {
done();
}
}
});
});
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle1');
// use 1 second delay to let files load
setTimeout(function() {
loadjs.ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
it('detects png|gif|jpg|svg|webp extensions', function(done) {
let files = [
'assets/flash.png',
'assets/flash.gif',
it('should allow bundle callbacks before definitions', function(done) {
// define callback
loadjs.ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
});
});
// use 1 second delay
setTimeout(function() {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle2');
}, 1000);
});
assertLoaded(src);
done();
}
});
});
loadjs(['assets/file1.js'], 'cleared');
};
expect(fn).not.to.throw(Error, "LoadJS");
});
});
});
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
var src = 'assets/flash.png';
src += '?' + Math.random();
src += '#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should support forced "img!" files', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
var src1 = 'assets/flash.png?' + Math.random(),
src2 = 'assets/flash-doesntexist.png?' + Math.random();
loadjs(['img!' + src1, 'img!' + src2], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assertLoaded(src1);
assertNotLoaded(src2);
done();
}
});
});
it('should support mix of img and js', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src, 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assertLoaded(src);
done();
}
});
});
it('should load external img files', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/mui-logo.png?';
src += Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/';
src += 'mui-logo-doesntexist.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assertNotLoaded(src);
done();
}
});
});
});
// ==========================================================================
// API tests
// ==========================================================================
describe('API tests', function() {
it('should throw an error if bundle is already defined', function() {
// define bundle
loadjs(['assets/file1.js'], 'bundle');
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'bundle');
};
expect(fn).to.throw("LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should chain loadjs object', function(done) {
function bothDone() {
if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done();
}
// define bundles
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs
.ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
.ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
}
});
});
it('should handle multiple dependencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file-doesntexist.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle2');
done();
}
});
});
it('should execute callbacks on .done()', function(done) {
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
// execute done
loadjs.done('plugin');
});
it('should execute callbacks created after .done()', function(done) {
// execute done
loadjs.done('plugin');
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
});
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
// use 1 second delay to let files load
setTimeout(function() {
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
}, 1000);
});
it('should allow bundle callbacks before definitions', function(done) {
// define callback
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
// use 1 second delay
setTimeout(function() {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
}, 1000);
});
it('should reset dependencies statuses', function() {
loadjs(['assets/file1.js'], 'cleared');
loadjs.reset();
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'cleared');
};
expect(fn).not.to.throw("LoadJS");
});
it('should indicate if bundle has already been defined', function() {
loadjs(['assets/file1/js'], 'bundle1');
assert.equal(loadjs.isDefined('bundle1'), true);
assert.equal(loadjs.isDefined('bundleXX'), false);
});
it('should accept success callback functions to loadjs()', function(done) {
loadjs('assets/file1.js', function() {
done();
});
});
it('should accept success callback functions to .ready()', function(done) {
loadjs.done('plugin');
loadjs.ready('plugin', function() {
done();
});
});
it('should return Promise object if returnPromise is true', function() {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
// verify that response object is a Promise
assert.equal(prom instanceof Promise, true);
});
it('Promise object should support resolutions', function(done) {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
prom.then(function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
});
});
it('Promise object should support rejections', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom.then(
function(){},
function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
);
});
it('Promise object should support catches', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom
.catch(function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
it('supports Promises and success callbacks', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
var prom = loadjs('assets/file1.js', {
success: completedFn,
returnPromise: true
});
prom.then(completedFn);
});
it('supports Promises and bundle ready events', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
loadjs('assets/file1.js', 'bundle1', {returnPromise: true})
.then(completedFn);
loadjs.ready('bundle1', completedFn);
});
});
});
<MSG> shaved off some bytes by throwing error string, updated tests and documentation
<DFF> @@ -14,6 +14,9 @@ describe('LoadJS tests', function() {
beforeEach(function() {
// reset register
pathsLoaded = {};
+
+ // reset loadjs dependencies
+ loadjs.reset();
});
// ==========================================================================
@@ -307,19 +310,19 @@ describe('LoadJS tests', function() {
it('should throw an error if bundle is already defined', function() {
// define bundle
- loadjs(['assets/file1.js'], 'bundle3');
+ loadjs(['assets/file1.js'], 'bundle');
// define bundle again
var fn = function() {
- loadjs(['assets/file1.js'], 'bundle3');
+ loadjs(['assets/file1.js'], 'bundle');
};
- expect(fn).to.throw(Error, "LoadJS");
+ expect(fn).to.throw("LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
- loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle4', {
+ loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
@@ -335,16 +338,16 @@ describe('LoadJS tests', function() {
}
// define bundles
- loadjs('assets/file1.js', 'bundle5');
- loadjs('assets/file2.js', 'bundle6');
+ loadjs('assets/file1.js', 'bundle1');
+ loadjs('assets/file2.js', 'bundle2');
loadjs
- .ready('bundle5', {
+ .ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
- .ready('bundle6', {
+ .ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
@@ -354,10 +357,10 @@ describe('LoadJS tests', function() {
it('should handle multiple dependencies', function(done) {
- loadjs('assets/file1.js', 'bundle7');
- loadjs('assets/file2.js', 'bundle8');
+ loadjs('assets/file1.js', 'bundle1');
+ loadjs('assets/file2.js', 'bundle2');
- loadjs.ready(['bundle7', 'bundle8'], {
+ loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
@@ -368,17 +371,17 @@ describe('LoadJS tests', function() {
it('should error on missing depdendencies', function(done) {
- loadjs('assets/file1.js', 'bundle9');
- loadjs('assets/file-doesntexist.js', 'bundle10');
+ loadjs('assets/file1.js', 'bundle1');
+ loadjs('assets/file-doesntexist.js', 'bundle2');
- loadjs.ready(['bundle9', 'bundle10'], {
+ loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
- assert.equal(depsNotFound[0], 'bundle10');
+ assert.equal(depsNotFound[0], 'bundle2');
done();
}
});
@@ -387,23 +390,23 @@ describe('LoadJS tests', function() {
it('should execute callbacks on .done()', function(done) {
// add handler
- loadjs.ready('plugin1', {
+ loadjs.ready('plugin', {
success: function() {
done();
}
});
// execute done
- loadjs.done('plugin1');
+ loadjs.done('plugin');
});
it('should execute callbacks created after .done()', function(done) {
// execute done
- loadjs.done('plugin2');
+ loadjs.done('plugin');
// add handler
- loadjs.ready('plugin2', {
+ loadjs.ready('plugin', {
success: function() {
done();
}
@@ -413,11 +416,11 @@ describe('LoadJS tests', function() {
it('should define bundles', function(done) {
// define bundle
- loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle1');
+ loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
// use 1 second delay to let files load
setTimeout(function() {
- loadjs.ready('bundle1', {
+ loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
@@ -430,7 +433,7 @@ describe('LoadJS tests', function() {
it('should allow bundle callbacks before definitions', function(done) {
// define callback
- loadjs.ready('bundle2', {
+ loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
@@ -440,7 +443,7 @@ describe('LoadJS tests', function() {
// use 1 second delay
setTimeout(function() {
- loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle2');
+ loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
}, 1000);
});
@@ -454,7 +457,7 @@ describe('LoadJS tests', function() {
loadjs(['assets/file1.js'], 'cleared');
};
- expect(fn).not.to.throw(Error, "LoadJS");
+ expect(fn).not.to.throw("LoadJS");
});
});
});
| 27 | shaved off some bytes by throwing error string, updated tests and documentation | 24 | .js | js | mit | muicss/loadjs |
10067643 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Update test project to net5
<DFF> @@ -1,10 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>netcoreapp2.2</TargetFramework>
+ <TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
+ <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 2 | Update test project to net5 | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10067644 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Update test project to net5
<DFF> @@ -1,10 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>netcoreapp2.2</TargetFramework>
+ <TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
+ <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 2 | Update test project to net5 | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10067645 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Update test project to net5
<DFF> @@ -1,10 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>netcoreapp2.2</TargetFramework>
+ <TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
+ <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 2 | Update test project to net5 | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10067646 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Update test project to net5
<DFF> @@ -1,10 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>netcoreapp2.2</TargetFramework>
+ <TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
+ <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 2 | Update test project to net5 | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10067647 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Update test project to net5
<DFF> @@ -1,10 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>netcoreapp2.2</TargetFramework>
+ <TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
+ <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 2 | Update test project to net5 | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10067648 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Update test project to net5
<DFF> @@ -1,10 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>netcoreapp2.2</TargetFramework>
+ <TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
+ <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 2 | Update test project to net5 | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10067649 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Update test project to net5
<DFF> @@ -1,10 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>netcoreapp2.2</TargetFramework>
+ <TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
+ <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 2 | Update test project to net5 | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.