From 01c6bf4bb79c006d8998d3994b1c04bc9bb08ed7 Mon Sep 17 00:00:00 2001 From: Tim Date: Fri, 9 Sep 2022 12:48:43 +0200 Subject: [PATCH 01/55] Add DisplayMemberBinding to ItemsControl --- .../Generators/IItemContainerGenerator.cs | 6 ++++++ .../Generators/ItemContainerGenerator.cs | 13 ++++++++++++- .../Generators/ItemContainerGenerator`1.cs | 12 ++++++++++-- .../Generators/TreeItemContainerGenerator.cs | 10 +++++++++- src/Avalonia.Controls/ItemsControl.cs | 19 +++++++++++++++++++ .../Presenters/ItemsPresenterBase.cs | 17 +++++++++++++++++ 6 files changed, 73 insertions(+), 4 deletions(-) diff --git a/src/Avalonia.Controls/Generators/IItemContainerGenerator.cs b/src/Avalonia.Controls/Generators/IItemContainerGenerator.cs index f9772cb399..79c77f2519 100644 --- a/src/Avalonia.Controls/Generators/IItemContainerGenerator.cs +++ b/src/Avalonia.Controls/Generators/IItemContainerGenerator.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Avalonia.Controls.Templates; +using Avalonia.Data; using Avalonia.Styling; namespace Avalonia.Controls.Generators @@ -24,6 +25,11 @@ namespace Avalonia.Controls.Generators /// Gets or sets the data template used to display the items in the control. /// IDataTemplate? ItemTemplate { get; set; } + + /// + /// Gets or sets the binding to use to bind to the member of an item used for displaying + /// + IBinding? DisplayMemberBinding { get; set; } /// /// Gets the ContainerType, or null if its an untyped ContainerGenerator. diff --git a/src/Avalonia.Controls/Generators/ItemContainerGenerator.cs b/src/Avalonia.Controls/Generators/ItemContainerGenerator.cs index 8b36b07cec..42f0124295 100644 --- a/src/Avalonia.Controls/Generators/ItemContainerGenerator.cs +++ b/src/Avalonia.Controls/Generators/ItemContainerGenerator.cs @@ -45,6 +45,9 @@ namespace Avalonia.Controls.Generators /// Gets or sets the data template used to display the items in the control. /// public IDataTemplate? ItemTemplate { get; set; } + + /// + public IBinding? DisplayMemberBinding { get; set; } /// /// Gets the owner control. @@ -189,7 +192,15 @@ namespace Avalonia.Controls.Generators if (result == null) { result = new ContentPresenter(); - result.SetValue(ContentPresenter.ContentProperty, item, BindingPriority.Style); + if (DisplayMemberBinding is not null) + { + result.SetValue(StyledElement.DataContextProperty, item, BindingPriority.Style); + result.Bind(ContentPresenter.ContentProperty, DisplayMemberBinding, BindingPriority.Style); + } + else + { + result.SetValue(ContentPresenter.ContentProperty, item, BindingPriority.Style); + } if (ItemTemplate != null) { diff --git a/src/Avalonia.Controls/Generators/ItemContainerGenerator`1.cs b/src/Avalonia.Controls/Generators/ItemContainerGenerator`1.cs index 3ff1b0702d..5e965a9d04 100644 --- a/src/Avalonia.Controls/Generators/ItemContainerGenerator`1.cs +++ b/src/Avalonia.Controls/Generators/ItemContainerGenerator`1.cs @@ -53,8 +53,16 @@ namespace Avalonia.Controls.Generators container.SetValue(ContentTemplateProperty, ItemTemplate, BindingPriority.Style); } - container.SetValue(ContentProperty, item, BindingPriority.Style); - + if (DisplayMemberBinding is not null) + { + container.SetValue(StyledElement.DataContextProperty, item, BindingPriority.Style); + container.Bind(ContentProperty, DisplayMemberBinding, BindingPriority.Style); + } + else + { + container.SetValue(ContentProperty, item, BindingPriority.Style); + } + if (!(item is IControl)) { container.DataContext = item; diff --git a/src/Avalonia.Controls/Generators/TreeItemContainerGenerator.cs b/src/Avalonia.Controls/Generators/TreeItemContainerGenerator.cs index 4e3deb5552..9f9845b14f 100644 --- a/src/Avalonia.Controls/Generators/TreeItemContainerGenerator.cs +++ b/src/Avalonia.Controls/Generators/TreeItemContainerGenerator.cs @@ -76,7 +76,15 @@ namespace Avalonia.Controls.Generators result.SetValue(Control.ThemeProperty, ItemContainerTheme, BindingPriority.Style); } - result.SetValue(ContentProperty, template.Build(item), BindingPriority.Style); + if (DisplayMemberBinding is not null) + { + result.SetValue(StyledElement.DataContextProperty, item, BindingPriority.Style); + result.Bind(ContentProperty, DisplayMemberBinding, BindingPriority.Style); + } + else + { + result.SetValue(ContentProperty, item, BindingPriority.Style); + } var itemsSelector = template.ItemsSelector(item); diff --git a/src/Avalonia.Controls/ItemsControl.cs b/src/Avalonia.Controls/ItemsControl.cs index 345e7fcac8..e9ce7912a7 100644 --- a/src/Avalonia.Controls/ItemsControl.cs +++ b/src/Avalonia.Controls/ItemsControl.cs @@ -11,6 +11,7 @@ using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Controls.Utils; +using Avalonia.Data; using Avalonia.Input; using Avalonia.LogicalTree; using Avalonia.Metadata; @@ -61,6 +62,23 @@ namespace Avalonia.Controls public static readonly StyledProperty ItemTemplateProperty = AvaloniaProperty.Register(nameof(ItemTemplate)); + + /// + /// Defines the property + /// + public static readonly StyledProperty DisplayMemberBindingProperty = + AvaloniaProperty.Register(nameof(DisplayMemberBinding)); + + /// + /// Gets or sets the to use for binding to the display member of each item. + /// + [AssignBinding] + public IBinding? DisplayMemberBinding + { + get { return GetValue(DisplayMemberBindingProperty); } + set { SetValue(DisplayMemberBindingProperty, value); } + } + private IEnumerable? _items = new AvaloniaList(); private int _itemCount; private IItemContainerGenerator? _itemContainerGenerator; @@ -97,6 +115,7 @@ namespace Avalonia.Controls _itemContainerGenerator.ItemContainerTheme = ItemContainerTheme; _itemContainerGenerator.ItemTemplate = ItemTemplate; + _itemContainerGenerator.DisplayMemberBinding = DisplayMemberBinding; _itemContainerGenerator.Materialized += (_, e) => OnContainersMaterialized(e); _itemContainerGenerator.Dematerialized += (_, e) => OnContainersDematerialized(e); _itemContainerGenerator.Recycled += (_, e) => OnContainersRecycled(e); diff --git a/src/Avalonia.Controls/Presenters/ItemsPresenterBase.cs b/src/Avalonia.Controls/Presenters/ItemsPresenterBase.cs index 2821fa8cf0..836433cdf8 100644 --- a/src/Avalonia.Controls/Presenters/ItemsPresenterBase.cs +++ b/src/Avalonia.Controls/Presenters/ItemsPresenterBase.cs @@ -5,6 +5,7 @@ using Avalonia.Collections; using Avalonia.Controls.Generators; using Avalonia.Controls.Templates; using Avalonia.Controls.Utils; +using Avalonia.Data; using Avalonia.LogicalTree; using Avalonia.Styling; @@ -33,6 +34,12 @@ namespace Avalonia.Controls.Presenters public static readonly StyledProperty ItemTemplateProperty = ItemsControl.ItemTemplateProperty.AddOwner(); + /// + /// Defines the property + /// + public static readonly StyledProperty DisplayMemberBindingProperty = + ItemsControl.DisplayMemberBindingProperty.AddOwner(); + private IEnumerable? _items; private IDisposable? _itemsSubscription; private bool _createdPanel; @@ -120,6 +127,15 @@ namespace Avalonia.Controls.Presenters set { SetValue(ItemTemplateProperty, value); } } + /// + /// Gets or sets the to use for binding to the display member of each item. + /// + public IBinding? DisplayMemberBinding + { + get { return GetValue(DisplayMemberBindingProperty); } + set { SetValue(DisplayMemberBindingProperty, value); } + } + /// /// Gets the panel used to display the items. /// @@ -177,6 +193,7 @@ namespace Avalonia.Controls.Presenters { result = new ItemContainerGenerator(this); result.ItemTemplate = ItemTemplate; + result.DisplayMemberBinding = DisplayMemberBinding; } result.Materialized += ContainerActionHandler; From 30e46518693d4bb2e14ddede6b2c00448cd0fc31 Mon Sep 17 00:00:00 2001 From: Tim Date: Mon, 19 Sep 2022 13:48:26 +0200 Subject: [PATCH 02/55] Add TabItem HeaderDisplayMemberBinding --- .../Generators/TabItemContainerGenerator.cs | 7 +++++++ src/Avalonia.Controls/TabControl.cs | 17 +++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/Avalonia.Controls/Generators/TabItemContainerGenerator.cs b/src/Avalonia.Controls/Generators/TabItemContainerGenerator.cs index c6b0bda9af..4021b8436a 100644 --- a/src/Avalonia.Controls/Generators/TabItemContainerGenerator.cs +++ b/src/Avalonia.Controls/Generators/TabItemContainerGenerator.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; +using Avalonia.Data; using Avalonia.LogicalTree; using Avalonia.Reactive; using Avalonia.VisualTree; @@ -33,6 +34,12 @@ namespace Avalonia.Controls.Generators TabControl.ItemTemplateProperty)); } + if (Owner.HeaderDisplayMemberBinding is not null) + { + tabItem.Bind(HeaderedContentControl.HeaderProperty, Owner.HeaderDisplayMemberBinding, + BindingPriority.Style); + } + if (tabItem.Header == null) { if (item is IHeadered headered) diff --git a/src/Avalonia.Controls/TabControl.cs b/src/Avalonia.Controls/TabControl.cs index 70fecc7ce1..63738716c0 100644 --- a/src/Avalonia.Controls/TabControl.cs +++ b/src/Avalonia.Controls/TabControl.cs @@ -12,6 +12,7 @@ using Avalonia.LogicalTree; using Avalonia.VisualTree; using Avalonia.Automation; using Avalonia.Controls.Metadata; +using Avalonia.Data; namespace Avalonia.Controls { @@ -57,6 +58,12 @@ namespace Avalonia.Controls public static readonly StyledProperty SelectedContentTemplateProperty = AvaloniaProperty.Register(nameof(SelectedContentTemplate)); + /// + /// Defines the property + /// + public static readonly StyledProperty HeaderDisplayMemberBindingProperty = + AvaloniaProperty.Register(nameof(HeaderDisplayMemberBinding)); + /// /// The default value for the property. /// @@ -134,6 +141,16 @@ namespace Avalonia.Controls get { return GetValue(SelectedContentTemplateProperty); } internal set { SetValue(SelectedContentTemplateProperty, value); } } + + /// + /// Gets or sets the to use for binding to the display member of each tab-items header. + /// + [AssignBinding] + public IBinding? HeaderDisplayMemberBinding + { + get { return GetValue(HeaderDisplayMemberBindingProperty); } + set { SetValue(HeaderDisplayMemberBindingProperty, value); } + } internal ItemsPresenter? ItemsPresenterPart { get; private set; } From dcebd4f5ab8a496b7f2a91490806f676241e6fd7 Mon Sep 17 00:00:00 2001 From: Tim Date: Mon, 19 Sep 2022 13:49:22 +0200 Subject: [PATCH 03/55] Update TabControl-Demo to use the new added HeaderDisplayMemberBinding --- samples/ControlCatalog/Pages/TabControlPage.xaml | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/samples/ControlCatalog/Pages/TabControlPage.xaml b/samples/ControlCatalog/Pages/TabControlPage.xaml index cba6fcd0ad..90afb5ceca 100644 --- a/samples/ControlCatalog/Pages/TabControlPage.xaml +++ b/samples/ControlCatalog/Pages/TabControlPage.xaml @@ -51,15 +51,9 @@ - - - - - - - + From ab4bb208f56eee4a06dd052eece7afa642e5753f Mon Sep 17 00:00:00 2001 From: Tim Date: Thu, 22 Sep 2022 14:31:02 +0200 Subject: [PATCH 04/55] Add Unit Test --- .../ItemsControlTests.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/Avalonia.Controls.UnitTests/ItemsControlTests.cs b/tests/Avalonia.Controls.UnitTests/ItemsControlTests.cs index f08653a4f8..944f974cb0 100644 --- a/tests/Avalonia.Controls.UnitTests/ItemsControlTests.cs +++ b/tests/Avalonia.Controls.UnitTests/ItemsControlTests.cs @@ -4,6 +4,7 @@ using System.Linq; using Avalonia.Collections; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; +using Avalonia.Data; using Avalonia.Input; using Avalonia.LogicalTree; using Avalonia.Styling; @@ -736,6 +737,25 @@ namespace Avalonia.Controls.UnitTests root.Child = null; root.Child = target; } + + [Fact] + public void Should_Use_DisplayMemberBinding() + { + var target = new ItemsControl + { + Template = GetTemplate(), + DisplayMemberBinding = new Binding("Length") + }; + + target.Items = new[] { "Foo" }; + target.ApplyTemplate(); + target.Presenter.ApplyTemplate(); + + var container = (ContentPresenter)target.Presenter.Panel.Children[0]; + container.UpdateChild(); + + Assert.Equal(container.Child!.GetValue(TextBlock.TextProperty), "3"); + } private class Item { From 42e27d89508a5a523f24c1eb1f2f272154b6a374 Mon Sep 17 00:00:00 2001 From: Tim Date: Fri, 7 Oct 2022 15:40:23 +0200 Subject: [PATCH 05/55] Fix Tests --- src/Avalonia.Controls/Generators/TreeItemContainerGenerator.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Avalonia.Controls/Generators/TreeItemContainerGenerator.cs b/src/Avalonia.Controls/Generators/TreeItemContainerGenerator.cs index 9f9845b14f..2d8cb05e03 100644 --- a/src/Avalonia.Controls/Generators/TreeItemContainerGenerator.cs +++ b/src/Avalonia.Controls/Generators/TreeItemContainerGenerator.cs @@ -83,7 +83,7 @@ namespace Avalonia.Controls.Generators } else { - result.SetValue(ContentProperty, item, BindingPriority.Style); + result.SetValue(ContentProperty, template.Build(item), BindingPriority.Style); } var itemsSelector = template.ItemsSelector(item); From 2a2add7d4dbb54c271296f17a545d28d3f829cf6 Mon Sep 17 00:00:00 2001 From: Tim <47110241+timunie@users.noreply.github.com> Date: Mon, 10 Oct 2022 14:59:39 +0200 Subject: [PATCH 06/55] Update ListBoxPage: - Added ItemModel - Enable CompiledBindings - Use DisplayMemberBinding --- samples/ControlCatalog/Pages/ListBoxPage.xaml | 4 +++ .../ViewModels/ListBoxPageViewModel.cs | 36 ++++++++++++++++--- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/samples/ControlCatalog/Pages/ListBoxPage.xaml b/samples/ControlCatalog/Pages/ListBoxPage.xaml index 433592345a..067d4d9890 100644 --- a/samples/ControlCatalog/Pages/ListBoxPage.xaml +++ b/samples/ControlCatalog/Pages/ListBoxPage.xaml @@ -1,5 +1,8 @@ @@ -30,6 +33,7 @@ diff --git a/samples/ControlCatalog/ViewModels/ListBoxPageViewModel.cs b/samples/ControlCatalog/ViewModels/ListBoxPageViewModel.cs index 59489ebcc0..f89d9d1e20 100644 --- a/samples/ControlCatalog/ViewModels/ListBoxPageViewModel.cs +++ b/samples/ControlCatalog/ViewModels/ListBoxPageViewModel.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Reactive; using Avalonia.Controls; using Avalonia.Controls.Selection; +using ControlCatalog.Pages; using MiniMvvm; namespace ControlCatalog.ViewModels @@ -20,9 +21,9 @@ namespace ControlCatalog.ViewModels public ListBoxPageViewModel() { - Items = new ObservableCollection(Enumerable.Range(1, 10000).Select(i => GenerateItem())); + Items = new ObservableCollection(Enumerable.Range(1, 10000).Select(i => GenerateItem())); - Selection = new SelectionModel(); + Selection = new SelectionModel(); Selection.Select(1); _selectionMode = this.WhenAnyValue( @@ -58,8 +59,8 @@ namespace ControlCatalog.ViewModels }); } - public ObservableCollection Items { get; } - public SelectionModel Selection { get; } + public ObservableCollection Items { get; } + public SelectionModel Selection { get; } public IObservable SelectionMode => _selectionMode; public bool Multiple @@ -96,6 +97,31 @@ namespace ControlCatalog.ViewModels public MiniCommand RemoveItemCommand { get; } public MiniCommand SelectRandomItemCommand { get; } - private string GenerateItem() => $"Item {_counter++.ToString()}"; + private ItemModel GenerateItem() => new ItemModel(_counter ++); + } + + /// + /// An Item model for the + /// + public class ItemModel + { + /// + /// Creates a new ItemModel with the given ID + /// + /// The ID to display + public ItemModel(int id) + { + ID = id; + } + + /// + /// The ID of this Item + /// + public int ID { get; } + + public override string ToString() + { + return $"Item {ID}"; + } } } From 16f3114e61b4fdf535613aae47972d028f7f6766 Mon Sep 17 00:00:00 2001 From: amwx <40413319+amwx@users.noreply.github.com> Date: Sun, 20 Nov 2022 23:53:34 -0500 Subject: [PATCH 07/55] TextBox programmatic Undo/Redo & CanUndo/CanRedo --- src/Avalonia.Controls/TextBox.cs | 109 ++++++++++++++---- src/Avalonia.Controls/Utils/UndoRedoHelper.cs | 20 ++++ 2 files changed, 109 insertions(+), 20 deletions(-) diff --git a/src/Avalonia.Controls/TextBox.cs b/src/Avalonia.Controls/TextBox.cs index d5b45398e7..b06ec3492c 100644 --- a/src/Avalonia.Controls/TextBox.cs +++ b/src/Avalonia.Controls/TextBox.cs @@ -17,7 +17,6 @@ using Avalonia.Controls.Metadata; using Avalonia.Media.TextFormatting; using Avalonia.Media.TextFormatting.Unicode; using Avalonia.Automation.Peers; -using System.Diagnostics; using Avalonia.Threading; namespace Avalonia.Controls @@ -166,6 +165,18 @@ namespace Avalonia.Controls (o, v) => o.UndoLimit = v, unsetValue: -1); + /// + /// Defines the property + /// + public static readonly DirectProperty CanUndoProperty = + AvaloniaProperty.RegisterDirect(nameof(CanUndo), x => x.CanUndo); + + /// + /// Defines the property + /// + public static readonly DirectProperty CanRedoProperty = + AvaloniaProperty.RegisterDirect(nameof(CanRedo), x => x.CanRedo); + /// /// Defines the event. /// @@ -232,6 +243,8 @@ namespace Avalonia.Controls private bool _canPaste; private string _newLine = Environment.NewLine; private static readonly string[] invalidCharacters = new String[1] { "\u007f" }; + private bool _canUndo; + private bool _canRedo; private int _wordSelectionStart = -1; private int _selectedTextChangesMadeSinceLastUndoSnapshot; @@ -590,6 +603,24 @@ namespace Avalonia.Controls } } + /// + /// Gets a value that indicates whether the undo stack has an action that can be undone + /// + public bool CanUndo + { + get => _canUndo; + private set => SetAndRaise(CanUndoProperty, ref _canUndo, value); + } + + /// + /// Gets a value that indicates whether the redo stack has an action that can be redone + /// + public bool CanRedo + { + get => _canRedo; + private set => SetAndRaise(CanRedoProperty, ref _canRedo, value); + } + public event EventHandler? CopyingToClipboard { add => AddHandler(CopyingToClipboardEvent, value); @@ -943,30 +974,13 @@ namespace Avalonia.Controls } else if (Match(keymap.Undo) && IsUndoEnabled) { - try - { - SnapshotUndoRedo(); - _isUndoingRedoing = true; - _undoRedoHelper.Undo(); - } - finally - { - _isUndoingRedoing = false; - } + Undo(); handled = true; } else if (Match(keymap.Redo) && IsUndoEnabled) { - try - { - _isUndoingRedoing = true; - _undoRedoHelper.Redo(); - } - finally - { - _isUndoingRedoing = false; - } + Redo(); handled = true; } @@ -1703,5 +1717,60 @@ namespace Avalonia.Controls } } } + + /// + /// Undoes the first action in the undo stack + /// + public void Undo() + { + if (IsUndoEnabled && CanUndo) + { + try + { + SnapshotUndoRedo(); + _isUndoingRedoing = true; + _undoRedoHelper.Undo(); + } + finally + { + _isUndoingRedoing = false; + } + } + } + + /// + /// Reapplies the first item on the redo stack + /// + public void Redo() + { + if (IsUndoEnabled && CanRedo) + { + try + { + _isUndoingRedoing = true; + _undoRedoHelper.Redo(); + } + finally + { + _isUndoingRedoing = false; + } + } + } + + /// + /// Called from the UndoRedoHelper when the undo stack is modified + /// + void UndoRedoHelper.IUndoRedoHost.OnUndoStackChanged() + { + CanUndo = _undoRedoHelper.CanUndo; + } + + /// + /// Called from the UndoRedoHelper when the redo stack is modified + /// + void UndoRedoHelper.IUndoRedoHost.OnRedoStackChanged() + { + CanRedo = _undoRedoHelper.CanRedo; + } } } diff --git a/src/Avalonia.Controls/Utils/UndoRedoHelper.cs b/src/Avalonia.Controls/Utils/UndoRedoHelper.cs index 0d5048c080..976dbb5d5f 100644 --- a/src/Avalonia.Controls/Utils/UndoRedoHelper.cs +++ b/src/Avalonia.Controls/Utils/UndoRedoHelper.cs @@ -14,6 +14,10 @@ namespace Avalonia.Controls.Utils public interface IUndoRedoHost { TState UndoRedoState { get; set; } + + void OnUndoStackChanged(); + + void OnRedoStackChanged(); } @@ -28,6 +32,10 @@ namespace Avalonia.Controls.Utils /// public int Limit { get; set; } = 10; + public bool CanUndo => _currentNode?.Previous != null; + + public bool CanRedo => _currentNode?.Next != null; + public UndoRedoHelper(IUndoRedoHost host) { _host = host; @@ -39,6 +47,8 @@ namespace Avalonia.Controls.Utils { _currentNode = _currentNode.Previous; _host.UndoRedoState = _currentNode.Value; + _host.OnUndoStackChanged(); + _host.OnRedoStackChanged(); } } @@ -72,6 +82,8 @@ namespace Avalonia.Controls.Utils { while (_currentNode?.Next != null) _states.Remove(_currentNode.Next); + + _host.OnRedoStackChanged(); } public void Redo() @@ -80,6 +92,8 @@ namespace Avalonia.Controls.Utils { _currentNode = _currentNode.Next; _host.UndoRedoState = _currentNode.Value; + _host.OnRedoStackChanged(); + _host.OnUndoStackChanged(); } } @@ -94,6 +108,9 @@ namespace Avalonia.Controls.Utils _currentNode = _states.Last; if (Limit != -1 && _states.Count > Limit) _states.RemoveFirst(); + + _host.OnUndoStackChanged(); + _host.OnRedoStackChanged(); } } @@ -101,6 +118,9 @@ namespace Avalonia.Controls.Utils { _states.Clear(); _currentNode = null; + + _host.OnUndoStackChanged(); + _host.OnRedoStackChanged(); } } } From 3f1a342e6f3052f0f319924209680dfbe56ae708 Mon Sep 17 00:00:00 2001 From: amwx <40413319+amwx@users.noreply.github.com> Date: Sun, 20 Nov 2022 23:53:41 -0500 Subject: [PATCH 08/55] Add some tests --- .../TextBoxTests.cs | 170 ++++++++++++++++++ 1 file changed, 170 insertions(+) diff --git a/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs b/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs index 23a330c96f..52a89cd13d 100644 --- a/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs +++ b/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs @@ -866,6 +866,176 @@ namespace Avalonia.Controls.UnitTests } } + [Fact] + public void CanUndo_CanRedo_Is_False_When_Initialized() + { + using (UnitTestApplication.Start(Services)) + { + var tb = new TextBox + { + Template = CreateTemplate(), + Text = "New Text" + }; + + tb.Measure(Size.Infinity); + + Assert.False(tb.CanUndo); + Assert.False(tb.CanRedo); + } + } + + [Fact] + public void CanUndo_CanRedo_and_Programmatic_Undo_Redo_Works() + { + using (UnitTestApplication.Start(Services)) + { + var tb = new TextBox + { + Template = CreateTemplate(), + }; + + tb.Measure(Size.Infinity); + + // See GH #6024 for a bit more insight on when Undo/Redo snapshots are taken: + // - Every 'Space', but only when space is handled in OnKeyDown - Spaces in TextInput event won't work + // - Every 7 chars in a long word + RaiseTextEvent(tb, "ABC"); + RaiseKeyEvent(tb, Key.Space, KeyModifiers.None); + RaiseTextEvent(tb, "DEF"); + RaiseKeyEvent(tb, Key.Space, KeyModifiers.None); + RaiseTextEvent(tb, "123"); + + // NOTE: the spaces won't actually add spaces b/c they're sent only as key events and not Text events + // so our final text is without spaces + Assert.Equal("ABCDEF123", tb.Text); + + Assert.True(tb.CanUndo); + + tb.Undo(); + + // Undo will take us back one step + Assert.Equal("ABCDEF", tb.Text); + + Assert.True(tb.CanRedo); + + tb.Redo(); + + // Redo should restore us + Assert.Equal("ABCDEF123", tb.Text); + } + } + + [Fact] + public void Setting_UndoLimit_Clears_Undo_Redo() + { + using (UnitTestApplication.Start(Services)) + { + var tb = new TextBox + { + Template = CreateTemplate(), + }; + + tb.Measure(Size.Infinity); + + // This is all the same as the above test (CanUndo_CanRedo_and_Programmatic_Undo_Redo_Works) + // We do this to get the undo/redo stacks in a state where both are active + RaiseTextEvent(tb, "ABC"); + RaiseKeyEvent(tb, Key.Space, KeyModifiers.None); + RaiseTextEvent(tb, "DEF"); + RaiseKeyEvent(tb, Key.Space, KeyModifiers.None); + RaiseTextEvent(tb, "123"); + + Assert.Equal("ABCDEF123", tb.Text); + Assert.True(tb.CanUndo); + tb.Undo(); + // Undo will take us back one step + Assert.Equal("ABCDEF", tb.Text); + Assert.True(tb.CanRedo); + tb.Redo(); + // Redo should restore us + Assert.Equal("ABCDEF123", tb.Text); + + // Change the undo limit, this should clear both stacks setting CanUndo and CanRedo to false + tb.UndoLimit = 1; + + Assert.False(tb.CanUndo); + Assert.False(tb.CanRedo); + } + } + + [Fact] + public void Setting_IsUndoEnabled_To_False_Clears_Undo_Redo() + { + using (UnitTestApplication.Start(Services)) + { + var tb = new TextBox + { + Template = CreateTemplate(), + }; + + tb.Measure(Size.Infinity); + + // This is all the same as the above test (CanUndo_CanRedo_and_Programmatic_Undo_Redo_Works) + // We do this to get the undo/redo stacks in a state where both are active + RaiseTextEvent(tb, "ABC"); + RaiseKeyEvent(tb, Key.Space, KeyModifiers.None); + RaiseTextEvent(tb, "DEF"); + RaiseKeyEvent(tb, Key.Space, KeyModifiers.None); + RaiseTextEvent(tb, "123"); + + Assert.Equal("ABCDEF123", tb.Text); + Assert.True(tb.CanUndo); + tb.Undo(); + // Undo will take us back one step + Assert.Equal("ABCDEF", tb.Text); + Assert.True(tb.CanRedo); + tb.Redo(); + // Redo should restore us + Assert.Equal("ABCDEF123", tb.Text); + + // Disable Undo/Redo, this should clear both stacks setting CanUndo and CanRedo to false + tb.IsUndoEnabled = false; + + Assert.False(tb.CanUndo); + Assert.False(tb.CanRedo); + } + } + + [Fact] + public void UndoLimit_Count_Is_Respected() + { + using (UnitTestApplication.Start(Services)) + { + var tb = new TextBox + { + Template = CreateTemplate(), + UndoLimit = 3 // Something small for this test + }; + + tb.Measure(Size.Infinity); + + // Push 3 undoable actions, we should only be able to recover 2 + RaiseTextEvent(tb, "ABC"); + RaiseKeyEvent(tb, Key.Space, KeyModifiers.None); + RaiseTextEvent(tb, "DEF"); + RaiseKeyEvent(tb, Key.Space, KeyModifiers.None); + RaiseTextEvent(tb, "123"); + + Assert.Equal("ABCDEF123", tb.Text); + + // Undo will take us back one step + tb.Undo(); + Assert.Equal("ABCDEF", tb.Text); + + // Undo again + tb.Undo(); + Assert.Equal("ABC", tb.Text); + + // We now should not be able to undo again + Assert.False(tb.CanUndo); + } + } + private static TestServices FocusServices => TestServices.MockThreadingInterface.With( focusManager: new FocusManager(), keyboardDevice: () => new KeyboardDevice(), From 4b089c0e823dfccfab096fe4057a55e5fe9a2b8f Mon Sep 17 00:00:00 2001 From: amwx <40413319+amwx@users.noreply.github.com> Date: Mon, 21 Nov 2022 00:16:44 -0500 Subject: [PATCH 09/55] Add some missing xml docs & a little cleanup --- src/Avalonia.Controls/TextBox.cs | 178 +++++++++++++++++- src/Avalonia.Controls/Utils/UndoRedoHelper.cs | 8 +- 2 files changed, 178 insertions(+), 8 deletions(-) diff --git a/src/Avalonia.Controls/TextBox.cs b/src/Avalonia.Controls/TextBox.cs index b06ec3492c..dbab912716 100644 --- a/src/Avalonia.Controls/TextBox.cs +++ b/src/Avalonia.Controls/TextBox.cs @@ -28,60 +28,108 @@ namespace Avalonia.Controls [PseudoClasses(":empty")] public class TextBox : TemplatedControl, UndoRedoHelper.IUndoRedoHost { + /// + /// Gets a platform-specific for the Cut action + /// public static KeyGesture? CutGesture { get; } = AvaloniaLocator.Current .GetService()?.Cut.FirstOrDefault(); + /// + /// Gets a platform-specific for the Copy action + /// public static KeyGesture? CopyGesture { get; } = AvaloniaLocator.Current .GetService()?.Copy.FirstOrDefault(); + /// + /// Gets a platform-specific for the Paste action + /// public static KeyGesture? PasteGesture { get; } = AvaloniaLocator.Current .GetService()?.Paste.FirstOrDefault(); + /// + /// Defines the property + /// public static readonly StyledProperty AcceptsReturnProperty = AvaloniaProperty.Register(nameof(AcceptsReturn)); + /// + /// Defines the property + /// public static readonly StyledProperty AcceptsTabProperty = AvaloniaProperty.Register(nameof(AcceptsTab)); + /// + /// Defines the property + /// public static readonly DirectProperty CaretIndexProperty = AvaloniaProperty.RegisterDirect( nameof(CaretIndex), o => o.CaretIndex, (o, v) => o.CaretIndex = v); + /// + /// Defines the property + /// public static readonly StyledProperty IsReadOnlyProperty = AvaloniaProperty.Register(nameof(IsReadOnly)); + /// + /// Defines the property + /// public static readonly StyledProperty PasswordCharProperty = AvaloniaProperty.Register(nameof(PasswordChar)); + /// + /// Defines the property + /// public static readonly StyledProperty SelectionBrushProperty = AvaloniaProperty.Register(nameof(SelectionBrush)); + /// + /// Defines the property + /// public static readonly StyledProperty SelectionForegroundBrushProperty = AvaloniaProperty.Register(nameof(SelectionForegroundBrush)); + /// + /// Defines the property + /// public static readonly StyledProperty CaretBrushProperty = AvaloniaProperty.Register(nameof(CaretBrush)); + /// + /// Defines the property + /// public static readonly DirectProperty SelectionStartProperty = AvaloniaProperty.RegisterDirect( nameof(SelectionStart), o => o.SelectionStart, (o, v) => o.SelectionStart = v); + /// + /// Defines the property + /// public static readonly DirectProperty SelectionEndProperty = AvaloniaProperty.RegisterDirect( nameof(SelectionEnd), o => o.SelectionEnd, (o, v) => o.SelectionEnd = v); + /// + /// Defines the property + /// public static readonly StyledProperty MaxLengthProperty = AvaloniaProperty.Register(nameof(MaxLength), defaultValue: 0); + /// + /// Defines the property + /// public static readonly StyledProperty MaxLinesProperty = AvaloniaProperty.Register(nameof(MaxLines), defaultValue: 0); + /// + /// Defines the property + /// public static readonly DirectProperty TextProperty = TextBlock.TextProperty.AddOwnerWithDataValidation( o => o.Text, @@ -89,6 +137,9 @@ namespace Avalonia.Controls defaultBindingMode: BindingMode.TwoWay, enableDataValidation: true); + /// + /// Defines the property + /// public static readonly StyledProperty TextAlignmentProperty = TextBlock.TextAlignmentProperty.AddOwner(); @@ -119,45 +170,78 @@ namespace Avalonia.Controls public static readonly StyledProperty LetterSpacingProperty = TextBlock.LetterSpacingProperty.AddOwner(); + /// + /// Defines the property + /// public static readonly StyledProperty WatermarkProperty = AvaloniaProperty.Register(nameof(Watermark)); + /// + /// Defines the property + /// public static readonly StyledProperty UseFloatingWatermarkProperty = AvaloniaProperty.Register(nameof(UseFloatingWatermark)); + /// + /// Defines the property + /// public static readonly DirectProperty NewLineProperty = AvaloniaProperty.RegisterDirect(nameof(NewLine), textbox => textbox.NewLine, (textbox, newline) => textbox.NewLine = newline); + /// + /// Defines the property + /// public static readonly StyledProperty InnerLeftContentProperty = AvaloniaProperty.Register(nameof(InnerLeftContent)); + /// + /// Defines the property + /// public static readonly StyledProperty InnerRightContentProperty = AvaloniaProperty.Register(nameof(InnerRightContent)); + /// + /// Defines the property + /// public static readonly StyledProperty RevealPasswordProperty = AvaloniaProperty.Register(nameof(RevealPassword)); + /// + /// Defines the property + /// public static readonly DirectProperty CanCutProperty = AvaloniaProperty.RegisterDirect( nameof(CanCut), o => o.CanCut); + /// + /// Defines the property + /// public static readonly DirectProperty CanCopyProperty = AvaloniaProperty.RegisterDirect( nameof(CanCopy), o => o.CanCopy); + /// + /// Defines the property + /// public static readonly DirectProperty CanPasteProperty = AvaloniaProperty.RegisterDirect( nameof(CanPaste), o => o.CanPaste); + /// + /// Defines the property + /// public static readonly StyledProperty IsUndoEnabledProperty = AvaloniaProperty.Register( nameof(IsUndoEnabled), defaultValue: true); + /// + /// Defines the property + /// public static readonly DirectProperty UndoLimitProperty = AvaloniaProperty.RegisterDirect( nameof(UndoLimit), @@ -212,9 +296,13 @@ namespace Avalonia.Controls RoutedEvent.Register( nameof(TextChanging), RoutingStrategies.Bubble); + /// + /// Stores the state information for available actions in the UndoRedoHelper + /// readonly struct UndoRedoState : IEquatable { public string? Text { get; } + public int CaretPosition { get; } public UndoRedoState(string? text, int caretPosition) @@ -287,18 +375,27 @@ namespace Avalonia.Controls UpdatePseudoclasses(); } + /// + /// Gets or sets a value that determines whether the TextBox allows and displays newline or return characters + /// public bool AcceptsReturn { get => GetValue(AcceptsReturnProperty); set => SetValue(AcceptsReturnProperty, value); } + /// + /// Gets or sets a value that determins whether the TextBox allows and displays tabs + /// public bool AcceptsTab { get => GetValue(AcceptsTabProperty); set => SetValue(AcceptsTabProperty, value); } + /// + /// Gets or sets the index of the text caret + /// public int CaretIndex { get => _caretIndex; @@ -315,36 +412,54 @@ namespace Avalonia.Controls } } + /// + /// Gets or sets a value whether this TextBox is read-only + /// public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } + /// + /// Gets or sets the that should be used for password masking + /// public char PasswordChar { get => GetValue(PasswordCharProperty); set => SetValue(PasswordCharProperty, value); } + /// + /// Gets or sets a brush that is used to highlight selected text + /// public IBrush? SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } + /// + /// Gets or sets a brush that is used for the foreground of selected text + /// public IBrush? SelectionForegroundBrush { get => GetValue(SelectionForegroundBrushProperty); set => SetValue(SelectionForegroundBrushProperty, value); } + /// + /// Gets or sets a brush that is used for the text caret + /// public IBrush? CaretBrush { get => GetValue(CaretBrushProperty); set => SetValue(CaretBrushProperty, value); } + /// + /// Gets or sets the starting position of the text selected in the TextBox + /// public int SelectionStart { get => _selectionStart; @@ -365,6 +480,13 @@ namespace Avalonia.Controls } } + /// + /// Gets or sets the end position of the text selected in the TextBox + /// + /// + /// When the SelectionEnd is equal to , there is no + /// selected text and it marks the caret position + /// public int SelectionEnd { get => _selectionEnd; @@ -384,19 +506,28 @@ namespace Avalonia.Controls } } } - + + /// + /// Gets or sets the maximum character length of the TextBox + /// public int MaxLength { get => GetValue(MaxLengthProperty); set => SetValue(MaxLengthProperty, value); } + /// + /// Gets or sets the maximum number of lines the TextBox can contain + /// public int MaxLines { get => GetValue(MaxLinesProperty); set => SetValue(MaxLinesProperty, value); } + /// + /// Gets or sets the spacing between characters + /// public double LetterSpacing { get => GetValue(LetterSpacingProperty); @@ -412,6 +543,9 @@ namespace Avalonia.Controls set => SetValue(LineHeightProperty, value); } + /// + /// Gets or sets the Text content of the TextBox + /// [Content] public string? Text { @@ -441,6 +575,9 @@ namespace Avalonia.Controls } } + /// + /// Gets or sets the text selected in the TextBox + /// public string SelectedText { get => GetSelection(); @@ -477,6 +614,9 @@ namespace Avalonia.Controls set => SetValue(VerticalContentAlignmentProperty, value); } + /// + /// Gets or sets the of the TextBox + /// public TextAlignment TextAlignment { get => GetValue(TextAlignmentProperty); @@ -503,24 +643,36 @@ namespace Avalonia.Controls set => SetValue(UseFloatingWatermarkProperty, value); } + /// + /// Gets or sets custom content that is positioned on the left side of the text layout box + /// public object InnerLeftContent { get => GetValue(InnerLeftContentProperty); set => SetValue(InnerLeftContentProperty, value); } + /// + /// Gets or sets custom content that is positioned on the right side of the text layout box + /// public object InnerRightContent { get => GetValue(InnerRightContentProperty); set => SetValue(InnerRightContentProperty, value); } + /// + /// Gets or sets whether text masked by should be revealed + /// public bool RevealPassword { get => GetValue(RevealPasswordProperty); set => SetValue(RevealPasswordProperty, value); } + /// + /// Gets or sets the of the TextBox + /// public TextWrapping TextWrapping { get => GetValue(TextWrappingProperty); @@ -580,6 +732,9 @@ namespace Avalonia.Controls set => SetValue(IsUndoEnabledProperty, value); } + /// + /// Gets or sets the maximum number of items that can reside in the Undo stack + /// public int UndoLimit { get => _undoRedoHelper.Limit; @@ -621,18 +776,27 @@ namespace Avalonia.Controls private set => SetAndRaise(CanRedoProperty, ref _canRedo, value); } + /// + /// Raised when content is being copied to the clipboard + /// public event EventHandler? CopyingToClipboard { add => AddHandler(CopyingToClipboardEvent, value); remove => RemoveHandler(CopyingToClipboardEvent, value); } + /// + /// Raised when content is being cut to the clipboard + /// public event EventHandler? CuttingToClipboard { add => AddHandler(CuttingToClipboardEvent, value); remove => RemoveHandler(CuttingToClipboardEvent, value); } + /// + /// Raised when content is being pasted from the clipboard + /// public event EventHandler? PastingFromClipboard { add => AddHandler(PastingFromClipboardEvent, value); @@ -862,6 +1026,9 @@ namespace Avalonia.Controls return text; } + /// + /// Cuts the current text onto the clipboard + /// public async void Cut() { var text = GetSelection(); @@ -882,6 +1049,9 @@ namespace Avalonia.Controls } } + /// + /// Copies the current text onto the clipboard + /// public async void Copy() { var text = GetSelection(); @@ -900,6 +1070,9 @@ namespace Avalonia.Controls } } + /// + /// Pastes the current clipboard text content into the TextBox + /// public async void Paste() { var eventArgs = new RoutedEventArgs(PastingFromClipboardEvent); @@ -1434,6 +1607,9 @@ namespace Avalonia.Controls } } + /// + /// Clears the text in the TextBox + /// public void Clear() { Text = string.Empty; diff --git a/src/Avalonia.Controls/Utils/UndoRedoHelper.cs b/src/Avalonia.Controls/Utils/UndoRedoHelper.cs index 976dbb5d5f..6ff72751a6 100644 --- a/src/Avalonia.Controls/Utils/UndoRedoHelper.cs +++ b/src/Avalonia.Controls/Utils/UndoRedoHelper.cs @@ -1,9 +1,4 @@ -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Avalonia.Utilities; namespace Avalonia.Controls.Utils { @@ -20,8 +15,6 @@ namespace Avalonia.Controls.Utils void OnRedoStackChanged(); } - - private readonly LinkedList _states = new LinkedList(); private LinkedListNode? _currentNode; @@ -65,6 +58,7 @@ namespace Avalonia.Controls.Utils } public bool HasState => _currentNode != null; + public void UpdateLastState(TState state) { if (_states.Last != null) From 273124603f184b8de42a22067b7dfc560f7d9792 Mon Sep 17 00:00:00 2001 From: Steven Kirk Date: Mon, 21 Nov 2022 15:03:33 +0100 Subject: [PATCH 10/55] Added benchmark for changing control theme. --- .../Styling/ControlTheme_Change.cs | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 tests/Avalonia.Benchmarks/Styling/ControlTheme_Change.cs diff --git a/tests/Avalonia.Benchmarks/Styling/ControlTheme_Change.cs b/tests/Avalonia.Benchmarks/Styling/ControlTheme_Change.cs new file mode 100644 index 0000000000..627edfdeb6 --- /dev/null +++ b/tests/Avalonia.Benchmarks/Styling/ControlTheme_Change.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using Avalonia.Controls; +using Avalonia.Media; +using Avalonia.Styling; +using Avalonia.UnitTests; +using BenchmarkDotNet.Attributes; + +namespace Avalonia.Benchmarks.Styling +{ + [MemoryDiagnoser] + public class ControlTheme_Change : IDisposable + { + private readonly IDisposable _app; + private readonly TestRoot _root; + private readonly TextBox _control; + private readonly ControlTheme _theme1; + private readonly ControlTheme _theme2; + + public ControlTheme_Change() + { + _app = UnitTestApplication.Start( + TestServices.StyledWindow.With( + renderInterface: new NullRenderingPlatform(), + threadingInterface: new NullThreadingPlatform())); + + // Simulate an application with a lot of styles by creating a tree of nested panels, + // each with a bunch of styles applied. + var (rootPanel, leafPanel) = CreateNestedPanels(10); + + // We're benchmarking how long it takes to switch control theme on a TextBox in this + // situation. + var baseTheme = (ControlTheme)Application.Current.FindResource(typeof(TextBox)) ?? + throw new Exception("Base TextBox theme not found."); + + _theme1 = new ControlTheme(typeof(TextBox)) + { + BasedOn = baseTheme, + Setters = { new Setter(TextBox.BackgroundProperty, Brushes.Red) }, + }; + + _theme2 = new ControlTheme(typeof(TextBox)) + { + BasedOn = baseTheme, + Setters = { new Setter(TextBox.BackgroundProperty, Brushes.Green) }, + }; + + _control = new TextBox { Theme = _theme1 }; + leafPanel.Children.Add(_control); + + _root = new TestRoot(true, rootPanel) + { + Renderer = new NullRenderer(), + }; + + _root.LayoutManager.ExecuteInitialLayoutPass(); + } + + [Benchmark] + [MethodImpl(MethodImplOptions.NoInlining)] + public void Change_ControlTheme() + { + if (_control.Background != Brushes.Red) + throw new Exception("Invalid benchmark state"); + + _control.Theme = _theme2; + _root.LayoutManager.ExecuteLayoutPass(); + + if (_control.Background != Brushes.Green) + throw new Exception("Invalid benchmark state"); + + _control.Theme = _theme1; + _root.LayoutManager.ExecuteLayoutPass(); + + if (_control.Background != Brushes.Red) + throw new Exception("Invalid benchmark state"); + } + + public void Dispose() + { + _app.Dispose(); + } + + private static (Panel, Panel) CreateNestedPanels(int count) + { + var root = new Panel(); + var last = root; + + for (var i = 0; i < count; ++i) + { + var panel = new Panel(); + panel.Styles.AddRange(CreateStyles()); + last.Children.Add(panel); + last = panel; + } + + return (root, last); + } + + private static IEnumerable CreateStyles() + { + var types = new[] + { + typeof(Border), + typeof(Button), + typeof(ButtonSpinner), + typeof(Carousel), + typeof(CheckBox), + typeof(ComboBox), + typeof(ContentControl), + typeof(Expander), + typeof(ItemsControl), + typeof(Label), + typeof(ListBox), + typeof(ProgressBar), + typeof(RadioButton), + typeof(RepeatButton), + typeof(ScrollViewer), + typeof(Slider), + typeof(Spinner), + typeof(SplitView), + typeof(TextBox), + typeof(ToggleSwitch), + typeof(TreeView), + typeof(Viewbox), + typeof(Window), + }; + + foreach (var type in types) + { + yield return new Style(x => x.OfType(type)) + { + Setters = { new Setter(Control.TagProperty, type.Name) } + }; + + yield return new Style(x => x.OfType(type).Class("foo")) + { + Setters = { new Setter(Control.TagProperty, type.Name + " foo") } + }; + + yield return new Style(x => x.OfType(type).Class("bar")) + { + Setters = { new Setter(Control.TagProperty, type.Name + " bar") } + }; + } + } + } +} From 326dac232899a17d7f6ae8852c81357282af0cfa Mon Sep 17 00:00:00 2001 From: Steven Kirk Date: Fri, 18 Nov 2022 12:02:32 +0100 Subject: [PATCH 11/55] Refactored how we switch control themes. Instead of simply wiping all control themes and styles that are applied to a control, we can now just remove the `ValueFrame`s which relate to the control theme that was changed. To do this, added `ValueFrame.FramePriority` which encodes both the `BindingPriority` and source of the frame (style, control theme, templated parent control theme). --- src/Avalonia.Base/Layout/Layoutable.cs | 7 + .../PropertyStore/FramePriority.cs | 36 +++ .../PropertyStore/ImmediateValueFrame.cs | 2 +- src/Avalonia.Base/PropertyStore/ValueFrame.cs | 20 +- src/Avalonia.Base/PropertyStore/ValueStore.cs | 33 ++- src/Avalonia.Base/StyledElement.cs | 95 ++++---- src/Avalonia.Base/Styling/ControlTheme.cs | 7 +- src/Avalonia.Base/Styling/Style.cs | 5 +- src/Avalonia.Base/Styling/StyleBase.cs | 6 +- src/Avalonia.Base/Styling/StyleInstance.cs | 13 +- src/Avalonia.Base/Styling/Styles.cs | 3 +- .../Primitives/TemplatedControl.cs | 59 ++--- .../Animation/AnimatableTests.cs | 3 +- .../PropertyStore/ValueStoreTests_Frames.cs | 2 +- .../Styling/SetterTests.cs | 3 +- .../Styling/StyleTests.cs | 17 +- .../Styling/StyledElementTests_Theming.cs | 218 +++++++++++++++++- .../Styling/Style_Activation.cs | 3 +- .../Styling/Style_Apply.cs | 3 +- .../Styling/Style_ClassSelector.cs | 7 +- .../Styling/Style_NonActive.cs | 3 +- .../StyleTests.cs | 3 +- 22 files changed, 410 insertions(+), 138 deletions(-) create mode 100644 src/Avalonia.Base/PropertyStore/FramePriority.cs diff --git a/src/Avalonia.Base/Layout/Layoutable.cs b/src/Avalonia.Base/Layout/Layoutable.cs index 527b63292d..d09d1dc8d2 100644 --- a/src/Avalonia.Base/Layout/Layoutable.cs +++ b/src/Avalonia.Base/Layout/Layoutable.cs @@ -1,5 +1,6 @@ using System; using Avalonia.Logging; +using Avalonia.Styling; using Avalonia.VisualTree; #nullable enable @@ -795,6 +796,12 @@ namespace Avalonia.Layout base.OnVisualParentChanged(oldParent, newParent); } + private protected override void OnControlThemeChanged() + { + base.OnControlThemeChanged(); + InvalidateMeasure(); + } + /// /// Called when the layout manager raises a LayoutUpdated event. /// diff --git a/src/Avalonia.Base/PropertyStore/FramePriority.cs b/src/Avalonia.Base/PropertyStore/FramePriority.cs new file mode 100644 index 0000000000..950a8375f2 --- /dev/null +++ b/src/Avalonia.Base/PropertyStore/FramePriority.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; +using Avalonia.Data; + +namespace Avalonia.PropertyStore +{ + internal enum FramePriority : sbyte + { + Animation, + AnimationTemplatedParentTheme, + AnimationTheme, + StyleTrigger, + StyleTriggerTemplatedParentTheme, + StyleTriggerTheme, + Template, + TemplateTemplatedParentTheme, + TemplateTheme, + Style, + StyleTemplatedParentTheme, + StyleTheme, + } + + internal static class FramePriorityExtensions + { + public static FramePriority ToFramePriority(this BindingPriority priority, FrameType type = FrameType.Style) + { + Debug.Assert(priority != BindingPriority.LocalValue); + var p = (int)(priority > 0 ? priority : priority + 1); + return (FramePriority)(p * 3 + (int)type); + } + + public static bool IsType(this FramePriority priority, FrameType type) + { + return (FrameType)((int)priority % 3) == type; + } + } +} diff --git a/src/Avalonia.Base/PropertyStore/ImmediateValueFrame.cs b/src/Avalonia.Base/PropertyStore/ImmediateValueFrame.cs index 1d886e7501..756ab7aadf 100644 --- a/src/Avalonia.Base/PropertyStore/ImmediateValueFrame.cs +++ b/src/Avalonia.Base/PropertyStore/ImmediateValueFrame.cs @@ -10,8 +10,8 @@ namespace Avalonia.PropertyStore internal class ImmediateValueFrame : ValueFrame { public ImmediateValueFrame(BindingPriority priority) + : base(priority, FrameType.Style) { - Priority = priority; } public TypedBindingEntry AddBinding( diff --git a/src/Avalonia.Base/PropertyStore/ValueFrame.cs b/src/Avalonia.Base/PropertyStore/ValueFrame.cs index 5ada4b3c84..7a9d1bb13a 100644 --- a/src/Avalonia.Base/PropertyStore/ValueFrame.cs +++ b/src/Avalonia.Base/PropertyStore/ValueFrame.cs @@ -1,13 +1,18 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Avalonia.Data; using Avalonia.Utilities; -using static Avalonia.Rendering.Composition.Animations.PropertySetSnapshot; namespace Avalonia.PropertyStore { + internal enum FrameType + { + Style, + TemplatedParentTheme, + Theme, + } + internal abstract class ValueFrame { private List? _entries; @@ -15,11 +20,18 @@ namespace Avalonia.PropertyStore private ValueStore? _owner; private bool _isShared; + protected ValueFrame(BindingPriority priority, FrameType type) + { + Priority = priority; + FramePriority = priority.ToFramePriority(type); + } + public int EntryCount => _index.Count; public bool IsActive => GetIsActive(out _); public ValueStore? Owner => !_isShared ? _owner : throw new AvaloniaInternalException("Cannot get owner for shared ValueFrame"); - public BindingPriority Priority { get; protected set; } + public BindingPriority Priority { get; } + public FramePriority FramePriority { get; } public bool Contains(AvaloniaProperty property) => _index.ContainsKey(property); diff --git a/src/Avalonia.Base/PropertyStore/ValueStore.cs b/src/Avalonia.Base/PropertyStore/ValueStore.cs index d858e30212..e14d018564 100644 --- a/src/Avalonia.Base/PropertyStore/ValueStore.cs +++ b/src/Avalonia.Base/PropertyStore/ValueStore.cs @@ -4,8 +4,8 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Avalonia.Data; using Avalonia.Diagnostics; -using Avalonia.Logging; using Avalonia.Utilities; +using static Avalonia.Rendering.Composition.Animations.PropertySetSnapshot; namespace Avalonia.PropertyStore { @@ -580,6 +580,29 @@ namespace Avalonia.PropertyStore return false; } + public void RemoveFrames(FrameType type) + { + var removed = false; + + for (var i = _frames.Count - 1; i >= 0; --i) + { + var frame = _frames[i]; + + if (frame.FramePriority.IsType(type)) + { + _frames.RemoveAt(i); + frame.Dispose(); + removed = true; + } + } + + if (removed) + { + ++_frameGeneration; + ReevaluateEffectiveValues(); + } + } + public AvaloniaPropertyValue GetDiagnostic(AvaloniaProperty property) { object? value; @@ -612,7 +635,7 @@ namespace Avalonia.PropertyStore { Debug.Assert(!_frames.Contains(frame)); - var index = BinarySearchFrame(frame.Priority); + var index = BinarySearchFrame(frame.FramePriority); _frames.Insert(index, frame); ++_frameGeneration; frame.SetOwner(this); @@ -626,7 +649,7 @@ namespace Avalonia.PropertyStore { Debug.Assert(priority != BindingPriority.LocalValue); - var index = BinarySearchFrame(priority); + var index = BinarySearchFrame(priority.ToFramePriority()); if (index > 0 && _frames[index - 1] is ImmediateValueFrame f && f.Priority == priority && @@ -914,7 +937,7 @@ namespace Avalonia.PropertyStore } } - private int BinarySearchFrame(BindingPriority priority) + private int BinarySearchFrame(FramePriority priority) { var lo = 0; var hi = _frames.Count - 1; @@ -923,7 +946,7 @@ namespace Avalonia.PropertyStore while (lo <= hi) { var i = lo + ((hi - lo) >> 1); - var order = priority - _frames[i].Priority; + var order = priority - _frames[i].FramePriority; if (order <= 0) { diff --git a/src/Avalonia.Base/StyledElement.cs b/src/Avalonia.Base/StyledElement.cs index c72f398fd9..33bca9b0ab 100644 --- a/src/Avalonia.Base/StyledElement.cs +++ b/src/Avalonia.Base/StyledElement.cs @@ -3,6 +3,7 @@ using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; +using System.Diagnostics; using System.Linq; using Avalonia.Animation; using Avalonia.Collections; @@ -11,6 +12,7 @@ using Avalonia.Data; using Avalonia.Diagnostics; using Avalonia.Logging; using Avalonia.LogicalTree; +using Avalonia.PropertyStore; using Avalonia.Styling; namespace Avalonia @@ -69,10 +71,10 @@ namespace Avalonia private IAvaloniaList? _logicalChildren; private IResourceDictionary? _resources; private Styles? _styles; - private bool _styled; + private bool _stylesApplied; + private bool _themeApplied; private ITemplatedControl? _templatedParent; private bool _dataContextUpdating; - private bool _hasPromotedTheme; private ControlTheme? _implicitTheme; /// @@ -141,7 +143,7 @@ namespace Avalonia set { - if (_styled) + if (_stylesApplied) { throw new InvalidOperationException("Cannot set Name : styled element already styled."); } @@ -353,31 +355,31 @@ namespace Avalonia /// public bool ApplyStyling() { - if (_initCount == 0 && !_styled) + if (_initCount == 0 && (!_stylesApplied || !_themeApplied)) { - var hasPromotedTheme = _hasPromotedTheme; - GetValueStore().BeginStyling(); try { - ApplyControlTheme(); - ApplyStyles(this); + if (!_themeApplied) + { + ApplyControlTheme(); + _themeApplied = true; + } + + if (!_stylesApplied) + { + ApplyStyles(this); + _stylesApplied = true; + } } finally { - _styled = true; GetValueStore().EndStyling(); } - - if (hasPromotedTheme) - { - _hasPromotedTheme = false; - ClearValue(ThemeProperty); - } } - return _styled; + return _stylesApplied; } /// @@ -615,31 +617,25 @@ namespace Avalonia if (change.Property == ThemeProperty) { - var (oldValue, newValue) = change.GetOldAndNewValue(); - - // Changing the theme detaches all styles, meaning that if the theme property was - // set via a style, it will get cleared! To work around this, if the value was - // applied at less than local value priority then promote the value to local value - // priority until styling is re-applied. - if (change.Priority > BindingPriority.LocalValue) - { - Theme = newValue; - _hasPromotedTheme = true; - } - else if (_hasPromotedTheme && change.Priority == BindingPriority.LocalValue) - { - _hasPromotedTheme = false; - } - - InvalidateStyles(); - - if (oldValue is not null) - DetachControlThemeFromTemplateChildren(oldValue); + OnControlThemeChanged(); + _themeApplied = false; } } - internal virtual void DetachControlThemeFromTemplateChildren(ControlTheme theme) + private protected virtual void OnControlThemeChanged() { + var values = GetValueStore(); + values.BeginStyling(); + try { values.RemoveFrames(FrameType.Theme); } + finally { values.EndStyling(); } + } + + internal virtual void OnTemplatedParentControlThemeChanged() + { + var values = GetValueStore(); + values.BeginStyling(); + try { values.RemoveFrames(FrameType.TemplatedParentTheme); } + finally { values.EndStyling(); } } internal ControlTheme? GetEffectiveTheme() @@ -736,26 +732,28 @@ namespace Avalonia var theme = GetEffectiveTheme(); if (theme is not null) - ApplyControlTheme(theme); + ApplyControlTheme(theme, FrameType.Theme); if (TemplatedParent is StyledElement styleableParent && styleableParent.GetEffectiveTheme() is { } parentTheme) { - ApplyControlTheme(parentTheme); + ApplyControlTheme(parentTheme, FrameType.TemplatedParentTheme); } } - private void ApplyControlTheme(ControlTheme theme) + private void ApplyControlTheme(ControlTheme theme, FrameType type) { + Debug.Assert(type is FrameType.Theme or FrameType.TemplatedParentTheme); + if (theme.BasedOn is ControlTheme basedOn) - ApplyControlTheme(basedOn); + ApplyControlTheme(basedOn, type); - theme.TryAttach(this, null); + theme.TryAttach(this, type); if (theme.HasChildren) { foreach (var child in theme.Children) - ApplyStyle(child, null); + ApplyStyle(child, null, type); } } @@ -768,17 +766,17 @@ namespace Avalonia if (host.IsStylesInitialized) { foreach (var style in host.Styles) - ApplyStyle(style, host); + ApplyStyle(style, host, FrameType.Style); } } - private void ApplyStyle(IStyle style, IStyleHost? host) + private void ApplyStyle(IStyle style, IStyleHost? host, FrameType type) { if (style is Style s) - s.TryAttach(this, host); + s.TryAttach(this, host, type); foreach (var child in style.Children) - ApplyStyle(child, host); + ApplyStyle(child, host, type); } private void OnAttachedToLogicalTreeCore(LogicalTreeAttachmentEventArgs e) @@ -895,6 +893,7 @@ namespace Avalonia for (var i = valueStore.Frames.Count - 1; i >= 0; --i) { if (valueStore.Frames[i] is StyleInstance si && + si.Source is not ControlTheme && (styles is null || styles.Contains(si.Source))) { valueStore.RemoveFrame(si); @@ -902,7 +901,7 @@ namespace Avalonia } valueStore.EndStyling(); - _styled = false; + _stylesApplied = false; } private void InvalidateStylesOnThisAndDescendents() diff --git a/src/Avalonia.Base/Styling/ControlTheme.cs b/src/Avalonia.Base/Styling/ControlTheme.cs index 2971703c95..5fc900d2cb 100644 --- a/src/Avalonia.Base/Styling/ControlTheme.cs +++ b/src/Avalonia.Base/Styling/ControlTheme.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics; using Avalonia.PropertyStore; namespace Avalonia.Styling @@ -36,8 +37,10 @@ namespace Avalonia.Styling throw new InvalidOperationException("ControlThemes cannot be added as a nested style."); } - internal override SelectorMatchResult TryAttach(IStyleable target, object? host) + internal SelectorMatchResult TryAttach(IStyleable target, FrameType type) { + Debug.Assert(type is FrameType.Theme or FrameType.TemplatedParentTheme); + _ = target ?? throw new ArgumentNullException(nameof(target)); if (TargetType is null) @@ -45,7 +48,7 @@ namespace Avalonia.Styling if (HasSettersOrAnimations && TargetType.IsAssignableFrom(target.StyleKey)) { - Attach(target, null); + Attach(target, null, type); return SelectorMatchResult.AlwaysThisType; } diff --git a/src/Avalonia.Base/Styling/Style.cs b/src/Avalonia.Base/Styling/Style.cs index aad91824d3..15d8a9fe2e 100644 --- a/src/Avalonia.Base/Styling/Style.cs +++ b/src/Avalonia.Base/Styling/Style.cs @@ -1,4 +1,5 @@ using System; +using Avalonia.PropertyStore; namespace Avalonia.Styling { @@ -58,7 +59,7 @@ namespace Avalonia.Styling base.SetParent(parent); } - internal override SelectorMatchResult TryAttach(IStyleable target, object? host) + internal SelectorMatchResult TryAttach(IStyleable target, object? host, FrameType type) { _ = target ?? throw new ArgumentNullException(nameof(target)); @@ -73,7 +74,7 @@ namespace Avalonia.Styling if (match.IsMatch) { - Attach(target, match.Activator); + Attach(target, match.Activator, type); } result = match.Result; diff --git a/src/Avalonia.Base/Styling/StyleBase.cs b/src/Avalonia.Base/Styling/StyleBase.cs index dba80df2e5..83fcf04d2f 100644 --- a/src/Avalonia.Base/Styling/StyleBase.cs +++ b/src/Avalonia.Base/Styling/StyleBase.cs @@ -92,9 +92,7 @@ namespace Avalonia.Styling return false; } - internal abstract SelectorMatchResult TryAttach(IStyleable target, object? host); - - internal ValueFrame Attach(IStyleable target, IStyleActivator? activator) + internal ValueFrame Attach(IStyleable target, IStyleActivator? activator, FrameType type) { if (target is not AvaloniaObject ao) throw new InvalidOperationException("Styles can only be applied to AvaloniaObjects."); @@ -109,7 +107,7 @@ namespace Avalonia.Styling { var canShareInstance = activator is null; - instance = new StyleInstance(this, activator); + instance = new StyleInstance(this, activator, type); if (_setters is not null) { diff --git a/src/Avalonia.Base/Styling/StyleInstance.cs b/src/Avalonia.Base/Styling/StyleInstance.cs index 2d7c695b32..4985aa16c7 100644 --- a/src/Avalonia.Base/Styling/StyleInstance.cs +++ b/src/Avalonia.Base/Styling/StyleInstance.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Reactive.Subjects; using Avalonia.Animation; using Avalonia.Data; @@ -27,10 +26,13 @@ namespace Avalonia.Styling private List? _animations; private Subject? _animationTrigger; - public StyleInstance(IStyle style, IStyleActivator? activator) + public StyleInstance( + IStyle style, + IStyleActivator? activator, + FrameType type) + : base(GetPriority(activator), type) { _activator = activator; - Priority = activator is object ? BindingPriority.StyleTrigger : BindingPriority.Style; Source = style; } @@ -99,5 +101,10 @@ namespace Avalonia.Styling hasChanged = _isActive != previous; return _isActive; } + + private static BindingPriority GetPriority(IStyleActivator? activator) + { + return activator is not null ? BindingPriority.StyleTrigger : BindingPriority.Style; + } } } diff --git a/src/Avalonia.Base/Styling/Styles.cs b/src/Avalonia.Base/Styling/Styles.cs index 76271b9748..f22bbc0eae 100644 --- a/src/Avalonia.Base/Styling/Styles.cs +++ b/src/Avalonia.Base/Styling/Styles.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Collections.Specialized; using Avalonia.Collections; using Avalonia.Controls; +using Avalonia.PropertyStore; namespace Avalonia.Styling { @@ -233,7 +234,7 @@ namespace Avalonia.Styling { if (s is not Style style) continue; - var r = style.TryAttach(target, host); + var r = style.TryAttach(target, host, FrameType.Style); if (r > result) result = r; } diff --git a/src/Avalonia.Controls/Primitives/TemplatedControl.cs b/src/Avalonia.Controls/Primitives/TemplatedControl.cs index 80151fbfb3..17d90e6dd0 100644 --- a/src/Avalonia.Controls/Primitives/TemplatedControl.cs +++ b/src/Avalonia.Controls/Primitives/TemplatedControl.cs @@ -5,6 +5,7 @@ using Avalonia.Interactivity; using Avalonia.Logging; using Avalonia.LogicalTree; using Avalonia.Media; +using Avalonia.PropertyStore; using Avalonia.Styling; using Avalonia.VisualTree; @@ -395,56 +396,36 @@ namespace Avalonia.Controls.Primitives } } - internal override void DetachControlThemeFromTemplateChildren(ControlTheme theme) + private protected override void OnControlThemeChanged() { - static ControlTheme? GetControlTheme(StyleBase style) - { - var s = style; + base.OnControlThemeChanged(); - while (s is not null) + var count = VisualChildren.Count; + for (var i = 0; i < count; ++i) + { + if (VisualChildren[i] is StyledElement child && + child.TemplatedParent == this) { - if (s is ControlTheme c) - return c; - s = s.Parent as StyleBase; + child.OnTemplatedParentControlThemeChanged(); } - - return null; } + } - static void Detach(Visual control, ITemplatedControl templatedParent, ControlTheme theme) - { - var valueStore = control.GetValueStore(); - var count = valueStore.Frames.Count; - - if (control != templatedParent) - { - valueStore.BeginStyling(); - - for (var i = count - 1; i >= 0; --i) - { - if (valueStore.Frames[i] is StyleInstance si && - si.Source is StyleBase style && - GetControlTheme(style) == theme) - { - valueStore.RemoveFrame(si); - } - } - - valueStore.EndStyling(); - } + internal override void OnTemplatedParentControlThemeChanged() + { + base.OnTemplatedParentControlThemeChanged(); - var children = ((IVisual)control).VisualChildren; - count = children.Count; + var count = VisualChildren.Count; + var templatedParent = TemplatedParent; - for (var i = 0; i < count; i++) + for (var i = 0; i < count; ++i) + { + if (VisualChildren[i] is TemplatedControl child && + child.TemplatedParent == templatedParent) { - if (children[i] is Visual v && - v.TemplatedParent == templatedParent) - Detach(v, templatedParent, theme); + child.OnTemplatedParentControlThemeChanged(); } } - - Detach(this, this, theme); } } } diff --git a/tests/Avalonia.Base.UnitTests/Animation/AnimatableTests.cs b/tests/Avalonia.Base.UnitTests/Animation/AnimatableTests.cs index 668b8a875c..dec813b3b0 100644 --- a/tests/Avalonia.Base.UnitTests/Animation/AnimatableTests.cs +++ b/tests/Avalonia.Base.UnitTests/Animation/AnimatableTests.cs @@ -5,6 +5,7 @@ using Avalonia.Controls.Shapes; using Avalonia.Data; using Avalonia.Layout; using Avalonia.Media; +using Avalonia.PropertyStore; using Avalonia.Styling; using Avalonia.UnitTests; using Moq; @@ -435,7 +436,7 @@ namespace Avalonia.Base.UnitTests.Animation } }; - style.TryAttach(control, control); + style.TryAttach(control, control, FrameType.Style); // Which means that the transition state hasn't been initialized with the new // Transitions when the Opacity change notification gets raised here. diff --git a/tests/Avalonia.Base.UnitTests/PropertyStore/ValueStoreTests_Frames.cs b/tests/Avalonia.Base.UnitTests/PropertyStore/ValueStoreTests_Frames.cs index bb726a1d63..3a307447ac 100644 --- a/tests/Avalonia.Base.UnitTests/PropertyStore/ValueStoreTests_Frames.cs +++ b/tests/Avalonia.Base.UnitTests/PropertyStore/ValueStoreTests_Frames.cs @@ -117,7 +117,7 @@ namespace Avalonia.Base.UnitTests.PropertyStore private static StyleInstance InstanceStyle(Style style, StyledElement target) { - var result = new StyleInstance(style, null); + var result = new StyleInstance(style, null, FrameType.Style); foreach (var setter in style.Setters) result.Add(setter.Instance(result, target)); diff --git a/tests/Avalonia.Base.UnitTests/Styling/SetterTests.cs b/tests/Avalonia.Base.UnitTests/Styling/SetterTests.cs index dc31d3d3ec..18f572dedc 100644 --- a/tests/Avalonia.Base.UnitTests/Styling/SetterTests.cs +++ b/tests/Avalonia.Base.UnitTests/Styling/SetterTests.cs @@ -6,6 +6,7 @@ using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.Data.Converters; using Avalonia.Media; +using Avalonia.PropertyStore; using Avalonia.Styling; using Avalonia.UnitTests; using Moq; @@ -503,7 +504,7 @@ namespace Avalonia.Base.UnitTests.Styling private void Apply(Style style, Control control) { - style.TryAttach(control, null); + style.TryAttach(control, null, FrameType.Style); } private void Apply(Setter setter, Control control) diff --git a/tests/Avalonia.Base.UnitTests/Styling/StyleTests.cs b/tests/Avalonia.Base.UnitTests/Styling/StyleTests.cs index e7ecba61a7..a318a8d76a 100644 --- a/tests/Avalonia.Base.UnitTests/Styling/StyleTests.cs +++ b/tests/Avalonia.Base.UnitTests/Styling/StyleTests.cs @@ -5,6 +5,7 @@ using Avalonia.Base.UnitTests.Animation; using Avalonia.Controls; using Avalonia.Controls.Templates; using Avalonia.Data; +using Avalonia.PropertyStore; using Avalonia.Styling; using Avalonia.UnitTests; using Moq; @@ -27,7 +28,7 @@ namespace Avalonia.Base.UnitTests.Styling var target = new Class1(); - style.TryAttach(target, null); + style.TryAttach(target, null, FrameType.Style); Assert.Equal("Foo", target.Foo); } @@ -45,7 +46,7 @@ namespace Avalonia.Base.UnitTests.Styling var target = new Class1(); - style.TryAttach(target, null); + style.TryAttach(target, null, FrameType.Style); Assert.Equal("foodefault", target.Foo); target.Classes.Add("foo"); Assert.Equal("Foo", target.Foo); @@ -66,7 +67,7 @@ namespace Avalonia.Base.UnitTests.Styling var target = new Class1(); - style.TryAttach(target, target); + style.TryAttach(target, target, FrameType.Style); Assert.Equal("Foo", target.Foo); } @@ -92,7 +93,7 @@ namespace Avalonia.Base.UnitTests.Styling var target = new Class1(); var other = new Class1(); - style.TryAttach(target, other); + style.TryAttach(target, other, FrameType.Style); Assert.Equal("foodefault", target.Foo); } @@ -113,7 +114,7 @@ namespace Avalonia.Base.UnitTests.Styling Foo = "Original", }; - style.TryAttach(target, null); + style.TryAttach(target, null, FrameType.Style); Assert.Equal("Original", target.Foo); } @@ -577,7 +578,7 @@ namespace Avalonia.Base.UnitTests.Styling Child = border = new Border(), }; - style.TryAttach(border, null); + style.TryAttach(border, null, FrameType.Style); Assert.Equal(new Thickness(4), border.BorderThickness); root.Child = null; @@ -761,7 +762,7 @@ namespace Avalonia.Base.UnitTests.Styling var target = new Class1(); - style.TryAttach(target, null); + style.TryAttach(target, null, FrameType.Style); Assert.Equal(1, target.Classes.ListenerCount); @@ -874,7 +875,7 @@ namespace Avalonia.Base.UnitTests.Styling var clock = new TestClock(); var target = new Class1 { Clock = clock }; - style.TryAttach(target, null); + style.TryAttach(target, null, FrameType.Style); Assert.Equal(0.0, target.Double); diff --git a/tests/Avalonia.Base.UnitTests/Styling/StyledElementTests_Theming.cs b/tests/Avalonia.Base.UnitTests/Styling/StyledElementTests_Theming.cs index a1dac931ce..b5524affb7 100644 --- a/tests/Avalonia.Base.UnitTests/Styling/StyledElementTests_Theming.cs +++ b/tests/Avalonia.Base.UnitTests/Styling/StyledElementTests_Theming.cs @@ -23,7 +23,7 @@ public class StyledElementTests_Theming Assert.Null(target.Template); - var root = CreateRoot(target); + CreateRoot(target); Assert.NotNull(target.Template); var border = Assert.IsType(target.VisualChild); @@ -43,7 +43,7 @@ public class StyledElementTests_Theming Assert.Null(target.Template); - var root = CreateRoot(target); + CreateRoot(target); Assert.NotNull(target.Template); var border = Assert.IsType(target.VisualChild); @@ -57,7 +57,7 @@ public class StyledElementTests_Theming public void Theme_Is_Detached_When_Theme_Property_Cleared() { var target = CreateTarget(); - var root = CreateRoot(target); + CreateRoot(target); Assert.NotNull(target.Template); @@ -66,7 +66,47 @@ public class StyledElementTests_Theming } [Fact] - public void Theme_Is_Detached_From_Template_Controls_When_Theme_Property_Cleared() + public void Setting_Explicit_Theme_Detaches_Default_Theme() + { + var target = new ThemedControl(); + var root = new TestRoot + { + Resources = { { typeof(ThemedControl), CreateTheme() } }, + Child = target, + }; + + root.LayoutManager.ExecuteInitialLayoutPass(); + + Assert.Equal("theme", target.Tag); + + target.Theme = new ControlTheme(typeof(ThemedControl)) + { + Setters = + { + new Setter(ThemedControl.BackgroundProperty, Brushes.Yellow), + } + }; + + root.LayoutManager.ExecuteLayoutPass(); + + Assert.Null(target.Tag); + Assert.Equal(Brushes.Yellow, target.Background); + } + + [Fact] + public void Unrelated_Styles_Are_Not_Detached_When_Theme_Property_Cleared() + { + var target = CreateTarget(); + CreateRoot(target, createAdditionalStyles: true); + + Assert.Equal("style", target.Tag); + + target.Theme = null; + Assert.Equal("style", target.Tag); + } + + [Fact] + public void TemplatedParent_Theme_Is_Detached_From_Template_Controls_When_Theme_Property_Cleared() { var theme = new ControlTheme { @@ -93,10 +133,115 @@ public class StyledElementTests_Theming target.Theme = null; - Assert.IsType(target.VisualChild); + Assert.Same(canvas, target.VisualChild); Assert.Null(canvas.Background); } + [Fact] + public void Primary_Theme_Is_Not_Detached_From_Template_Controls_When_Theme_Property_Cleared() + { + var templatedParentTheme = new ControlTheme + { + TargetType = typeof(ThemedControl), + Children = + { + new Style(x => x.Nesting().Template().OfType - internal class ImmediateValueFrame : ValueFrame + internal sealed class ImmediateValueFrame : ValueFrame { public ImmediateValueFrame(BindingPriority priority) : base(priority, FrameType.Style) diff --git a/src/Avalonia.Base/PropertyStore/ValueStore.cs b/src/Avalonia.Base/PropertyStore/ValueStore.cs index e14d018564..92e5288255 100644 --- a/src/Avalonia.Base/PropertyStore/ValueStore.cs +++ b/src/Avalonia.Base/PropertyStore/ValueStore.cs @@ -2,8 +2,10 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Linq; using Avalonia.Data; using Avalonia.Diagnostics; +using Avalonia.Styling; using Avalonia.Utilities; using static Avalonia.Rendering.Composition.Animations.PropertySetSnapshot; @@ -588,7 +590,31 @@ namespace Avalonia.PropertyStore { var frame = _frames[i]; - if (frame.FramePriority.IsType(type)) + if (frame is not ImmediateValueFrame && frame.FramePriority.IsType(type)) + { + _frames.RemoveAt(i); + frame.Dispose(); + removed = true; + } + } + + if (removed) + { + ++_frameGeneration; + ReevaluateEffectiveValues(); + } + } + + + public void RemoveFrames(IReadOnlyList styles) + { + var removed = false; + + for (var i = _frames.Count - 1; i >= 0; --i) + { + var frame = _frames[i]; + + if (frame is StyleInstance style && styles.Contains(style.Source)) { _frames.RemoveAt(i); frame.Dispose(); diff --git a/src/Avalonia.Base/StyledElement.cs b/src/Avalonia.Base/StyledElement.cs index 33bca9b0ab..187edd8335 100644 --- a/src/Avalonia.Base/StyledElement.cs +++ b/src/Avalonia.Base/StyledElement.cs @@ -382,11 +382,6 @@ namespace Avalonia return _stylesApplied; } - /// - /// Detaches all styles from the element and queues a restyle. - /// - protected virtual void InvalidateStyles() => DetachStyles(); - protected void InitializeIfNeeded() { if (_initCount == 0 && !IsInitialized) @@ -508,17 +503,16 @@ namespace Avalonia }; } - void IStyleable.DetachStyles() => DetachStyles(); - void IStyleHost.StylesAdded(IReadOnlyList styles) { - InvalidateStylesOnThisAndDescendents(); + if (HasSettersOrAnimations(styles)) + InvalidateStyles(recurse: true); } void IStyleHost.StylesRemoved(IReadOnlyList styles) { - var allStyles = RecurseStyles(styles); - DetachStylesFromThisAndDescendents(allStyles); + if (FlattenStyles(styles) is { } allStyles) + DetachStyles(allStyles); } protected virtual void LogicalChildrenCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) @@ -663,6 +657,23 @@ namespace Avalonia return null; } + internal virtual void InvalidateStyles(bool recurse) + { + var values = GetValueStore(); + values.BeginStyling(); + try { values.RemoveFrames(FrameType.Style); } + finally { values.EndStyling(); } + + _stylesApplied = false; + + if (recurse && GetInheritanceChildren() is { } children) + { + var childCount = children.Count; + for (var i = 0; i < childCount; ++i) + (children[i] as StyledElement)?.InvalidateStyles(recurse); + } + } + private static void DataContextNotifying(IAvaloniaObject o, bool updateStarted) { if (o is StyledElement element) @@ -822,7 +833,7 @@ namespace Avalonia { _logicalRoot = null; _implicitTheme = null; - DetachStyles(); + InvalidateStyles(recurse: false); OnDetachedFromLogicalTree(e); DetachedFromLogicalTree?.Invoke(this, e); @@ -884,71 +895,81 @@ namespace Avalonia } } - private void DetachStyles(IReadOnlyList? styles = null) + private void DetachStyles(IReadOnlyList -"; - - using (StyledWindow(assets: ("test:style.xaml", styleXaml))) - { - var xaml = @" +"), + new RuntimeXamlLoaderDocument(@" - + -"; - - var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml); +") + }; + + using (StyledWindow()) + { + var compiled = AvaloniaRuntimeXamlLoader.LoadGroup(documents); + var window = Assert.IsType(compiled[1]); var border = window.FindControl("border"); var brush = (ISolidColorBrush)border.Background; @@ -284,13 +286,14 @@ namespace Avalonia.Markup.Xaml.UnitTests.MarkupExtensions [Fact] public void DynamicResource_Can_Be_Assigned_To_Property_In_ControlTemplate_In_Styles_File() { - var styleXaml = @" + var documents = new[] + { + new RuntimeXamlLoaderDocument(new Uri("avares://Tests/Style.xaml"), @" #ff506070 - -"; - - using (StyledWindow(assets: ("test:style.xaml", styleXaml))) - { - var xaml = @" +"), + new RuntimeXamlLoaderDocument(@" - +