From 0c8f54fe009761088f91bb394e136e4d9bb113d6 Mon Sep 17 00:00:00 2001 From: Benedikt Stebner Date: Tue, 21 Jun 2022 15:34:05 +0200 Subject: [PATCH 1/9] Introduce RichTextBlock --- .../ControlCatalog/Pages/TextBlockPage.xaml | 4 +- .../Documents/InlineCollection.cs | 72 +++++-- src/Avalonia.Controls/Documents/Span.cs | 84 ++++++-- .../Documents/TextElement.cs | 18 +- src/Avalonia.Controls/RichTextBlock.cs | 199 ++++++++++++++++++ src/Avalonia.Controls/TextBlock.cs | 123 ++--------- 6 files changed, 353 insertions(+), 147 deletions(-) create mode 100644 src/Avalonia.Controls/RichTextBlock.cs diff --git a/samples/ControlCatalog/Pages/TextBlockPage.xaml b/samples/ControlCatalog/Pages/TextBlockPage.xaml index fe9455bd29..cb49ba96c6 100644 --- a/samples/ControlCatalog/Pages/TextBlockPage.xaml +++ b/samples/ControlCatalog/Pages/TextBlockPage.xaml @@ -118,7 +118,7 @@ - + This is a TextBlock with several @@ -126,7 +126,7 @@ using a variety of styles . - + diff --git a/src/Avalonia.Controls/Documents/InlineCollection.cs b/src/Avalonia.Controls/Documents/InlineCollection.cs index a76222385e..0cbf272297 100644 --- a/src/Avalonia.Controls/Documents/InlineCollection.cs +++ b/src/Avalonia.Controls/Documents/InlineCollection.cs @@ -12,39 +12,55 @@ namespace Avalonia.Controls.Documents [WhitespaceSignificantCollection] public class InlineCollection : AvaloniaList { - private readonly IInlineHost? _host; + private ILogical? _parent; + private IInlineHost? _inlineHost; private string? _text = string.Empty; /// /// Initializes a new instance of the class. /// - public InlineCollection(ILogical parent) : this(parent, null) { } - - /// - /// Initializes a new instance of the class. - /// - internal InlineCollection(ILogical parent, IInlineHost? host = null) : base(0) + public InlineCollection() { - _host = host; - ResetBehavior = ResetBehavior.Remove; this.ForEachItem( x => { - ((ISetLogicalParent)x).SetParent(parent); - x.InlineHost = host; - host?.Invalidate(); + ((ISetLogicalParent)x).SetParent(Parent); + x.InlineHost = InlineHost; + Invalidate(); }, x => { ((ISetLogicalParent)x).SetParent(null); - x.InlineHost = host; - host?.Invalidate(); + x.InlineHost = InlineHost; + Invalidate(); }, () => throw new NotSupportedException()); } + internal ILogical? Parent + { + get => _parent; + set + { + _parent = value; + + OnParentChanged(value); + } + } + + internal IInlineHost? InlineHost + { + get => _inlineHost; + set + { + _inlineHost = value; + + OnInlineHostChanged(value); + } + } + public bool HasComplexContent => Count > 0; /// @@ -57,14 +73,16 @@ namespace Avalonia.Controls.Documents { get { + return _text; + if (!HasComplexContent) { return _text; } - + var builder = new StringBuilder(); - foreach(var inline in this) + foreach (var inline in this) { inline.AppendText(builder); } @@ -100,7 +118,7 @@ namespace Avalonia.Controls.Documents } else { - _text += text; + _text = text; } } @@ -136,14 +154,30 @@ namespace Avalonia.Controls.Documents /// protected void Invalidate() { - if(_host != null) + if(InlineHost != null) { - _host.Invalidate(); + InlineHost.Invalidate(); } Invalidated?.Invoke(this, EventArgs.Empty); } private void Invalidate(object? sender, EventArgs e) => Invalidate(); + + private void OnParentChanged(ILogical? parent) + { + foreach(var child in this) + { + ((ISetLogicalParent)child).SetParent(parent); + } + } + + private void OnInlineHostChanged(IInlineHost? inlineHost) + { + foreach (var child in this) + { + child.InlineHost = inlineHost; + } + } } } diff --git a/src/Avalonia.Controls/Documents/Span.cs b/src/Avalonia.Controls/Documents/Span.cs index bd1b4fc5e1..c2576ec231 100644 --- a/src/Avalonia.Controls/Documents/Span.cs +++ b/src/Avalonia.Controls/Documents/Span.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Text; using Avalonia.Media.TextFormatting; -using Avalonia.Metadata; namespace Avalonia.Controls.Documents { @@ -14,25 +13,42 @@ namespace Avalonia.Controls.Documents /// /// Defines the property. /// - public static readonly DirectProperty InlinesProperty = - AvaloniaProperty.RegisterDirect( - nameof(Inlines), - o => o.Inlines); + public static readonly StyledProperty InlinesProperty = + AvaloniaProperty.Register( + nameof(Inlines)); - /// - /// Initializes a new instance of a Span element. - /// public Span() { - Inlines = new InlineCollection(this); - Inlines.Invalidated += (s, e) => InlineHost?.Invalidate(); + Inlines = new InlineCollection + { + Parent = this + }; } /// /// Gets or sets the inlines. - /// - [Content] - public InlineCollection Inlines { get; } + /// + public InlineCollection Inlines + { + get => GetValue(InlinesProperty); + set => SetValue(InlinesProperty, value); + } + + public void Add(Inline inline) + { + if (Inlines is not null) + { + Inlines.Add(inline); + } + } + + public void Add(string text) + { + if (Inlines is not null) + { + Inlines.Add(text); + } + } internal override void BuildTextRun(IList textRuns) { @@ -52,7 +68,7 @@ namespace Avalonia.Controls.Documents var textCharacters = new TextCharacters(text.AsMemory(), textRunProperties); textRuns.Add(textCharacters); - } + } } } @@ -71,5 +87,45 @@ namespace Avalonia.Controls.Documents stringBuilder.Append(text); } } + + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + + switch (change.Property.Name) + { + case nameof(InlinesProperty): + OnInlinesChanged(change.OldValue as InlineCollection, change.NewValue as InlineCollection); + InlineHost?.Invalidate(); + break; + } + } + + internal override void OnInlinesHostChanged(IInlineHost? oldValue, IInlineHost? newValue) + { + base.OnInlinesHostChanged(oldValue, newValue); + + if(Inlines is not null) + { + Inlines.InlineHost = newValue; + } + } + + private void OnInlinesChanged(InlineCollection? oldValue, InlineCollection? newValue) + { + if (oldValue is not null) + { + oldValue.Parent = null; + oldValue.InlineHost = null; + oldValue.Invalidated -= (s, e) => InlineHost?.Invalidate(); + } + + if (newValue is not null) + { + newValue.Parent = this; + newValue.InlineHost = InlineHost; + newValue.Invalidated += (s, e) => InlineHost?.Invalidate(); + } + } } } diff --git a/src/Avalonia.Controls/Documents/TextElement.cs b/src/Avalonia.Controls/Documents/TextElement.cs index f228519e60..e75fd87615 100644 --- a/src/Avalonia.Controls/Documents/TextElement.cs +++ b/src/Avalonia.Controls/Documents/TextElement.cs @@ -67,6 +67,8 @@ namespace Avalonia.Controls.Documents Brushes.Black, inherits: true); + private IInlineHost? _inlineHost; + /// /// Gets or sets a brush used to paint the control's background. /// @@ -250,7 +252,21 @@ namespace Avalonia.Controls.Documents control.SetValue(ForegroundProperty, value); } - internal IInlineHost? InlineHost { get; set; } + internal IInlineHost? InlineHost + { + get => _inlineHost; + set + { + var oldValue = _inlineHost; + _inlineHost = value; + OnInlinesHostChanged(oldValue, value); + } + } + + internal virtual void OnInlinesHostChanged(IInlineHost? oldValue, IInlineHost? newValue) + { + + } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { diff --git a/src/Avalonia.Controls/RichTextBlock.cs b/src/Avalonia.Controls/RichTextBlock.cs new file mode 100644 index 0000000000..16d0254f4a --- /dev/null +++ b/src/Avalonia.Controls/RichTextBlock.cs @@ -0,0 +1,199 @@ +using System; +using System.Collections.Generic; +using Avalonia.Controls.Documents; +using Avalonia.Media; +using Avalonia.Media.TextFormatting; + +namespace Avalonia.Controls +{ + /// + /// A control that displays a block of text. + /// + public class RichTextBlock : TextBlock, IInlineHost + { + /// + /// Defines the property. + /// + public static readonly StyledProperty InlinesProperty = + AvaloniaProperty.Register( + nameof(Inlines)); + + public RichTextBlock() + { + Inlines = new InlineCollection + { + Parent = this, + InlineHost = this + }; + } + + /// + /// Gets or sets the inlines. + /// + public InlineCollection Inlines + { + get => GetValue(InlinesProperty); + set => SetValue(InlinesProperty, value); + } + + public void Add(Inline inline) + { + if (Inlines is not null) + { + Inlines.Add(inline); + } + } + + public new void Add(string text) + { + if (Inlines is not null) + { + Inlines.Add(text); + } + } + + /// + /// Creates the used to render the text. + /// + /// The constraint of the text. + /// The text to format. + /// A object. + protected override TextLayout CreateTextLayout(Size constraint, string? text) + { + var defaultProperties = new GenericTextRunProperties( + new Typeface(FontFamily, FontStyle, FontWeight, FontStretch), + FontSize, + TextDecorations, + Foreground); + + var paragraphProperties = new GenericTextParagraphProperties(FlowDirection, TextAlignment, true, false, + defaultProperties, TextWrapping, LineHeight, 0); + + ITextSource textSource; + + var inlines = Inlines; + + if (inlines is not null && inlines.HasComplexContent) + { + var textRuns = new List(); + + foreach (var inline in inlines) + { + inline.BuildTextRun(textRuns); + } + + textSource = new InlinesTextSource(textRuns); + } + else + { + textSource = new SimpleTextSource((text ?? "").AsMemory(), defaultProperties); + } + + return new TextLayout( + textSource, + paragraphProperties, + TextTrimming, + constraint.Width, + constraint.Height, + maxLines: MaxLines, + lineHeight: LineHeight); + } + + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + + switch (change.Property.Name) + { + case nameof(InlinesProperty): + { + OnInlinesChanged(change.OldValue as InlineCollection, change.NewValue as InlineCollection); + InvalidateTextLayout(); + break; + } + case nameof(TextProperty): + { + OnTextChanged(change.OldValue as string, change.NewValue as string); + break; + } + } + } + + private void OnTextChanged(string? oldValue, string? newValue) + { + if (oldValue == newValue) + { + return; + } + + if (Inlines is null) + { + return; + } + + Inlines.Text = newValue; + } + + private void OnInlinesChanged(InlineCollection? oldValue, InlineCollection? newValue) + { + if (oldValue is not null) + { + oldValue.Parent = null; + oldValue.InlineHost = null; + oldValue.Invalidated -= (s, e) => InvalidateTextLayout(); + } + + if (newValue is not null) + { + newValue.Parent = this; + newValue.InlineHost = this; + newValue.Invalidated += (s, e) => InvalidateTextLayout(); + } + } + + void IInlineHost.AddVisualChild(IControl child) + { + if (child.VisualParent == null) + { + VisualChildren.Add(child); + } + } + + void IInlineHost.Invalidate() + { + InvalidateTextLayout(); + } + + private readonly struct InlinesTextSource : ITextSource + { + private readonly IReadOnlyList _textRuns; + + public InlinesTextSource(IReadOnlyList textRuns) + { + _textRuns = textRuns; + } + + public TextRun? GetTextRun(int textSourceIndex) + { + var currentPosition = 0; + + foreach (var textRun in _textRuns) + { + if (textRun.TextSourceLength == 0) + { + continue; + } + + if (currentPosition >= textSourceIndex) + { + return textRun; + } + + currentPosition += textRun.TextSourceLength; + } + + return null; + } + } + } +} diff --git a/src/Avalonia.Controls/TextBlock.cs b/src/Avalonia.Controls/TextBlock.cs index 1a69d1218c..87966e9a6f 100644 --- a/src/Avalonia.Controls/TextBlock.cs +++ b/src/Avalonia.Controls/TextBlock.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using Avalonia.Automation.Peers; using Avalonia.Controls.Documents; using Avalonia.Layout; @@ -14,7 +13,7 @@ namespace Avalonia.Controls /// /// A control that displays a block of text. /// - public class TextBlock : Control, IInlineHost + public class TextBlock : Control { /// /// Defines the property. @@ -101,14 +100,6 @@ namespace Avalonia.Controls o => o.Text, (o, v) => o.Text = v); - /// - /// Defines the property. - /// - public static readonly DirectProperty InlinesProperty = - AvaloniaProperty.RegisterDirect( - nameof(Inlines), - o => o.Inlines); - /// /// Defines the property. /// @@ -137,6 +128,7 @@ namespace Avalonia.Controls public static readonly StyledProperty TextDecorationsProperty = AvaloniaProperty.Register(nameof(TextDecorations)); + private string? _text; private TextLayout? _textLayout; private Size _constraint; @@ -150,14 +142,6 @@ namespace Avalonia.Controls AffectsRender(BackgroundProperty, ForegroundProperty); } - /// - /// Initializes a new instance of the class. - /// - public TextBlock() - { - Inlines = new InlineCollection(this, this); - } - /// /// Gets the used to render the text. /// @@ -165,7 +149,7 @@ namespace Avalonia.Controls { get { - return _textLayout ?? (_textLayout = CreateTextLayout(_constraint, Text)); + return _textLayout ??= CreateTextLayout(_constraint, Text); } } @@ -192,28 +176,13 @@ namespace Avalonia.Controls /// public string? Text { - get => Inlines.Text; + get => _text; set { - var old = Text; - - if (value == old) - { - return; - } - - Inlines.Text = value; - - RaisePropertyChanged(TextProperty, old, value); + SetAndRaise(TextProperty, ref _text, value); } } - /// - /// Gets the inlines. - /// - [Content] - public InlineCollection Inlines { get; } - /// /// Gets or sets the font family used to draw the control's text. /// @@ -333,6 +302,11 @@ namespace Avalonia.Controls set { SetValue(BaselineOffsetProperty, value); } } + public void Add(string text) + { + Text = text; + } + /// /// Reads the attached property from the given element /// @@ -559,26 +533,8 @@ namespace Avalonia.Controls var paragraphProperties = new GenericTextParagraphProperties(FlowDirection, TextAlignment, true, false, defaultProperties, TextWrapping, LineHeight, 0); - ITextSource textSource; - - if (Inlines.HasComplexContent) - { - var textRuns = new List(); - - foreach (var inline in Inlines) - { - inline.BuildTextRun(textRuns); - } - - textSource = new InlinesTextSource(textRuns); - } - else - { - textSource = new SimpleTextSource((text ?? "").AsMemory(), defaultProperties); - } - return new TextLayout( - textSource, + new SimpleTextSource((text ?? "").AsMemory(), defaultProperties), paragraphProperties, TextTrimming, constraint.Width, @@ -599,11 +555,6 @@ namespace Avalonia.Controls protected override Size MeasureOverride(Size availableSize) { - if (!Inlines.HasComplexContent && string.IsNullOrEmpty(Text)) - { - return new Size(); - } - var scale = LayoutHelper.GetLayoutScale(this); var padding = LayoutHelper.RoundLayoutThickness(Padding, scale, scale); @@ -683,57 +634,7 @@ namespace Avalonia.Controls } } - private void InlinesChanged(object? sender, EventArgs e) - { - InvalidateTextLayout(); - } - - void IInlineHost.AddVisualChild(IControl child) - { - if (child.VisualParent == null) - { - VisualChildren.Add(child); - } - } - - void IInlineHost.Invalidate() - { - InvalidateTextLayout(); - } - - private readonly struct InlinesTextSource : ITextSource - { - private readonly IReadOnlyList _textRuns; - - public InlinesTextSource(IReadOnlyList textRuns) - { - _textRuns = textRuns; - } - - public TextRun? GetTextRun(int textSourceIndex) - { - var currentPosition = 0; - - foreach (var textRun in _textRuns) - { - if(textRun.TextSourceLength == 0) - { - continue; - } - - if(currentPosition >= textSourceIndex) - { - return textRun; - } - - currentPosition += textRun.TextSourceLength; - } - - return null; - } - } - - private readonly struct SimpleTextSource : ITextSource + protected readonly struct SimpleTextSource : ITextSource { private readonly ReadOnlySlice _text; private readonly TextRunProperties _defaultProperties; From a408ea10d79ac357d968a1ff96a3664506a6058b Mon Sep 17 00:00:00 2001 From: Benedikt Stebner Date: Wed, 22 Jun 2022 16:45:38 +0200 Subject: [PATCH 2/9] Some Progress --- samples/Sandbox/MainWindow.axaml | 14 + .../Media/TextFormatting/TextFormatterImpl.cs | 2 +- .../TextFormatting/Unicode/BiDiAlgorithm.cs | 6 - .../Documents/InlineCollection.cs | 2 - src/Avalonia.Controls/Documents/Span.cs | 20 +- .../Presenters/TextPresenter.cs | 8 +- src/Avalonia.Controls/RichTextBlock.cs | 326 +++++++++++++++++- src/Avalonia.Controls/TextBlock.cs | 12 +- .../TextFormatting/BiDiAlgorithmTests.cs | 2 +- .../RichTextBlockTests.cs | 52 +++ .../TextBlockTests.cs | 42 --- 11 files changed, 397 insertions(+), 89 deletions(-) create mode 100644 tests/Avalonia.Controls.UnitTests/RichTextBlockTests.cs diff --git a/samples/Sandbox/MainWindow.axaml b/samples/Sandbox/MainWindow.axaml index 6929f192c7..806f6d37da 100644 --- a/samples/Sandbox/MainWindow.axaml +++ b/samples/Sandbox/MainWindow.axaml @@ -1,4 +1,18 @@ + + + + This is a + TextBlock + with several + Span elements, + + using a variety of styles + . + + + + diff --git a/src/Avalonia.Base/Media/TextFormatting/TextFormatterImpl.cs b/src/Avalonia.Base/Media/TextFormatting/TextFormatterImpl.cs index 4205268bc6..cd764be43f 100644 --- a/src/Avalonia.Base/Media/TextFormatting/TextFormatterImpl.cs +++ b/src/Avalonia.Base/Media/TextFormatting/TextFormatterImpl.cs @@ -177,7 +177,7 @@ namespace Avalonia.Media.TextFormatting } - var biDi = BidiAlgorithm.Instance.Value!; + var biDi = new BidiAlgorithm(); biDi.Process(biDiData); diff --git a/src/Avalonia.Base/Media/TextFormatting/Unicode/BiDiAlgorithm.cs b/src/Avalonia.Base/Media/TextFormatting/Unicode/BiDiAlgorithm.cs index 2511807d9c..3c510ff484 100644 --- a/src/Avalonia.Base/Media/TextFormatting/Unicode/BiDiAlgorithm.cs +++ b/src/Avalonia.Base/Media/TextFormatting/Unicode/BiDiAlgorithm.cs @@ -188,12 +188,6 @@ namespace Avalonia.Media.TextFormatting.Unicode { } - /// - /// Gets a per-thread instance that can be re-used as often - /// as necessary. - /// - public static ThreadLocal Instance { get; } = new ThreadLocal(() => new BidiAlgorithm()); - /// /// Gets the resolved levels. /// diff --git a/src/Avalonia.Controls/Documents/InlineCollection.cs b/src/Avalonia.Controls/Documents/InlineCollection.cs index 0cbf272297..2f27ca72d0 100644 --- a/src/Avalonia.Controls/Documents/InlineCollection.cs +++ b/src/Avalonia.Controls/Documents/InlineCollection.cs @@ -73,8 +73,6 @@ namespace Avalonia.Controls.Documents { get { - return _text; - if (!HasComplexContent) { return _text; diff --git a/src/Avalonia.Controls/Documents/Span.cs b/src/Avalonia.Controls/Documents/Span.cs index c2576ec231..98851726da 100644 --- a/src/Avalonia.Controls/Documents/Span.cs +++ b/src/Avalonia.Controls/Documents/Span.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Text; using Avalonia.Media.TextFormatting; +using Avalonia.Metadata; namespace Avalonia.Controls.Documents { @@ -27,29 +28,14 @@ namespace Avalonia.Controls.Documents /// /// Gets or sets the inlines. - /// + /// + [Content] public InlineCollection Inlines { get => GetValue(InlinesProperty); set => SetValue(InlinesProperty, value); } - public void Add(Inline inline) - { - if (Inlines is not null) - { - Inlines.Add(inline); - } - } - - public void Add(string text) - { - if (Inlines is not null) - { - Inlines.Add(text); - } - } - internal override void BuildTextRun(IList textRuns) { if (Inlines.HasComplexContent) diff --git a/src/Avalonia.Controls/Presenters/TextPresenter.cs b/src/Avalonia.Controls/Presenters/TextPresenter.cs index 3523cd5214..e463bc5731 100644 --- a/src/Avalonia.Controls/Presenters/TextPresenter.cs +++ b/src/Avalonia.Controls/Presenters/TextPresenter.cs @@ -543,9 +543,11 @@ namespace Avalonia.Controls.Presenters protected override Size ArrangeOverride(Size finalSize) { - if (finalSize.Width < TextLayout.Bounds.Width) + var textWidth = Math.Ceiling(TextLayout.Bounds.Width); + + if (finalSize.Width < textWidth) { - finalSize = finalSize.WithWidth(TextLayout.Bounds.Width); + finalSize = finalSize.WithWidth(textWidth); } if (MathUtilities.AreClose(_constraint.Width, finalSize.Width)) @@ -553,7 +555,7 @@ namespace Avalonia.Controls.Presenters return finalSize; } - _constraint = new Size(finalSize.Width, double.PositiveInfinity); + _constraint = new Size(Math.Ceiling(finalSize.Width), double.PositiveInfinity); _textLayout = null; diff --git a/src/Avalonia.Controls/RichTextBlock.cs b/src/Avalonia.Controls/RichTextBlock.cs index 16d0254f4a..859503e693 100644 --- a/src/Avalonia.Controls/RichTextBlock.cs +++ b/src/Avalonia.Controls/RichTextBlock.cs @@ -1,8 +1,14 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using Avalonia.Controls.Documents; +using Avalonia.Controls.Utils; +using Avalonia.Input; +using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Media.TextFormatting; +using Avalonia.Metadata; +using Avalonia.Utilities; namespace Avalonia.Controls { @@ -11,6 +17,38 @@ namespace Avalonia.Controls /// public class RichTextBlock : TextBlock, IInlineHost { + public static readonly StyledProperty IsTextSelectionEnabledProperty = + AvaloniaProperty.Register(nameof(IsTextSelectionEnabled), false); + + public static readonly DirectProperty CaretIndexProperty = + AvaloniaProperty.RegisterDirect( + nameof(CaretIndex), + o => o.CaretIndex, + (o, v) => o.CaretIndex = v); + + public static readonly DirectProperty SelectionStartProperty = + AvaloniaProperty.RegisterDirect( + nameof(SelectionStart), + o => o.SelectionStart, + (o, v) => o.SelectionStart = v); + + public static readonly DirectProperty SelectionEndProperty = + AvaloniaProperty.RegisterDirect( + nameof(SelectionEnd), + o => o.SelectionEnd, + (o, v) => o.SelectionEnd = v); + + public static readonly DirectProperty SelectedTextProperty = + AvaloniaProperty.RegisterDirect( + nameof(SelectedText), + o => o.SelectedText); + + public static readonly StyledProperty SelectionBrushProperty = + AvaloniaProperty.Register(nameof(SelectionBrush), Brushes.Blue); + + public static readonly StyledProperty SelectionForegroundBrushProperty = + AvaloniaProperty.Register(nameof(SelectionForegroundBrush)); + /// /// Defines the property. /// @@ -18,6 +56,17 @@ namespace Avalonia.Controls AvaloniaProperty.Register( nameof(Inlines)); + private int _caretIndex; + private int _selectionStart; + private int _selectionEnd; + + static RichTextBlock() + { + FocusableProperty.OverrideDefaultValue(typeof(RichTextBlock), true); + + AffectsRender(SelectionStartProperty, SelectionEndProperty, SelectionForegroundBrushProperty, SelectionBrushProperty); + } + public RichTextBlock() { Inlines = new InlineCollection @@ -27,31 +76,85 @@ namespace Avalonia.Controls }; } - /// - /// Gets or sets the inlines. - /// - public InlineCollection Inlines + public IBrush? SelectionBrush { - get => GetValue(InlinesProperty); - set => SetValue(InlinesProperty, value); + get => GetValue(SelectionBrushProperty); + set => SetValue(SelectionBrushProperty, value); } - public void Add(Inline inline) + public IBrush? SelectionForegroundBrush { - if (Inlines is not null) + get => GetValue(SelectionForegroundBrushProperty); + set => SetValue(SelectionForegroundBrushProperty, value); + } + + public int CaretIndex + { + get => _caretIndex; + set { - Inlines.Add(inline); + if(SetAndRaise(CaretIndexProperty, ref _caretIndex, value)) + { + SelectionStart = SelectionEnd = value; + } } } - public new void Add(string text) + public int SelectionStart { - if (Inlines is not null) + get => _selectionStart; + set { - Inlines.Add(text); + if (SetAndRaise(SelectionStartProperty, ref _selectionStart, value)) + { + RaisePropertyChanged(SelectedTextProperty, "", ""); + + if (SelectionEnd == value && CaretIndex != value) + { + CaretIndex = value; + } + } } } + public int SelectionEnd + { + get => _selectionEnd; + set + { + if(SetAndRaise(SelectionEndProperty, ref _selectionEnd, value)) + { + RaisePropertyChanged(SelectedTextProperty, "", ""); + + if (SelectionStart == value && CaretIndex != value) + { + CaretIndex = value; + } + } + } + } + + public string SelectedText + { + get => GetSelection(); + } + + public bool IsTextSelectionEnabled + { + get => GetValue(IsTextSelectionEnabledProperty); + set => SetValue(IsTextSelectionEnabledProperty, value); + } + + /// + /// Gets or sets the inlines. + /// + [Content] + public InlineCollection Inlines + { + get => GetValue(InlinesProperty); + set => SetValue(InlinesProperty, value); + } + /// /// Creates the used to render the text. /// @@ -99,6 +202,179 @@ namespace Avalonia.Controls lineHeight: LineHeight); } + public override void Render(DrawingContext context) + { + var selectionStart = SelectionStart; + var selectionEnd = SelectionEnd; + var selectionBrush = SelectionBrush; + + var selectionEnabled = IsTextSelectionEnabled; + + if (selectionEnabled && selectionStart != selectionEnd && selectionBrush != null) + { + var start = Math.Min(selectionStart, selectionEnd); + var length = Math.Max(selectionStart, selectionEnd) - start; + + var rects = TextLayout.HitTestTextRange(start, length); + + foreach (var rect in rects) + { + context.FillRectangle(selectionBrush, PixelRect.FromRect(rect, 1).ToRect(1)); + } + } + + base.Render(context); + } + + /// + /// Select all text in the TextBox + /// + public void SelectAll() + { + if (!IsTextSelectionEnabled) + { + return; + } + + var text = Inlines.Text ?? Text; + + SelectionStart = 0; + SelectionEnd = text?.Length ?? 0; + } + + /// + /// Clears the current selection/> + /// + public void ClearSelection() + { + if (!IsTextSelectionEnabled) + { + return; + } + + SelectionEnd = SelectionStart; + } + + protected override void OnLostFocus(RoutedEventArgs e) + { + base.OnLostFocus(e); + + ClearSelection(); + } + + protected override void OnPointerPressed(PointerPressedEventArgs e) + { + if (!IsTextSelectionEnabled) + { + return; + } + + var text = Inlines.Text; + var clickInfo = e.GetCurrentPoint(this); + + if (text != null && clickInfo.Properties.IsLeftButtonPressed) + { + var point = e.GetPosition(this); + + var clickToSelect = e.KeyModifiers.HasFlag(KeyModifiers.Shift); + + var hit = TextLayout.HitTestPoint(point); + + var oldIndex = CaretIndex; + var index = hit.TextPosition; + CaretIndex = index; + +#pragma warning disable CS0618 // Type or member is obsolete + switch (e.ClickCount) +#pragma warning restore CS0618 // Type or member is obsolete + { + case 1: + if (clickToSelect) + { + SelectionStart = Math.Min(oldIndex, index); + SelectionEnd = Math.Max(oldIndex, index); + } + else + { + SelectionStart = SelectionEnd = index; + } + + break; + case 2: + if (!StringUtils.IsStartOfWord(text, index)) + { + SelectionStart = StringUtils.PreviousWord(text, index); + } + + SelectionEnd = StringUtils.NextWord(text, index); + break; + case 3: + SelectAll(); + break; + } + } + + e.Pointer.Capture(this); + e.Handled = true; + } + + protected override void OnPointerMoved(PointerEventArgs e) + { + if (!IsTextSelectionEnabled) + { + return; + } + + // selection should not change during pointer move if the user right clicks + if (e.Pointer.Captured == this && e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) + { + var point = e.GetPosition(this); + + point = new Point( + MathUtilities.Clamp(point.X, 0, Math.Max(Bounds.Width - 1, 0)), + MathUtilities.Clamp(point.Y, 0, Math.Max(Bounds.Height - 1, 0))); + + var hit = TextLayout.HitTestPoint(point); + + SelectionEnd = hit.TextPosition; + } + } + + protected override void OnPointerReleased(PointerReleasedEventArgs e) + { + if (!IsTextSelectionEnabled) + { + return; + } + + if (e.Pointer.Captured != this) + { + return; + } + + if (e.InitialPressMouseButton == MouseButton.Right) + { + var point = e.GetPosition(this); + + var hit = TextLayout.HitTestPoint(point); + + var caretIndex = hit.TextPosition; + + // see if mouse clicked inside current selection + // if it did not, we change the selection to where the user clicked + var firstSelection = Math.Min(SelectionStart, SelectionEnd); + var lastSelection = Math.Max(SelectionStart, SelectionEnd); + var didClickInSelection = SelectionStart != SelectionEnd && + caretIndex >= firstSelection && caretIndex <= lastSelection; + if (!didClickInSelection) + { + _caretIndex = SelectionEnd = SelectionStart = caretIndex; + } + } + + e.Pointer.Capture(null); + } + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); @@ -134,6 +410,32 @@ namespace Avalonia.Controls Inlines.Text = newValue; } + private string GetSelection() + { + var text = Inlines.Text ?? Text; + + if (string.IsNullOrEmpty(text)) + { + return ""; + } + + var selectionStart = SelectionStart; + var selectionEnd = SelectionEnd; + var start = Math.Min(selectionStart, selectionEnd); + var end = Math.Max(selectionStart, selectionEnd); + + if (start == end || text.Length < end) + { + return ""; + } + + var length = Math.Max(0, end - start); + + var selectedText = text.Substring(start, length); + + return selectedText; + } + private void OnInlinesChanged(InlineCollection? oldValue, InlineCollection? newValue) { if (oldValue is not null) diff --git a/src/Avalonia.Controls/TextBlock.cs b/src/Avalonia.Controls/TextBlock.cs index 87966e9a6f..1f891b092f 100644 --- a/src/Avalonia.Controls/TextBlock.cs +++ b/src/Avalonia.Controls/TextBlock.cs @@ -128,8 +128,8 @@ namespace Avalonia.Controls public static readonly StyledProperty TextDecorationsProperty = AvaloniaProperty.Register(nameof(TextDecorations)); - private string? _text; - private TextLayout? _textLayout; + protected string? _text; + protected TextLayout? _textLayout; private Size _constraint; /// @@ -572,9 +572,11 @@ namespace Avalonia.Controls protected override Size ArrangeOverride(Size finalSize) { - if(finalSize.Width < TextLayout.Bounds.Width) + var textWidth = Math.Ceiling(TextLayout.Bounds.Width); + + if(finalSize.Width < textWidth) { - finalSize = finalSize.WithWidth(TextLayout.Bounds.Width); + finalSize = finalSize.WithWidth(textWidth); } if (MathUtilities.AreClose(_constraint.Width, finalSize.Width)) @@ -586,7 +588,7 @@ namespace Avalonia.Controls var padding = LayoutHelper.RoundLayoutThickness(Padding, scale, scale); - _constraint = new Size(finalSize.Deflate(padding).Width, double.PositiveInfinity); + _constraint = new Size(Math.Ceiling(finalSize.Deflate(padding).Width), double.PositiveInfinity); _textLayout = null; diff --git a/tests/Avalonia.Base.UnitTests/Media/TextFormatting/BiDiAlgorithmTests.cs b/tests/Avalonia.Base.UnitTests/Media/TextFormatting/BiDiAlgorithmTests.cs index f8a2abc716..5ff2c0e07b 100644 --- a/tests/Avalonia.Base.UnitTests/Media/TextFormatting/BiDiAlgorithmTests.cs +++ b/tests/Avalonia.Base.UnitTests/Media/TextFormatting/BiDiAlgorithmTests.cs @@ -27,7 +27,7 @@ namespace Avalonia.Visuals.UnitTests.Media.TextFormatting private bool Run(BiDiTestData testData) { - var bidi = BidiAlgorithm.Instance.Value; + var bidi = new BidiAlgorithm(); // Run the algorithm... ArraySlice resultLevels; diff --git a/tests/Avalonia.Controls.UnitTests/RichTextBlockTests.cs b/tests/Avalonia.Controls.UnitTests/RichTextBlockTests.cs new file mode 100644 index 0000000000..eb4b88956d --- /dev/null +++ b/tests/Avalonia.Controls.UnitTests/RichTextBlockTests.cs @@ -0,0 +1,52 @@ +using Avalonia.Controls.Documents; +using Avalonia.Media; +using Avalonia.UnitTests; +using Xunit; + +namespace Avalonia.Controls.UnitTests +{ + public class RichTextBlockTests + { + [Fact] + public void Changing_InlinesCollection_Should_Invalidate_Measure() + { + using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface)) + { + var target = new RichTextBlock(); + + target.Measure(Size.Infinity); + + Assert.True(target.IsMeasureValid); + + target.Inlines.Add(new Run("Hello")); + + Assert.False(target.IsMeasureValid); + + target.Measure(Size.Infinity); + + Assert.True(target.IsMeasureValid); + } + } + + [Fact] + public void Changing_Inlines_Properties_Should_Invalidate_Measure() + { + using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface)) + { + var target = new RichTextBlock(); + + var inline = new Run("Hello"); + + target.Inlines.Add(inline); + + target.Measure(Size.Infinity); + + Assert.True(target.IsMeasureValid); + + inline.Foreground = Brushes.Green; + + Assert.False(target.IsMeasureValid); + } + } + } +} diff --git a/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs b/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs index 0ed1f8d2d0..6da011f062 100644 --- a/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs +++ b/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs @@ -62,47 +62,5 @@ namespace Avalonia.Controls.UnitTests renderer.Verify(x => x.AddDirty(target), Times.Once); } - - [Fact] - public void Changing_InlinesCollection_Should_Invalidate_Measure() - { - using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface)) - { - var target = new TextBlock(); - - target.Measure(Size.Infinity); - - Assert.True(target.IsMeasureValid); - - target.Inlines.Add(new Run("Hello")); - - Assert.False(target.IsMeasureValid); - - target.Measure(Size.Infinity); - - Assert.True(target.IsMeasureValid); - } - } - - [Fact] - public void Changing_Inlines_Properties_Should_Invalidate_Measure() - { - using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface)) - { - var target = new TextBlock(); - - var inline = new Run("Hello"); - - target.Inlines.Add(inline); - - target.Measure(Size.Infinity); - - Assert.True(target.IsMeasureValid); - - inline.Text = "1337"; - - Assert.False(target.IsMeasureValid); - } - } } } From 90e0dcc9e3161cb9659ca7381c6ff98ee7e84f10 Mon Sep 17 00:00:00 2001 From: Benedikt Stebner Date: Thu, 23 Jun 2022 15:18:36 +0200 Subject: [PATCH 3/9] Add Copy geasture --- samples/Sandbox/MainWindow.axaml | 1 + .../Documents/InlineCollection.cs | 4 +- src/Avalonia.Controls/Documents/Span.cs | 12 +- .../Documents/TextElement.cs | 4 +- .../Primitives/AccessText.cs | 4 +- src/Avalonia.Controls/RichTextBlock.cs | 194 +++++++++++++----- src/Avalonia.Controls/TextBlock.cs | 38 ++-- .../Media/TextFormatting/BiDiClassTests.cs | 2 +- .../Styling/SetterTests.cs | 2 +- 9 files changed, 174 insertions(+), 87 deletions(-) diff --git a/samples/Sandbox/MainWindow.axaml b/samples/Sandbox/MainWindow.axaml index 806f6d37da..a834e3fef3 100644 --- a/samples/Sandbox/MainWindow.axaml +++ b/samples/Sandbox/MainWindow.axaml @@ -13,6 +13,7 @@ . + diff --git a/src/Avalonia.Controls/Documents/InlineCollection.cs b/src/Avalonia.Controls/Documents/InlineCollection.cs index 2f27ca72d0..dc688fc359 100644 --- a/src/Avalonia.Controls/Documents/InlineCollection.cs +++ b/src/Avalonia.Controls/Documents/InlineCollection.cs @@ -136,7 +136,7 @@ namespace Avalonia.Controls.Documents base.Add(new Run(_text)); } - _text = string.Empty; + _text = null; } base.Add(item); @@ -160,8 +160,6 @@ namespace Avalonia.Controls.Documents Invalidated?.Invoke(this, EventArgs.Empty); } - private void Invalidate(object? sender, EventArgs e) => Invalidate(); - private void OnParentChanged(ILogical? parent) { foreach(var child in this) diff --git a/src/Avalonia.Controls/Documents/Span.cs b/src/Avalonia.Controls/Documents/Span.cs index 98851726da..c7289dbc3f 100644 --- a/src/Avalonia.Controls/Documents/Span.cs +++ b/src/Avalonia.Controls/Documents/Span.cs @@ -67,10 +67,12 @@ namespace Avalonia.Controls.Documents inline.AppendText(stringBuilder); } } - - if (Inlines.Text is string text) + else { - stringBuilder.Append(text); + if (Inlines.Text is string text) + { + stringBuilder.Append(text); + } } } @@ -87,9 +89,9 @@ namespace Avalonia.Controls.Documents } } - internal override void OnInlinesHostChanged(IInlineHost? oldValue, IInlineHost? newValue) + internal override void OnInlineHostChanged(IInlineHost? oldValue, IInlineHost? newValue) { - base.OnInlinesHostChanged(oldValue, newValue); + base.OnInlineHostChanged(oldValue, newValue); if(Inlines is not null) { diff --git a/src/Avalonia.Controls/Documents/TextElement.cs b/src/Avalonia.Controls/Documents/TextElement.cs index e75fd87615..5bac3642ed 100644 --- a/src/Avalonia.Controls/Documents/TextElement.cs +++ b/src/Avalonia.Controls/Documents/TextElement.cs @@ -259,11 +259,11 @@ namespace Avalonia.Controls.Documents { var oldValue = _inlineHost; _inlineHost = value; - OnInlinesHostChanged(oldValue, value); + OnInlineHostChanged(oldValue, value); } } - internal virtual void OnInlinesHostChanged(IInlineHost? oldValue, IInlineHost? newValue) + internal virtual void OnInlineHostChanged(IInlineHost? oldValue, IInlineHost? newValue) { } diff --git a/src/Avalonia.Controls/Primitives/AccessText.cs b/src/Avalonia.Controls/Primitives/AccessText.cs index 87cf660cad..7e5b34acd9 100644 --- a/src/Avalonia.Controls/Primitives/AccessText.cs +++ b/src/Avalonia.Controls/Primitives/AccessText.cs @@ -79,9 +79,9 @@ namespace Avalonia.Controls.Primitives } /// - protected override TextLayout CreateTextLayout(Size constraint, string? text) + protected override TextLayout CreateTextLayout(string? text) { - return base.CreateTextLayout(constraint, RemoveAccessKeyMarker(text)); + return base.CreateTextLayout(RemoveAccessKeyMarker(text)); } /// diff --git a/src/Avalonia.Controls/RichTextBlock.cs b/src/Avalonia.Controls/RichTextBlock.cs index 859503e693..1411d715ec 100644 --- a/src/Avalonia.Controls/RichTextBlock.cs +++ b/src/Avalonia.Controls/RichTextBlock.cs @@ -1,9 +1,10 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Avalonia.Controls.Documents; using Avalonia.Controls.Utils; using Avalonia.Input; +using Avalonia.Input.Platform; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Media.TextFormatting; @@ -56,6 +57,16 @@ namespace Avalonia.Controls AvaloniaProperty.Register( nameof(Inlines)); + public static readonly DirectProperty CanCopyProperty = + AvaloniaProperty.RegisterDirect( + nameof(CanCopy), + o => o.CanCopy); + + public static readonly RoutedEvent CopyingToClipboardEvent = + RoutedEvent.Register( + nameof(CopyingToClipboard), RoutingStrategies.Bubble); + + private bool _canCopy; private int _caretIndex; private int _selectionStart; private int _selectionEnd; @@ -75,7 +86,7 @@ namespace Avalonia.Controls InlineHost = this }; } - + public IBrush? SelectionBrush { get => GetValue(SelectionBrushProperty); @@ -156,50 +167,43 @@ namespace Avalonia.Controls } /// - /// Creates the used to render the text. + /// Property for determining if the Copy command can be executed. /// - /// The constraint of the text. - /// The text to format. - /// A object. - protected override TextLayout CreateTextLayout(Size constraint, string? text) + public bool CanCopy { - var defaultProperties = new GenericTextRunProperties( - new Typeface(FontFamily, FontStyle, FontWeight, FontStretch), - FontSize, - TextDecorations, - Foreground); + get => _canCopy; + private set => SetAndRaise(CanCopyProperty, ref _canCopy, value); + } - var paragraphProperties = new GenericTextParagraphProperties(FlowDirection, TextAlignment, true, false, - defaultProperties, TextWrapping, LineHeight, 0); + public event EventHandler? CopyingToClipboard + { + add => AddHandler(CopyingToClipboardEvent, value); + remove => RemoveHandler(CopyingToClipboardEvent, value); + } - ITextSource textSource; + public async void Copy() + { + if (_canCopy || !IsTextSelectionEnabled) + { + return; + } - var inlines = Inlines; + var text = GetSelection(); - if (inlines is not null && inlines.HasComplexContent) + if (string.IsNullOrEmpty(text)) { - var textRuns = new List(); + return; + } - foreach (var inline in inlines) - { - inline.BuildTextRun(textRuns); - } + var eventArgs = new RoutedEventArgs(CopyingToClipboardEvent); - textSource = new InlinesTextSource(textRuns); - } - else + RaiseEvent(eventArgs); + + if (!eventArgs.Handled) { - textSource = new SimpleTextSource((text ?? "").AsMemory(), defaultProperties); + await ((IClipboard)AvaloniaLocator.Current.GetRequiredService(typeof(IClipboard))) + .SetTextAsync(text); } - - return new TextLayout( - textSource, - paragraphProperties, - TextTrimming, - constraint.Width, - constraint.Height, - maxLines: MaxLines, - lineHeight: LineHeight); } public override void Render(DrawingContext context) @@ -236,7 +240,7 @@ namespace Avalonia.Controls return; } - var text = Inlines.Text ?? Text; + var text = Text; SelectionStart = 0; SelectionEnd = text?.Length ?? 0; @@ -255,6 +259,75 @@ namespace Avalonia.Controls SelectionEnd = SelectionStart; } + + protected override string? GetText() + { + return _text ?? Inlines.Text; + } + + protected override void SetText(string? text) + { + var oldValue = _text ?? Inlines?.Text; + + if (Inlines is not null && Inlines.HasComplexContent) + { + Inlines.Text = text; + + _text = null; + } + else + { + _text = text; + } + + RaisePropertyChanged(TextProperty, oldValue, text); + } + + /// + /// Creates the used to render the text. + /// + /// A object. + protected override TextLayout CreateTextLayout(string? text) + { + var defaultProperties = new GenericTextRunProperties( + new Typeface(FontFamily, FontStyle, FontWeight, FontStretch), + FontSize, + TextDecorations, + Foreground); + + var paragraphProperties = new GenericTextParagraphProperties(FlowDirection, TextAlignment, true, false, + defaultProperties, TextWrapping, LineHeight, 0); + + ITextSource textSource; + + var inlines = Inlines; + + if (inlines is not null && inlines.HasComplexContent) + { + var textRuns = new List(); + + foreach (var inline in inlines) + { + inline.BuildTextRun(textRuns); + } + + textSource = new InlinesTextSource(textRuns); + } + else + { + textSource = new SimpleTextSource((text ?? "").AsMemory(), defaultProperties); + } + + return new TextLayout( + textSource, + paragraphProperties, + TextTrimming, + _constraint.Width, + _constraint.Height, + maxLines: MaxLines, + lineHeight: LineHeight); + } + protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); @@ -262,6 +335,24 @@ namespace Avalonia.Controls ClearSelection(); } + protected override void OnKeyDown(KeyEventArgs e) + { + var handled = false; + var modifiers = e.KeyModifiers; + var keymap = AvaloniaLocator.Current.GetRequiredService(); + + bool Match(List gestures) => gestures.Any(g => g.Matches(e)); + + if (Match(keymap.Copy)) + { + Copy(); + + handled = true; + } + + e.Handled = handled; + } + protected override void OnPointerPressed(PointerPressedEventArgs e) { if (!IsTextSelectionEnabled) @@ -269,20 +360,21 @@ namespace Avalonia.Controls return; } - var text = Inlines.Text; + var text = Text; var clickInfo = e.GetCurrentPoint(this); if (text != null && clickInfo.Properties.IsLeftButtonPressed) { var point = e.GetPosition(this); - var clickToSelect = e.KeyModifiers.HasFlag(KeyModifiers.Shift); - - var hit = TextLayout.HitTestPoint(point); + var clickToSelect = e.KeyModifiers.HasFlag(KeyModifiers.Shift); var oldIndex = CaretIndex; + + var hit = TextLayout.HitTestPoint(point); var index = hit.TextPosition; - CaretIndex = index; + + SetAndRaise(CaretIndexProperty, ref _caretIndex, index); #pragma warning disable CS0618 // Type or member is obsolete switch (e.ClickCount) @@ -368,7 +460,7 @@ namespace Avalonia.Controls caretIndex >= firstSelection && caretIndex <= lastSelection; if (!didClickInSelection) { - _caretIndex = SelectionEnd = SelectionStart = caretIndex; + CaretIndex = SelectionEnd = SelectionStart = caretIndex; } } @@ -389,29 +481,19 @@ namespace Avalonia.Controls } case nameof(TextProperty): { - OnTextChanged(change.OldValue as string, change.NewValue as string); + InvalidateTextLayout(); break; } } } - private void OnTextChanged(string? oldValue, string? newValue) + private string GetSelection() { - if (oldValue == newValue) - { - return; - } - - if (Inlines is null) + if (!IsTextSelectionEnabled) { - return; + return ""; } - Inlines.Text = newValue; - } - - private string GetSelection() - { var text = Inlines.Text ?? Text; if (string.IsNullOrEmpty(text)) diff --git a/src/Avalonia.Controls/TextBlock.cs b/src/Avalonia.Controls/TextBlock.cs index 1f891b092f..2f83ee1002 100644 --- a/src/Avalonia.Controls/TextBlock.cs +++ b/src/Avalonia.Controls/TextBlock.cs @@ -130,7 +130,7 @@ namespace Avalonia.Controls protected string? _text; protected TextLayout? _textLayout; - private Size _constraint; + protected Size _constraint; /// /// Initializes static members of the class. @@ -149,7 +149,7 @@ namespace Avalonia.Controls { get { - return _textLayout ??= CreateTextLayout(_constraint, Text); + return _textLayout ??= CreateTextLayout(_text); } } @@ -176,11 +176,8 @@ namespace Avalonia.Controls /// public string? Text { - get => _text; - set - { - SetAndRaise(TextProperty, ref _text, value); - } + get => GetText(); + set => SetText(value); } /// @@ -302,11 +299,6 @@ namespace Avalonia.Controls set { SetValue(BaselineOffsetProperty, value); } } - public void Add(string text) - { - Text = text; - } - /// /// Reads the attached property from the given element /// @@ -481,6 +473,10 @@ namespace Avalonia.Controls control.SetValue(MaxLinesProperty, maxLines); } + public void Add(string text) + { + _text = text; + } /// /// Renders the to a drawing context. @@ -516,13 +512,21 @@ namespace Avalonia.Controls TextLayout.Draw(context, new Point(padding.Left, top)); } + protected virtual string? GetText() + { + return _text; + } + + protected virtual void SetText(string? text) + { + SetAndRaise(TextProperty, ref _text, text); + } + /// /// Creates the used to render the text. /// - /// The constraint of the text. - /// The text to format. /// A object. - protected virtual TextLayout CreateTextLayout(Size constraint, string? text) + protected virtual TextLayout CreateTextLayout(string? text) { var defaultProperties = new GenericTextRunProperties( new Typeface(FontFamily, FontStyle, FontWeight, FontStretch), @@ -537,8 +541,8 @@ namespace Avalonia.Controls new SimpleTextSource((text ?? "").AsMemory(), defaultProperties), paragraphProperties, TextTrimming, - constraint.Width, - constraint.Height, + _constraint.Width, + _constraint.Height, maxLines: MaxLines, lineHeight: LineHeight); } diff --git a/tests/Avalonia.Base.UnitTests/Media/TextFormatting/BiDiClassTests.cs b/tests/Avalonia.Base.UnitTests/Media/TextFormatting/BiDiClassTests.cs index 1ed33e6132..f29420ff87 100644 --- a/tests/Avalonia.Base.UnitTests/Media/TextFormatting/BiDiClassTests.cs +++ b/tests/Avalonia.Base.UnitTests/Media/TextFormatting/BiDiClassTests.cs @@ -30,7 +30,7 @@ namespace Avalonia.Visuals.UnitTests.Media.TextFormatting private bool Run(BiDiClassData t) { - var bidi = BidiAlgorithm.Instance.Value; + var bidi = new BidiAlgorithm(); var bidiData = new BidiData(t.ParagraphLevel); var text = Encoding.UTF32.GetString(MemoryMarshal.Cast(t.CodePoints).ToArray()); diff --git a/tests/Avalonia.Base.UnitTests/Styling/SetterTests.cs b/tests/Avalonia.Base.UnitTests/Styling/SetterTests.cs index ed4c78aa3e..99dfc93a68 100644 --- a/tests/Avalonia.Base.UnitTests/Styling/SetterTests.cs +++ b/tests/Avalonia.Base.UnitTests/Styling/SetterTests.cs @@ -49,7 +49,7 @@ namespace Avalonia.Base.UnitTests.Styling setter.Instance(control).Start(false); - Assert.Equal("", control.Text); + Assert.Equal(null, control.Text); } [Fact] From f4a38437314b00f99122c2b36d14a016c26a8c52 Mon Sep 17 00:00:00 2001 From: Benedikt Stebner Date: Mon, 27 Jun 2022 09:49:21 +0200 Subject: [PATCH 4/9] Fix unit test --- tests/Avalonia.Controls.UnitTests/TextBlockTests.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs b/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs index 6da011f062..37dde9fbac 100644 --- a/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs +++ b/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs @@ -20,13 +20,11 @@ namespace Avalonia.Controls.UnitTests } [Fact] - public void Default_Text_Value_Should_Be_EmptyString() + public void Default_Text_Value_Should_Be_Null() { var textBlock = new TextBlock(); - Assert.Equal( - "", - textBlock.Text); + Assert.Equal(null, textBlock.Text); } [Fact] From 5dc768aa13435f4f126dae6e2d778df9f66b0da1 Mon Sep 17 00:00:00 2001 From: Benedikt Stebner Date: Mon, 4 Jul 2022 12:11:34 +0200 Subject: [PATCH 5/9] Add some xml comments --- src/Avalonia.Controls/RichTextBlock.cs | 71 +++++++++++--------------- src/Avalonia.Controls/TextBlock.cs | 2 - 2 files changed, 31 insertions(+), 42 deletions(-) diff --git a/src/Avalonia.Controls/RichTextBlock.cs b/src/Avalonia.Controls/RichTextBlock.cs index 1411d715ec..2b84113497 100644 --- a/src/Avalonia.Controls/RichTextBlock.cs +++ b/src/Avalonia.Controls/RichTextBlock.cs @@ -14,19 +14,13 @@ using Avalonia.Utilities; namespace Avalonia.Controls { /// - /// A control that displays a block of text. + /// A control that displays a block of formatted text. /// public class RichTextBlock : TextBlock, IInlineHost { public static readonly StyledProperty IsTextSelectionEnabledProperty = AvaloniaProperty.Register(nameof(IsTextSelectionEnabled), false); - public static readonly DirectProperty CaretIndexProperty = - AvaloniaProperty.RegisterDirect( - nameof(CaretIndex), - o => o.CaretIndex, - (o, v) => o.CaretIndex = v); - public static readonly DirectProperty SelectionStartProperty = AvaloniaProperty.RegisterDirect( nameof(SelectionStart), @@ -67,7 +61,6 @@ namespace Avalonia.Controls nameof(CopyingToClipboard), RoutingStrategies.Bubble); private bool _canCopy; - private int _caretIndex; private int _selectionStart; private int _selectionEnd; @@ -86,31 +79,28 @@ namespace Avalonia.Controls InlineHost = this }; } - + + /// + /// Gets or sets the brush that highlights selected text. + /// public IBrush? SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } + /// + /// Gets or sets a value that defines the brush used for selected text. + /// public IBrush? SelectionForegroundBrush { get => GetValue(SelectionForegroundBrushProperty); set => SetValue(SelectionForegroundBrushProperty, value); } - public int CaretIndex - { - get => _caretIndex; - set - { - if(SetAndRaise(CaretIndexProperty, ref _caretIndex, value)) - { - SelectionStart = SelectionEnd = value; - } - } - } - + /// + /// Gets or sets a character index for the beginning of the current selection. + /// public int SelectionStart { get => _selectionStart; @@ -119,37 +109,36 @@ namespace Avalonia.Controls if (SetAndRaise(SelectionStartProperty, ref _selectionStart, value)) { RaisePropertyChanged(SelectedTextProperty, "", ""); - - if (SelectionEnd == value && CaretIndex != value) - { - CaretIndex = value; - } } } } + /// + /// Gets or sets a character index for the end of the current selection. + /// public int SelectionEnd { get => _selectionEnd; set { - if(SetAndRaise(SelectionEndProperty, ref _selectionEnd, value)) + if (SetAndRaise(SelectionEndProperty, ref _selectionEnd, value)) { RaisePropertyChanged(SelectedTextProperty, "", ""); - - if (SelectionStart == value && CaretIndex != value) - { - CaretIndex = value; - } } } } + /// + /// Gets the content of the current selection. + /// public string SelectedText { get => GetSelection(); } + /// + /// Gets or sets a value that indicates whether text selection is enabled, either through user action or calling selection-related API. + /// public bool IsTextSelectionEnabled { get => GetValue(IsTextSelectionEnabledProperty); @@ -181,6 +170,9 @@ namespace Avalonia.Controls remove => RemoveHandler(CopyingToClipboardEvent, value); } + /// + /// Copies the current selection to the Clipboard. + /// public async void Copy() { if (_canCopy || !IsTextSelectionEnabled) @@ -259,7 +251,6 @@ namespace Avalonia.Controls SelectionEnd = SelectionStart; } - protected override string? GetText() { return _text ?? Inlines.Text; @@ -344,13 +335,13 @@ namespace Avalonia.Controls bool Match(List gestures) => gestures.Any(g => g.Matches(e)); if (Match(keymap.Copy)) - { + { Copy(); - + handled = true; } - e.Handled = handled; + e.Handled = handled; } protected override void OnPointerPressed(PointerPressedEventArgs e) @@ -367,14 +358,14 @@ namespace Avalonia.Controls { var point = e.GetPosition(this); - var clickToSelect = e.KeyModifiers.HasFlag(KeyModifiers.Shift); + var clickToSelect = e.KeyModifiers.HasFlag(KeyModifiers.Shift); - var oldIndex = CaretIndex; + var oldIndex = SelectionStart; var hit = TextLayout.HitTestPoint(point); var index = hit.TextPosition; - SetAndRaise(CaretIndexProperty, ref _caretIndex, index); + SelectionStart = SelectionEnd = index; #pragma warning disable CS0618 // Type or member is obsolete switch (e.ClickCount) @@ -460,7 +451,7 @@ namespace Avalonia.Controls caretIndex >= firstSelection && caretIndex <= lastSelection; if (!didClickInSelection) { - CaretIndex = SelectionEnd = SelectionStart = caretIndex; + SelectionStart = SelectionEnd = caretIndex; } } diff --git a/src/Avalonia.Controls/TextBlock.cs b/src/Avalonia.Controls/TextBlock.cs index 27f7fc28b3..52261d1c76 100644 --- a/src/Avalonia.Controls/TextBlock.cs +++ b/src/Avalonia.Controls/TextBlock.cs @@ -1,11 +1,9 @@ using System; -using System.Collections.Generic; using Avalonia.Automation.Peers; using Avalonia.Controls.Documents; using Avalonia.Layout; using Avalonia.Media; using Avalonia.Media.TextFormatting; -using Avalonia.Metadata; using Avalonia.Utilities; namespace Avalonia.Controls From 84a4de5c070f9dde1e0e752194f51c76daa978d3 Mon Sep 17 00:00:00 2001 From: Dan Walmsley Date: Wed, 6 Jul 2022 16:43:50 +0100 Subject: [PATCH 6/9] make splitview not culture sensitive. --- src/Avalonia.Controls/SplitView.cs | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/Avalonia.Controls/SplitView.cs b/src/Avalonia.Controls/SplitView.cs index 532cb1d329..caefad4af7 100644 --- a/src/Avalonia.Controls/SplitView.cs +++ b/src/Avalonia.Controls/SplitView.cs @@ -431,18 +431,40 @@ namespace Avalonia.Controls } } + private string GetPsuedoClass(SplitViewDisplayMode mode) + { + return mode switch + { + SplitViewDisplayMode.Inline => "inline", + SplitViewDisplayMode.CompactInline => "compactinline", + SplitViewDisplayMode.Overlay => "overlay", + SplitViewDisplayMode.CompactOverlay => "compactoverlay", + _ => throw new ArgumentOutOfRangeException(nameof(mode), mode, null) + }; + } + + private string GetPsuedoClass(SplitViewPanePlacement placement) + { + return placement switch + { + SplitViewPanePlacement.Left => "left", + SplitViewPanePlacement.Right => "right", + _ => throw new ArgumentOutOfRangeException(nameof(placement), placement, null) + }; + } + private void OnPanePlacementChanged(AvaloniaPropertyChangedEventArgs e) { - var oldState = e.OldValue!.ToString()!.ToLower(); - var newState = e.NewValue!.ToString()!.ToLower(); + var oldState = GetPsuedoClass(e.GetOldValue()); + var newState = GetPsuedoClass(e.GetNewValue()); PseudoClasses.Remove($":{oldState}"); PseudoClasses.Add($":{newState}"); } private void OnDisplayModeChanged(AvaloniaPropertyChangedEventArgs e) { - var oldState = e.OldValue!.ToString()!.ToLower(); - var newState = e.NewValue!.ToString()!.ToLower(); + var oldState = GetPsuedoClass(e.GetOldValue()); + var newState = GetPsuedoClass(e.GetNewValue()); PseudoClasses.Remove($":{oldState}"); PseudoClasses.Add($":{newState}"); From b7a3bce6f99202fce9128c9824d3157e91c6d615 Mon Sep 17 00:00:00 2001 From: Dan Walmsley Date: Wed, 6 Jul 2022 17:21:41 +0100 Subject: [PATCH 7/9] fix compiler warning. --- src/Avalonia.Controls/SplitView.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Avalonia.Controls/SplitView.cs b/src/Avalonia.Controls/SplitView.cs index caefad4af7..f560251e53 100644 --- a/src/Avalonia.Controls/SplitView.cs +++ b/src/Avalonia.Controls/SplitView.cs @@ -469,7 +469,7 @@ namespace Avalonia.Controls PseudoClasses.Remove($":{oldState}"); PseudoClasses.Add($":{newState}"); - var (closedPaneWidth, paneColumnGridLength) = (SplitViewDisplayMode)e.NewValue switch + var (closedPaneWidth, paneColumnGridLength) = e.GetNewValue() switch { SplitViewDisplayMode.Overlay => (0, new GridLength(0, GridUnitType.Pixel)), SplitViewDisplayMode.CompactOverlay => (CompactPaneLength, new GridLength(CompactPaneLength, GridUnitType.Pixel)), From cc2d791f3683ae77c21ba8d7b9ece37ac8852a7e Mon Sep 17 00:00:00 2001 From: Benedikt Stebner Date: Wed, 6 Jul 2022 19:45:01 +0200 Subject: [PATCH 8/9] Update samples/Sandbox/MainWindow.axaml Co-authored-by: Max Katz --- samples/Sandbox/MainWindow.axaml | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/samples/Sandbox/MainWindow.axaml b/samples/Sandbox/MainWindow.axaml index a834e3fef3..6929f192c7 100644 --- a/samples/Sandbox/MainWindow.axaml +++ b/samples/Sandbox/MainWindow.axaml @@ -1,19 +1,4 @@ - - - - This is a - TextBlock - with several - Span elements, - - using a variety of styles - . - - - - - From 45ae4221dc8cf2f40a92c4d57dbdca7a3aacdd64 Mon Sep 17 00:00:00 2001 From: Dan Walmsley Date: Wed, 6 Jul 2022 20:58:36 +0100 Subject: [PATCH 9/9] correct spelling. --- src/Avalonia.Controls/SplitView.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Avalonia.Controls/SplitView.cs b/src/Avalonia.Controls/SplitView.cs index f560251e53..c344dd795d 100644 --- a/src/Avalonia.Controls/SplitView.cs +++ b/src/Avalonia.Controls/SplitView.cs @@ -431,7 +431,7 @@ namespace Avalonia.Controls } } - private string GetPsuedoClass(SplitViewDisplayMode mode) + private string GetPseudoClass(SplitViewDisplayMode mode) { return mode switch { @@ -443,7 +443,7 @@ namespace Avalonia.Controls }; } - private string GetPsuedoClass(SplitViewPanePlacement placement) + private string GetPseudoClass(SplitViewPanePlacement placement) { return placement switch { @@ -455,16 +455,16 @@ namespace Avalonia.Controls private void OnPanePlacementChanged(AvaloniaPropertyChangedEventArgs e) { - var oldState = GetPsuedoClass(e.GetOldValue()); - var newState = GetPsuedoClass(e.GetNewValue()); + var oldState = GetPseudoClass(e.GetOldValue()); + var newState = GetPseudoClass(e.GetNewValue()); PseudoClasses.Remove($":{oldState}"); PseudoClasses.Add($":{newState}"); } private void OnDisplayModeChanged(AvaloniaPropertyChangedEventArgs e) { - var oldState = GetPsuedoClass(e.GetOldValue()); - var newState = GetPsuedoClass(e.GetNewValue()); + var oldState = GetPseudoClass(e.GetOldValue()); + var newState = GetPseudoClass(e.GetNewValue()); PseudoClasses.Remove($":{oldState}"); PseudoClasses.Add($":{newState}");