Browse Source

Merge branch 'master' into fix-nested-popups

pull/2928/head
ahopper 7 years ago
committed by GitHub
parent
commit
4572876d78
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 14
      build/NetFX.props
  2. 6
      native/Avalonia.Native/src/OSX/window.mm
  3. 3
      samples/BindingDemo/MainWindow.xaml
  4. 12
      samples/ControlCatalog/MainView.xaml
  5. 4
      samples/ControlCatalog/Pages/ListBoxPage.xaml
  6. 21
      samples/ControlCatalog/Pages/ListBoxPage.xaml.cs
  7. 7
      src/Avalonia.Animation/Animatable.cs
  8. 10
      src/Avalonia.Base/Data/Core/ExpressionNode.cs
  9. 2
      src/Avalonia.Base/Data/Core/Plugins/InpcPropertyAccessorPlugin.cs
  10. 5
      src/Avalonia.Base/Data/Core/SettableNode.cs
  11. 50
      src/Avalonia.Base/Utilities/TypeUtilities.cs
  12. 3
      src/Avalonia.Base/Utilities/WeakEventHandlerManager.cs
  13. 32
      src/Avalonia.Controls/ContentControl.cs
  14. 13
      src/Avalonia.Controls/ItemsControl.cs
  15. 6
      src/Avalonia.Controls/ListBox.cs
  16. 166
      src/Avalonia.Controls/Mixins/ContentControlMixin.cs
  17. 5
      src/Avalonia.Controls/Notifications/ReversibleStackPanel.cs
  18. 2
      src/Avalonia.Controls/Platform/DefaultMenuInteractionHandler.cs
  19. 47
      src/Avalonia.Controls/Presenters/ContentPresenter.cs
  20. 13
      src/Avalonia.Controls/Presenters/IContentPresenter.cs
  21. 13
      src/Avalonia.Controls/Presenters/IContentPresenterHost.cs
  22. 11
      src/Avalonia.Controls/Presenters/ItemVirtualizerSimple.cs
  23. 26
      src/Avalonia.Controls/Primitives/HeaderedContentControl.cs
  24. 32
      src/Avalonia.Controls/Primitives/HeaderedItemsControl.cs
  25. 32
      src/Avalonia.Controls/Primitives/HeaderedSelectingItemsControl.cs
  26. 6
      src/Avalonia.Controls/Primitives/PopupPositioning/ManagedPopupPositioner.cs
  27. 20
      src/Avalonia.Controls/Primitives/SelectingItemsControl.cs
  28. 25
      src/Avalonia.Controls/RadioButton.cs
  29. 2
      src/Avalonia.Controls/StackPanel.cs
  30. 36
      src/Avalonia.Controls/TabControl.cs
  31. 5
      src/Avalonia.Diagnostics/Views/TreePageView.xaml.cs
  32. 9
      src/Avalonia.Input/AccessKeyHandler.cs
  33. 12
      src/Avalonia.Input/InputElement.cs
  34. 129
      src/Avalonia.Input/KeyGesture.cs
  35. 57
      src/Avalonia.Visuals/Rendering/DeferredRenderer.cs
  36. 14
      src/Avalonia.Visuals/Rendering/RenderLoop.cs
  37. 4
      src/Avalonia.X11/X11KeyTransform.cs
  38. 1
      src/Shared/PlatformSupport/AssetLoader.cs
  39. 4
      src/Windows/Avalonia.Win32/WindowsMountedVolumeInfoListener.cs
  40. 20
      tests/Avalonia.Base.UnitTests/WeakEventHandlerManagerTests.cs
  41. 1
      tests/Avalonia.Controls.UnitTests/AutoCompleteBoxTests.cs
  42. 40
      tests/Avalonia.Controls.UnitTests/ContentControlTests.cs
  43. 12
      tests/Avalonia.Controls.UnitTests/ContextMenuTests.cs
  44. 107
      tests/Avalonia.Controls.UnitTests/Mixins/ContentControlMixinTests.cs
  45. 13
      tests/Avalonia.Controls.UnitTests/Presenters/ContentPresenterTests_InTemplate.cs
  46. 2
      tests/Avalonia.Controls.UnitTests/Primitives/PopupRootTests.cs
  47. 47
      tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests.cs
  48. 25
      tests/Avalonia.Controls.UnitTests/StackPanelTests.cs
  49. 12
      tests/Avalonia.Controls.UnitTests/TabControlTests.cs
  50. 3
      tests/Avalonia.Controls.UnitTests/TopLevelTests.cs
  51. 4
      tests/Avalonia.Controls.UnitTests/Utils/HotKeyManagerTests.cs
  52. 20
      tests/Avalonia.Input.UnitTests/KeyGestureTests.cs
  53. 68
      tests/Avalonia.Markup.UnitTests/Data/BindingTests.cs
  54. 1
      tests/Avalonia.Markup.Xaml.UnitTests/Xaml/BindingTests.cs
  55. 3
      tests/Avalonia.Markup.Xaml.UnitTests/Xaml/BindingTests_RelativeSource.cs

14
build/NetFX.props

@ -1,11 +1,7 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition=" '$(TargetFramework)' == 'net461' and '$(OS)' == 'Unix' ">
<FrameworkPathOverride>/usr/lib/mono/4.6.1-api</FrameworkPathOverride>
<FrameworkPathOverride Condition="$([MSBuild]::IsOsPlatform('OSX'))">/Library/Frameworks/Mono.framework/Versions/Current/lib/mono/4.6.1-api</FrameworkPathOverride>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'net47' and '$(OS)' == 'Unix' ">
<FrameworkPathOverride>/usr/lib/mono/4.7-api/</FrameworkPathOverride>
<FrameworkPathOverride Condition="$([MSBuild]::IsOsPlatform('OSX'))">/Library/Frameworks/Mono.framework/Versions/Current/lib/mono/4.7-api</FrameworkPathOverride>
</PropertyGroup>
<Project>
<ItemGroup>
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0-preview.2" PrivateAssets="All" />
</ItemGroup>
</Project>

6
native/Avalonia.Native/src/OSX/window.mm

@ -369,12 +369,9 @@ public:
virtual void UpdateCursor()
{
[View resetCursorRects];
if (cursor != nil)
{
auto rect = [Window frame];
[View addCursorRect:rect cursor:cursor];
[cursor set];
[cursor set];
}
}
@ -425,6 +422,7 @@ private:
{
WindowEvents = events;
[Window setCanBecomeKeyAndMain];
[Window disableCursorRects];
}
virtual HRESULT Show () override

3
samples/BindingDemo/MainWindow.xaml

@ -24,6 +24,9 @@
<TextBox Watermark="Two Way" UseFloatingWatermark="True" Text="{Binding Path=StringValue}" Name="first"/>
<TextBox Watermark="One Way" UseFloatingWatermark="True" Text="{Binding Path=StringValue, Mode=OneWay}"/>
<TextBox Watermark="One Time" UseFloatingWatermark="True" Text="{Binding Path=StringValue, Mode=OneTime}"/>
<!-- Removed due to #2983: reinstate when that's fixed.
<TextBox Watermark="One Way to Source" UseFloatingWatermark="True" Text="{Binding Path=StringValue, Mode=OneWayToSource}"/>
-->
</StackPanel>
<StackPanel Margin="18" Spacing="4" Width="200">
<TextBlock FontSize="16" Text="Collection Bindings"/>

12
samples/ControlCatalog/MainView.xaml

@ -24,7 +24,6 @@
<TabItem Header="CheckBox"><pages:CheckBoxPage/></TabItem>
<TabItem Header="ComboBox"><pages:ComboBoxPage/></TabItem>
<TabItem Header="ContextMenu"><pages:ContextMenuPage/></TabItem>
<!-- DataGrid is our special snowflake -->
<TabItem Header="DataGrid"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
@ -34,12 +33,15 @@
<TabItem Header="Drag+Drop"><pages:DragAndDropPage/></TabItem>
<TabItem Header="Expander"><pages:ExpanderPage/></TabItem>
<TabItem Header="Image"><pages:ImagePage/></TabItem>
<TabItem Header="ItemsRepeater"><pages:ItemsRepeaterPage/></TabItem>
<TabItem Header="ItemsRepeater"
ScrollViewer.VerticalScrollBarVisibility="Disabled">
<pages:ItemsRepeaterPage/>
</TabItem>
<TabItem Header="LayoutTransformControl"><pages:LayoutTransformControlPage/></TabItem>
<TabItem Header="ListBox"><pages:ListBoxPage/></TabItem>
<TabItem Header="Menu"><pages:MenuPage/></TabItem>
<TabItem Header="Notifications"><pages:NotificationsPage/></TabItem>
<TabItem Header="NumericUpDown"><pages:NumericUpDownPage/></TabItem>
<TabItem Header="NumericUpDown"><pages:NumericUpDownPage/></TabItem>
<TabItem Header="Pointers (Touch)"><pages:PointersPage/></TabItem>
<TabItem Header="ProgressBar"><pages:ProgressBarPage/></TabItem>
<TabItem Header="RadioButton"><pages:RadioButtonPage/></TabItem>
@ -50,12 +52,12 @@
<TabItem Header="ToolTip"><pages:ToolTipPage/></TabItem>
<TabItem Header="TreeView"><pages:TreeViewPage/></TabItem>
<TabItem Header="Viewbox"><pages:ViewboxPage/></TabItem>
<TabControl.Tag>
<TabControl.Tag>
<ComboBox x:Name="Themes" SelectedIndex="0" Width="100" Margin="8" HorizontalAlignment="Right" VerticalAlignment="Bottom">
<ComboBoxItem>Light</ComboBoxItem>
<ComboBoxItem>Dark</ComboBoxItem>
</ComboBox>
</TabControl.Tag>
</TabControl.Tag>
</TabControl>
</Grid>
</UserControl>

4
samples/ControlCatalog/Pages/ListBoxPage.xaml

@ -10,12 +10,14 @@
HorizontalAlignment="Center"
Spacing="16">
<StackPanel Orientation="Vertical" Spacing="8">
<ListBox Items="{Binding Items}" SelectedItems="{Binding SelectedItems}" SelectionMode="{Binding SelectionMode}" Width="250" Height="350"></ListBox>
<ListBox Items="{Binding Items}" SelectedItem="{Binding SelectedItem}" AutoScrollToSelectedItem="True" SelectedItems="{Binding SelectedItems}" SelectionMode="{Binding SelectionMode}" Width="250" Height="350"></ListBox>
<Button Command="{Binding AddItemCommand}">Add</Button>
<Button Command="{Binding RemoveItemCommand}">Remove</Button>
<Button Command="{Binding SelectRandomItemCommand}">Select Random Item</Button>
<ComboBox SelectedIndex="{Binding SelectionMode, Mode=TwoWay}">
<ComboBoxItem>Single</ComboBoxItem>
<ComboBoxItem>Multiple</ComboBoxItem>

21
samples/ControlCatalog/Pages/ListBoxPage.xaml.cs

@ -1,3 +1,4 @@
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive;
@ -27,7 +28,7 @@ namespace ControlCatalog.Pages
public PageViewModel()
{
Items = new ObservableCollection<string>(Enumerable.Range(1, 10).Select(i => GenerateItem()));
Items = new ObservableCollection<string>(Enumerable.Range(1, 10000).Select(i => GenerateItem()));
SelectedItems = new ObservableCollection<string>();
AddItemCommand = ReactiveCommand.Create(() => Items.Add(GenerateItem()));
@ -39,16 +40,34 @@ namespace ControlCatalog.Pages
Items.Remove(SelectedItems[0]);
}
});
SelectRandomItemCommand = ReactiveCommand.Create(() =>
{
var random = new Random();
SelectedItem = Items[random.Next(Items.Count - 1)];
});
}
public ObservableCollection<string> Items { get; }
private string _selectedItem;
public string SelectedItem
{
get { return _selectedItem; }
set { this.RaiseAndSetIfChanged(ref _selectedItem, value); }
}
public ObservableCollection<string> SelectedItems { get; }
public ReactiveCommand<Unit, Unit> AddItemCommand { get; }
public ReactiveCommand<Unit, Unit> RemoveItemCommand { get; }
public ReactiveCommand<Unit, Unit> SelectRandomItemCommand { get; }
public SelectionMode SelectionMode
{
get => _selectionMode;

7
src/Avalonia.Animation/Animatable.cs

@ -55,6 +55,11 @@ namespace Avalonia.Animation
}
set
{
if (value is null)
return;
if (_previousTransitions is null)
_previousTransitions = new Dictionary<AvaloniaProperty, IDisposable>();
SetAndRaise(TransitionsProperty, ref _transitions, value);
}
@ -70,7 +75,7 @@ namespace Avalonia.Animation
if (_transitions is null || _previousTransitions is null || e.Priority == BindingPriority.Animation) return;
// PERF-SENSITIVE: Called on every property change. Don't use LINQ here (too many allocations).
foreach (var transition in Transitions)
foreach (var transition in _transitions)
{
if (transition.Property == e.Property)
{

10
src/Avalonia.Base/Data/Core/ExpressionNode.cs

@ -8,9 +8,13 @@ namespace Avalonia.Data.Core
public abstract class ExpressionNode
{
private static readonly object CacheInvalid = new object();
protected static readonly WeakReference<object> UnsetReference =
new WeakReference<object>(AvaloniaProperty.UnsetValue);
protected static readonly WeakReference<object> NullReference =
new WeakReference<object>(null);
private WeakReference<object> _target = UnsetReference;
private Action<object> _subscriber;
private bool _listening;
@ -98,7 +102,7 @@ namespace Avalonia.Data.Core
if (notification == null)
{
LastValue = new WeakReference<object>(value);
LastValue = value != null ? new WeakReference<object>(value) : NullReference;
if (Next != null)
{
@ -111,7 +115,7 @@ namespace Avalonia.Data.Core
}
else
{
LastValue = new WeakReference<object>(notification.Value);
LastValue = notification.Value != null ? new WeakReference<object>(notification.Value) : NullReference;
if (Next != null)
{
@ -136,8 +140,8 @@ namespace Avalonia.Data.Core
}
else if (target != AvaloniaProperty.UnsetValue)
{
StartListeningCore(_target);
_listening = true;
StartListeningCore(_target);
}
else
{

2
src/Avalonia.Base/Data/Core/Plugins/InpcPropertyAccessorPlugin.cs

@ -103,8 +103,8 @@ namespace Avalonia.Data.Core.Plugins
protected override void SubscribeCore()
{
SendCurrentValue();
SubscribeToChanges();
SendCurrentValue();
}
protected override void UnsubscribeCore()

5
src/Avalonia.Base/Data/Core/SettableNode.cs

@ -29,6 +29,11 @@ namespace Avalonia.Data.Core
if (!isLastValueAlive)
{
if (value == null && LastValue == NullReference)
{
return true;
}
return false;
}

50
src/Avalonia.Base/Utilities/TypeUtilities.cs

@ -13,7 +13,7 @@ namespace Avalonia.Utilities
/// </summary>
public static class TypeUtilities
{
private static int[] Conversions =
private static readonly int[] Conversions =
{
0b101111111111101, // Boolean
0b100001111111110, // Char
@ -32,7 +32,7 @@ namespace Avalonia.Utilities
0b111111111111111, // String
};
private static int[] ImplicitConversions =
private static readonly int[] ImplicitConversions =
{
0b000000000000001, // Boolean
0b001110111100010, // Char
@ -51,7 +51,7 @@ namespace Avalonia.Utilities
0b100000000000000, // String
};
private static Type[] InbuiltTypes =
private static readonly Type[] InbuiltTypes =
{
typeof(Boolean),
typeof(Char),
@ -70,7 +70,7 @@ namespace Avalonia.Utilities
typeof(String),
};
private static readonly Type[] NumericTypes = new[]
private static readonly Type[] NumericTypes =
{
typeof(Byte),
typeof(Decimal),
@ -188,8 +188,7 @@ namespace Avalonia.Utilities
}
}
var cast = from.GetRuntimeMethods()
.FirstOrDefault(m => (m.Name == "op_Implicit" || m.Name == "op_Explicit") && m.ReturnType == to);
var cast = FindTypeConversionOperatorMethod(from, to, OperatorType.Implicit | OperatorType.Explicit);
if (cast != null)
{
@ -253,8 +252,7 @@ namespace Avalonia.Utilities
}
}
var cast = from.GetRuntimeMethods()
.FirstOrDefault(m => m.Name == "op_Implicit" && m.ReturnType == to);
var cast = FindTypeConversionOperatorMethod(from, to, OperatorType.Implicit);
if (cast != null)
{
@ -335,5 +333,41 @@ namespace Avalonia.Utilities
return NumericTypes.Contains(type);
}
}
[Flags]
private enum OperatorType
{
Implicit = 1,
Explicit = 2
}
private static MethodInfo FindTypeConversionOperatorMethod(Type fromType, Type toType, OperatorType operatorType)
{
const string implicitName = "op_Implicit";
const string explicitName = "op_Explicit";
bool allowImplicit = (operatorType & OperatorType.Implicit) != 0;
bool allowExplicit = (operatorType & OperatorType.Explicit) != 0;
foreach (MethodInfo method in fromType.GetMethods())
{
if (!method.IsSpecialName || method.ReturnType != toType)
{
continue;
}
if (allowImplicit && method.Name == implicitName)
{
return method;
}
if (allowExplicit && method.Name == explicitName)
{
return method;
}
}
return null;
}
}
}

3
src/Avalonia.Base/Utilities/WeakEventHandlerManager.cs

@ -161,9 +161,8 @@ namespace Avalonia.Utilities
for (int c = 0; c < _count; ++c)
{
var reference = _data[c].Subscriber;
TSubscriber instance;
if (reference != null && reference.TryGetTarget(out instance) && instance == s)
if (reference != null && reference.TryGetTarget(out TSubscriber instance) && Equals(instance, s.Target))
{
_data[c] = default;
removed = true;

32
src/Avalonia.Controls/ContentControl.cs

@ -1,11 +1,13 @@
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Collections;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Layout;
using Avalonia.LogicalTree;
using Avalonia.Metadata;
namespace Avalonia.Controls
@ -39,12 +41,9 @@ namespace Avalonia.Controls
public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty =
AvaloniaProperty.Register<ContentControl, VerticalAlignment>(nameof(VerticalContentAlignment));
/// <summary>
/// Initializes static members of the <see cref="ContentControl"/> class.
/// </summary>
static ContentControl()
{
ContentControlMixin.Attach<ContentControl>(ContentProperty, x => x.LogicalChildren);
ContentProperty.Changed.AddClassHandler<ContentControl>(x => x.ContentChanged);
}
/// <summary>
@ -95,20 +94,39 @@ namespace Avalonia.Controls
}
/// <inheritdoc/>
void IContentPresenterHost.RegisterContentPresenter(IContentPresenter presenter)
IAvaloniaList<ILogical> IContentPresenterHost.LogicalChildren => LogicalChildren;
/// <inheritdoc/>
bool IContentPresenterHost.RegisterContentPresenter(IContentPresenter presenter)
{
RegisterContentPresenter(presenter);
return RegisterContentPresenter(presenter);
}
/// <summary>
/// Called when an <see cref="IContentPresenter"/> is registered with the control.
/// </summary>
/// <param name="presenter">The presenter.</param>
protected virtual void RegisterContentPresenter(IContentPresenter presenter)
protected virtual bool RegisterContentPresenter(IContentPresenter presenter)
{
if (presenter.Name == "PART_ContentPresenter")
{
Presenter = presenter;
return true;
}
return false;
}
private void ContentChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.OldValue is ILogical oldChild)
{
LogicalChildren.Remove(oldChild);
}
if (e.NewValue is ILogical newChild)
{
LogicalChildren.Add(newChild);
}
}
}

13
src/Avalonia.Controls/ItemsControl.cs

@ -302,19 +302,6 @@ namespace Avalonia.Controls
/// <param name="e">The details of the containers.</param>
protected virtual void OnContainersRecycled(ItemContainerEventArgs e)
{
var toRemove = new List<ILogical>();
foreach (var container in e.Containers)
{
// If the item is its own container, then it will be removed from the logical tree
// when it is removed from the Items collection.
if (container?.ContainerControl != container?.Item)
{
toRemove.Add(container.ContainerControl);
}
}
LogicalChildren.RemoveAll(toRemove);
}
/// <summary>

6
src/Avalonia.Controls/ListBox.cs

@ -66,7 +66,11 @@ namespace Avalonia.Controls
}
/// <inheritdoc/>
public new IList SelectedItems => base.SelectedItems;
public new IList SelectedItems
{
get => base.SelectedItems;
set => base.SelectedItems = value;
}
/// <summary>
/// Gets or sets the selection mode.

166
src/Avalonia.Controls/Mixins/ContentControlMixin.cs

@ -1,166 +0,0 @@
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Linq;
using System.Reactive.Disposables;
using System.Runtime.CompilerServices;
using Avalonia.Collections;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
namespace Avalonia.Controls.Mixins
{
/// <summary>
/// Adds content control functionality to control classes.
/// </summary>
/// <para>
/// The <see cref="ContentControlMixin"/> adds behavior to a control which acts as a content
/// control such as <see cref="ContentControl"/> and <see cref="HeaderedItemsControl"/>. It
/// keeps the control's logical children in sync with the content being displayed by the
/// control.
/// </para>
public class ContentControlMixin
{
private static Lazy<ConditionalWeakTable<TemplatedControl, IDisposable>> subscriptions =
new Lazy<ConditionalWeakTable<TemplatedControl, IDisposable>>(() =>
new ConditionalWeakTable<TemplatedControl, IDisposable>());
/// <summary>
/// Initializes a new instance of the <see cref="SelectableMixin"/> class.
/// </summary>
/// <typeparam name="TControl">The control type.</typeparam>
/// <param name="content">The content property.</param>
/// <param name="logicalChildrenSelector">
/// Given an control of <typeparamref name="TControl"/> should return the control's
/// logical children collection.
/// </param>
/// <param name="presenterName">
/// The name of the content presenter in the control's template.
/// </param>
public static void Attach<TControl>(
AvaloniaProperty content,
Func<TControl, IAvaloniaList<ILogical>> logicalChildrenSelector,
string presenterName = "PART_ContentPresenter")
where TControl : TemplatedControl
{
Contract.Requires<ArgumentNullException>(content != null);
Contract.Requires<ArgumentNullException>(logicalChildrenSelector != null);
void ChildChanging(object s, AvaloniaPropertyChangedEventArgs e)
{
if (s is IControl sender && sender?.TemplatedParent is TControl parent)
{
UpdateLogicalChild(
sender,
logicalChildrenSelector(parent),
e.OldValue,
null);
}
}
void TemplateApplied(object s, RoutedEventArgs ev)
{
if (s is TControl sender)
{
var e = (TemplateAppliedEventArgs)ev;
var presenter = e.NameScope.Find(presenterName) as IContentPresenter;
if (presenter != null)
{
presenter.ApplyTemplate();
var logicalChildren = logicalChildrenSelector(sender);
var subscription = new CompositeDisposable();
presenter.ChildChanging += ChildChanging;
subscription.Add(Disposable.Create(() => presenter.ChildChanging -= ChildChanging));
subscription.Add(presenter
.GetPropertyChangedObservable(ContentPresenter.ChildProperty)
.Subscribe(c => UpdateLogicalChild(
sender,
logicalChildren,
null,
c.NewValue)));
UpdateLogicalChild(
sender,
logicalChildren,
null,
presenter.GetValue(ContentPresenter.ChildProperty));
if (subscriptions.Value.TryGetValue(sender, out IDisposable previousSubscription))
{
subscription = new CompositeDisposable(previousSubscription, subscription);
subscriptions.Value.Remove(sender);
}
subscriptions.Value.Add(sender, subscription);
}
}
}
TemplatedControl.TemplateAppliedEvent.AddClassHandler(
typeof(TControl),
TemplateApplied,
RoutingStrategies.Direct);
content.Changed.Subscribe(e =>
{
if (e.Sender is TControl sender)
{
var logicalChildren = logicalChildrenSelector(sender);
UpdateLogicalChild(sender, logicalChildren, e.OldValue, e.NewValue);
}
});
Control.TemplatedParentProperty.Changed.Subscribe(e =>
{
if (e.Sender is TControl sender)
{
var logicalChild = logicalChildrenSelector(sender).FirstOrDefault() as IControl;
logicalChild?.SetValue(Control.TemplatedParentProperty, sender.TemplatedParent);
}
});
TemplatedControl.TemplateProperty.Changed.Subscribe(e =>
{
if (e.Sender is TControl sender)
{
if (subscriptions.Value.TryGetValue(sender, out IDisposable subscription))
{
subscription.Dispose();
subscriptions.Value.Remove(sender);
}
}
});
}
private static void UpdateLogicalChild(
IControl control,
IAvaloniaList<ILogical> logicalChildren,
object oldValue,
object newValue)
{
if (oldValue != newValue)
{
if (oldValue is IControl child)
{
logicalChildren.Remove(child);
((ISetInheritanceParent)child).SetParent(child.Parent);
}
child = newValue as IControl;
if (child != null && !logicalChildren.Contains(child))
{
child.SetValue(Control.TemplatedParentProperty, control.TemplatedParent);
logicalChildren.Add(child);
}
}
}
}
}

5
src/Avalonia.Controls/Notifications/ReversibleStackPanel.cs

@ -39,6 +39,11 @@ namespace Avalonia.Controls
foreach (Control child in children)
{
if (!child.IsVisible)
{
continue;
}
double childWidth = child.DesiredSize.Width;
double childHeight = child.DesiredSize.Height;

2
src/Avalonia.Controls/Platform/DefaultMenuInteractionHandler.cs

@ -377,7 +377,7 @@ namespace Avalonia.Controls.Platform
if (mouse?.Type == RawPointerEventType.NonClientLeftButtonDown)
{
Menu.Close();
Menu?.Close();
}
}

47
src/Avalonia.Controls/Presenters/ContentPresenter.cs

@ -6,6 +6,7 @@ using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Controls.Utils;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.LogicalTree;
using Avalonia.Media;
@ -83,7 +84,6 @@ namespace Avalonia.Controls.Presenters
private IControl _child;
private bool _createdChild;
EventHandler<AvaloniaPropertyChangedEventArgs> _childChanging;
private IDataTemplate _dataTemplate;
private readonly BorderRenderHelper _borderRenderer = new BorderRenderHelper();
@ -190,12 +190,10 @@ namespace Avalonia.Controls.Presenters
set { SetValue(PaddingProperty, value); }
}
/// <inheritdoc/>
event EventHandler<AvaloniaPropertyChangedEventArgs> IContentPresenter.ChildChanging
{
add => _childChanging += value;
remove => _childChanging -= value;
}
/// <summary>
/// Gets the host content control.
/// </summary>
internal IContentPresenterHost Host { get; private set; }
/// <inheritdoc/>
public sealed override void ApplyTemplate()
@ -222,34 +220,16 @@ namespace Avalonia.Controls.Presenters
var content = Content;
var oldChild = Child;
var newChild = CreateChild();
var logicalChildren = Host?.LogicalChildren ?? LogicalChildren;
// Remove the old child if we're not recycling it.
if (newChild != oldChild)
{
if (oldChild != null)
{
VisualChildren.Remove(oldChild);
}
if (oldChild?.Parent == this)
{
// If we're the child's parent then the presenter isn't in a ContentControl's
// template.
LogicalChildren.Remove(oldChild);
}
else if (TemplatedParent != null)
{
// If we're in a ContentControl's template then invoke ChildChanging to let
// ContentControlMixin handle removing the logical child.
_childChanging?.Invoke(this, new AvaloniaPropertyChangedEventArgs(
this,
ChildProperty,
oldChild,
newChild,
BindingPriority.LocalValue));
}
else if (oldChild != null)
{
logicalChildren.Remove(oldChild);
((ISetInheritanceParent)oldChild).SetParent(oldChild.Parent);
}
}
@ -272,15 +252,11 @@ namespace Avalonia.Controls.Presenters
else if (newChild != oldChild)
{
((ISetInheritanceParent)newChild).SetParent(this);
Child = newChild;
// If we're in a ContentControl's template then the child's parent will have been
// set by ContentControlMixin in response to Child changing. If not, then we're
// standalone and should make the control our own logical child.
if (newChild.Parent == null && TemplatedParent == null)
if (!logicalChildren.Contains(newChild))
{
LogicalChildren.Add(newChild);
logicalChildren.Add(newChild);
}
VisualChildren.Add(newChild);
@ -459,7 +435,8 @@ namespace Avalonia.Controls.Presenters
private void TemplatedParentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.NewValue as IContentPresenterHost)?.RegisterContentPresenter(this);
var host = e.NewValue as IContentPresenterHost;
Host = host?.RegisterContentPresenter(this) == true ? host : null;
}
}
}

13
src/Avalonia.Controls/Presenters/IContentPresenter.cs

@ -1,8 +1,6 @@
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Primitives;
namespace Avalonia.Controls.Presenters
@ -22,16 +20,5 @@ namespace Avalonia.Controls.Presenters
/// Gets or sets the content to be displayed by the presenter.
/// </summary>
object Content { get; set; }
/// <summary>
/// Raised when <see cref="Child"/> property is about to change.
/// </summary>
/// <remarks>
/// This event should be raised after the child has been removed from the visual tree,
/// but before the <see cref="Child"/> property has changed. It is intended for consumption
/// by <see cref="ContentControlMixin"/> in order to update the host control's logical
/// children.
/// </remarks>
event EventHandler<AvaloniaPropertyChangedEventArgs> ChildChanging;
}
}

13
src/Avalonia.Controls/Presenters/IContentPresenterHost.cs

@ -1,6 +1,8 @@
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Collections;
using Avalonia.LogicalTree;
using Avalonia.Styling;
namespace Avalonia.Controls.Presenters
@ -18,10 +20,19 @@ namespace Avalonia.Controls.Presenters
/// </remarks>
public interface IContentPresenterHost : ITemplatedControl
{
/// <summary>
/// Gets a collection describing the logical children of the host control.
/// </summary>
IAvaloniaList<ILogical> LogicalChildren { get; }
/// <summary>
/// Registers an <see cref="IContentPresenter"/> with a host control.
/// </summary>
/// <param name="presenter">The content presenter.</param>
void RegisterContentPresenter(IContentPresenter presenter);
/// <returns>
/// True if the content presenter should add its child to the logical children of the
/// host; otherwise false.
/// </returns>
bool RegisterContentPresenter(IContentPresenter presenter);
}
}

11
src/Avalonia.Controls/Presenters/ItemVirtualizerSimple.cs

@ -295,11 +295,14 @@ namespace Avalonia.Controls.Presenters
/// <inheritdoc/>
public override void ScrollIntoView(object item)
{
var index = Items.IndexOf(item);
if (index != -1)
if (Items != null)
{
ScrollIntoView(index);
var index = Items.IndexOf(item);
if (index != -1)
{
ScrollIntoView(index);
}
}
}

26
src/Avalonia.Controls/Primitives/HeaderedContentControl.cs

@ -4,6 +4,7 @@
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Templates;
using Avalonia.LogicalTree;
namespace Avalonia.Controls.Primitives
{
@ -29,10 +30,7 @@ namespace Avalonia.Controls.Primitives
/// </summary>
static HeaderedContentControl()
{
ContentControlMixin.Attach<HeaderedContentControl>(
HeaderProperty,
x => x.LogicalChildren,
"PART_HeaderPresenter");
ContentProperty.Changed.AddClassHandler<HeaderedContentControl>(x => x.HeaderChanged);
}
/// <summary>
@ -63,13 +61,29 @@ namespace Avalonia.Controls.Primitives
}
/// <inheritdoc/>
protected override void RegisterContentPresenter(IContentPresenter presenter)
protected override bool RegisterContentPresenter(IContentPresenter presenter)
{
base.RegisterContentPresenter(presenter);
var result = base.RegisterContentPresenter(presenter);
if (presenter.Name == "PART_HeaderPresenter")
{
HeaderPresenter = presenter;
result = true;
}
return result;
}
private void HeaderChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.OldValue is ILogical oldChild)
{
LogicalChildren.Remove(oldChild);
}
if (e.NewValue is ILogical newChild)
{
LogicalChildren.Add(newChild);
}
}
}

32
src/Avalonia.Controls/Primitives/HeaderedItemsControl.cs

@ -1,8 +1,10 @@
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Collections;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Presenters;
using Avalonia.LogicalTree;
namespace Avalonia.Controls.Primitives
{
@ -22,10 +24,7 @@ namespace Avalonia.Controls.Primitives
/// </summary>
static HeaderedItemsControl()
{
ContentControlMixin.Attach<HeaderedItemsControl>(
HeaderProperty,
x => x.LogicalChildren,
"PART_HeaderPresenter");
HeaderProperty.Changed.AddClassHandler<HeaderedItemsControl>(x => x.HeaderChanged);
}
/// <summary>
@ -47,20 +46,39 @@ namespace Avalonia.Controls.Primitives
}
/// <inheritdoc/>
void IContentPresenterHost.RegisterContentPresenter(IContentPresenter presenter)
IAvaloniaList<ILogical> IContentPresenterHost.LogicalChildren => LogicalChildren;
/// <inheritdoc/>
bool IContentPresenterHost.RegisterContentPresenter(IContentPresenter presenter)
{
RegisterContentPresenter(presenter);
return RegisterContentPresenter(presenter);
}
/// <summary>
/// Called when an <see cref="IContentPresenter"/> is registered with the control.
/// </summary>
/// <param name="presenter">The presenter.</param>
protected virtual void RegisterContentPresenter(IContentPresenter presenter)
protected virtual bool RegisterContentPresenter(IContentPresenter presenter)
{
if (presenter.Name == "PART_HeaderPresenter")
{
HeaderPresenter = presenter;
return true;
}
return false;
}
private void HeaderChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.OldValue is ILogical oldChild)
{
LogicalChildren.Remove(oldChild);
}
if (e.NewValue is ILogical newChild)
{
LogicalChildren.Add(newChild);
}
}
}

32
src/Avalonia.Controls/Primitives/HeaderedSelectingItemsControl.cs

@ -1,8 +1,10 @@
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Collections;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Presenters;
using Avalonia.LogicalTree;
namespace Avalonia.Controls.Primitives
{
@ -22,10 +24,7 @@ namespace Avalonia.Controls.Primitives
/// </summary>
static HeaderedSelectingItemsControl()
{
ContentControlMixin.Attach<HeaderedSelectingItemsControl>(
HeaderProperty,
x => x.LogicalChildren,
"PART_HeaderPresenter");
HeaderProperty.Changed.AddClassHandler<HeaderedSelectingItemsControl>(x => x.HeaderChanged);
}
/// <summary>
@ -47,20 +46,39 @@ namespace Avalonia.Controls.Primitives
}
/// <inheritdoc/>
void IContentPresenterHost.RegisterContentPresenter(IContentPresenter presenter)
IAvaloniaList<ILogical> IContentPresenterHost.LogicalChildren => LogicalChildren;
/// <inheritdoc/>
bool IContentPresenterHost.RegisterContentPresenter(IContentPresenter presenter)
{
RegisterContentPresenter(presenter);
return RegisterContentPresenter(presenter);
}
/// <summary>
/// Called when an <see cref="IContentPresenter"/> is registered with the control.
/// </summary>
/// <param name="presenter">The presenter.</param>
protected virtual void RegisterContentPresenter(IContentPresenter presenter)
protected virtual bool RegisterContentPresenter(IContentPresenter presenter)
{
if (presenter.Name == "PART_HeaderPresenter")
{
HeaderPresenter = presenter;
return true;
}
return false;
}
private void HeaderChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.OldValue is ILogical oldChild)
{
LogicalChildren.Remove(oldChild);
}
if (e.NewValue is ILogical newChild)
{
LogicalChildren.Add(newChild);
}
}
}

6
src/Avalonia.Controls/Primitives/PopupPositioning/ManagedPopupPositioner.cs

@ -100,6 +100,12 @@ namespace Avalonia.Controls.Primitives.PopupPositioning
?? screens.FirstOrDefault(s => s.Bounds.Contains(parentGeometry.TopLeft))
?? screens.FirstOrDefault(s => s.Bounds.Intersects(parentGeometry))
?? screens.FirstOrDefault();
if (targetScreen != null && targetScreen.WorkingArea.IsEmpty)
{
return targetScreen.Bounds;
}
return targetScreen?.WorkingArea
?? new Rect(0, 0, double.MaxValue, double.MaxValue);
}

20
src/Avalonia.Controls/Primitives/SelectingItemsControl.cs

@ -112,7 +112,7 @@ namespace Avalonia.Controls.Primitives
private bool _syncingSelectedItems;
private int _updateCount;
private int _updateSelectedIndex;
private IList _updateSelectedItems;
private object _updateSelectedItem;
/// <summary>
/// Initializes static members of the <see cref="SelectingItemsControl"/> class.
@ -160,7 +160,7 @@ namespace Avalonia.Controls.Primitives
else
{
_updateSelectedIndex = value;
_updateSelectedItems = null;
_updateSelectedItem = null;
}
}
}
@ -183,7 +183,7 @@ namespace Avalonia.Controls.Primitives
}
else
{
_updateSelectedItems = new AvaloniaList<object>(value);
_updateSelectedItem = value;
_updateSelectedIndex = int.MinValue;
}
}
@ -855,11 +855,6 @@ namespace Avalonia.Controls.Primitives
_selectedItem = ElementAt(Items, _selectedIndex);
RaisePropertyChanged(SelectedIndexProperty, -1, _selectedIndex, BindingPriority.LocalValue);
RaisePropertyChanged(SelectedItemProperty, null, _selectedItem, BindingPriority.LocalValue);
if (AutoScrollToSelectedItem)
{
ScrollIntoView(_selectedIndex);
}
}
}
@ -1046,6 +1041,11 @@ namespace Avalonia.Controls.Primitives
removed?.Select(x => ElementAt(Items, x)).ToArray() ?? Array.Empty<object>());
RaiseEvent(e);
}
if (AutoScrollToSelectedItem && _selectedIndex != -1)
{
ScrollIntoView(_selectedItem);
}
}
private void UpdateSelectedItems(Action action)
@ -1075,9 +1075,9 @@ namespace Avalonia.Controls.Primitives
{
SelectedIndex = _updateSelectedIndex;
}
else if (_updateSelectedItems != null)
else if (_updateSelectedItem != null)
{
SelectedItems = _updateSelectedItems;
SelectedItem = _updateSelectedItem;
}
}

25
src/Avalonia.Controls/RadioButton.cs

@ -18,7 +18,7 @@ namespace Avalonia.Controls
public static readonly RadioButtonGroupManager Default = new RadioButtonGroupManager();
static readonly ConditionalWeakTable<IRenderRoot, RadioButtonGroupManager> s_registeredVisualRoots
= new ConditionalWeakTable<IRenderRoot, RadioButtonGroupManager>();
readonly Dictionary<string, List<WeakReference<RadioButton>>> s_registeredGroups
= new Dictionary<string, List<WeakReference<RadioButton>>>();
@ -127,13 +127,11 @@ namespace Avalonia.Controls
{
if (!string.IsNullOrEmpty(GroupName))
{
var manager = RadioButtonGroupManager.GetOrCreateForRoot(e.Root);
if (manager != _groupManager)
{
_groupManager.Remove(this, _groupName);
_groupManager = manager;
manager.Add(this);
}
_groupManager?.Remove(this, _groupName);
_groupManager = RadioButtonGroupManager.GetOrCreateForRoot(e.Root);
_groupManager.Add(this);
}
base.OnAttachedToVisualTree(e);
}
@ -141,9 +139,10 @@ namespace Avalonia.Controls
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTree(e);
if (!string.IsNullOrEmpty(GroupName) && _groupManager != null)
if (!string.IsNullOrEmpty(GroupName))
{
_groupManager.Remove(this, _groupName);
_groupManager?.Remove(this, _groupName);
}
}
@ -152,9 +151,9 @@ namespace Avalonia.Controls
string oldGroupName = GroupName;
if (newGroupName != oldGroupName)
{
if (!string.IsNullOrEmpty(oldGroupName) && _groupManager != null)
if (!string.IsNullOrEmpty(oldGroupName))
{
_groupManager.Remove(this, oldGroupName);
_groupManager?.Remove(this, oldGroupName);
}
_groupName = newGroupName;
if (!string.IsNullOrEmpty(newGroupName))
@ -181,7 +180,7 @@ namespace Avalonia.Controls
.GetVisualChildren()
.OfType<RadioButton>()
.Where(x => x != this);
foreach (var sibling in siblings)
{
if (sibling.IsChecked.GetValueOrDefault())

2
src/Avalonia.Controls/StackPanel.cs

@ -251,7 +251,7 @@ namespace Avalonia.Controls
{
var child = children[i];
if (child == null)
if (child == null || !child.IsVisible)
{ continue; }
if (fHorizontal)

36
src/Avalonia.Controls/TabControl.cs

@ -2,6 +2,7 @@
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Linq;
using Avalonia.Collections;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Presenters;
@ -9,6 +10,7 @@ using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.LogicalTree;
using Avalonia.VisualTree;
namespace Avalonia.Controls
@ -16,7 +18,7 @@ namespace Avalonia.Controls
/// <summary>
/// A tab control that displays a tab strip along with the content of the selected tab.
/// </summary>
public class TabControl : SelectingItemsControl
public class TabControl : SelectingItemsControl, IContentPresenterHost
{
/// <summary>
/// Defines the <see cref="TabStripPlacement"/> property.
@ -68,10 +70,6 @@ namespace Avalonia.Controls
SelectionModeProperty.OverrideDefaultValue<TabControl>(SelectionMode.AlwaysSelected);
ItemsPanelProperty.OverrideDefaultValue<TabControl>(DefaultPanel);
AffectsMeasure<TabControl>(TabStripPlacementProperty);
ContentControlMixin.Attach<TabControl>(
SelectedContentProperty,
x => x.LogicalChildren,
"PART_SelectedContentHost");
}
/// <summary>
@ -136,7 +134,31 @@ namespace Avalonia.Controls
internal ItemsPresenter ItemsPresenterPart { get; private set; }
internal ContentPresenter ContentPart { get; private set; }
internal IContentPresenter ContentPart { get; private set; }
/// <inheritdoc/>
IAvaloniaList<ILogical> IContentPresenterHost.LogicalChildren => LogicalChildren;
/// <inheritdoc/>
bool IContentPresenterHost.RegisterContentPresenter(IContentPresenter presenter)
{
return RegisterContentPresenter(presenter);
}
/// <summary>
/// Called when an <see cref="IContentPresenter"/> is registered with the control.
/// </summary>
/// <param name="presenter">The presenter.</param>
protected virtual bool RegisterContentPresenter(IContentPresenter presenter)
{
if (presenter.Name == "PART_SelectedContentHost")
{
ContentPart = presenter;
return true;
}
return false;
}
protected override IItemContainerGenerator CreateItemContainerGenerator()
{
@ -148,8 +170,6 @@ namespace Avalonia.Controls
base.OnTemplateApplied(e);
ItemsPresenterPart = e.NameScope.Get<ItemsPresenter>("PART_ItemsPresenter");
ContentPart = e.NameScope.Get<ContentPresenter>("PART_SelectedContentHost");
}
/// <inheritdoc/>

5
src/Avalonia.Diagnostics/Views/TreePageView.xaml.cs

@ -70,7 +70,10 @@ namespace Avalonia.Diagnostics.Views
private void TreeViewItemTemplateApplied(object sender, TemplateAppliedEventArgs e)
{
var item = (TreeViewItem)sender;
var header = item.HeaderPresenter.Child;
var headerPresenter = item.HeaderPresenter;
headerPresenter.ApplyTemplate();
var header = headerPresenter.Child;
header.PointerEnter += AddAdorner;
header.PointerLeave += RemoveAdorner;
item.TemplateApplied -= TreeViewItemTemplateApplied;

9
src/Avalonia.Input/AccessKeyHandler.cs

@ -231,15 +231,6 @@ namespace Avalonia.Input
}
break;
case Key.F10:
_owner.ShowAccessKeys = _showingAccessKeys = true;
if (MainMenu != null)
{
MainMenu.Open();
e.Handled = true;
}
break;
}
}

12
src/Avalonia.Input/InputElement.cs

@ -565,9 +565,17 @@ namespace Avalonia.Input
{
IsEffectivelyEnabled = IsEnabledCore && (parent?.IsEffectivelyEnabled ?? true);
foreach (var child in this.GetVisualChildren().OfType<InputElement>())
// PERF-SENSITIVE: This is called on entire hierarchy and using foreach or LINQ
// will cause extra allocations and overhead.
var children = VisualChildren;
// ReSharper disable once ForCanBeConvertedToForeach
for (int i = 0; i < children.Count; ++i)
{
child.UpdateIsEffectivelyEnabled(this);
var child = children[i] as InputElement;
child?.UpdateIsEffectivelyEnabled(this);
}
}
}

129
src/Avalonia.Input/KeyGesture.cs

@ -1,41 +1,56 @@
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Avalonia.Input
{
/// <summary>
/// Defines a keyboard input combination.
/// </summary>
public sealed class KeyGesture : IEquatable<KeyGesture>
{
public KeyGesture()
private static readonly Dictionary<string, Key> s_keySynonyms = new Dictionary<string, Key>
{
{ "+", Key.OemPlus }, { "-", Key.OemMinus }, { ".", Key.OemPeriod }
};
[Obsolete("Use constructor taking KeyModifiers")]
public KeyGesture(Key key, InputModifiers modifiers)
{
Key = key;
KeyModifiers = (KeyModifiers)(((int)modifiers) & 0xf);
}
public KeyGesture(Key key, InputModifiers modifiers = InputModifiers.None)
public KeyGesture(Key key, KeyModifiers modifiers = KeyModifiers.None)
{
Key = key;
Modifiers = modifiers;
KeyModifiers = modifiers;
}
public bool Equals(KeyGesture other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Key == other.Key && Modifiers == other.Modifiers;
return Key == other.Key && KeyModifiers == other.KeyModifiers;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj is KeyGesture && Equals((KeyGesture) obj);
return obj is KeyGesture && Equals((KeyGesture)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((int) Key*397) ^ (int) Modifiers;
return ((int)Key * 397) ^ (int)KeyModifiers;
}
}
@ -49,85 +64,85 @@ namespace Avalonia.Input
return !Equals(left, right);
}
public Key Key { get; set; }
public Key Key { get; }
[Obsolete("Use KeyModifiers")]
public InputModifiers Modifiers
{
get => (InputModifiers)KeyModifiers;
set => KeyModifiers = (KeyModifiers)(((int)value) & 0xf);
}
public KeyModifiers KeyModifiers { get; set; }
public InputModifiers Modifiers => (InputModifiers)KeyModifiers;
static readonly Dictionary<string, Key> KeySynonyms = new Dictionary<string, Key>
{
{"+", Key.OemPlus },
{"-", Key.OemMinus},
{".", Key.OemPeriod }
};
//TODO: Move that to external key parser
static Key ParseKey(string key)
{
Key rv;
if (KeySynonyms.TryGetValue(key.ToLower(), out rv))
return rv;
return (Key)Enum.Parse(typeof (Key), key, true);
}
static InputModifiers ParseModifier(string modifier)
{
if (modifier.Equals("ctrl", StringComparison.OrdinalIgnoreCase))
return InputModifiers.Control;
return (InputModifiers) Enum.Parse(typeof (InputModifiers), modifier, true);
}
public KeyModifiers KeyModifiers { get; }
public static KeyGesture Parse(string gesture)
{
//string.Split can't be used here because "Ctrl++" is a perfectly valid key gesture
// string.Split can't be used here because "Ctrl++" is a perfectly valid key gesture
var parts = new List<string>();
var key = Key.None;
var keyModifiers = KeyModifiers.None;
var cstart = 0;
for (var c = 0; c <= gesture.Length; c++)
{
var ch = c == gesture.Length ? '\0' : gesture[c];
if (c == gesture.Length || (ch == '+' && cstart != c))
bool isLast = c == gesture.Length;
if (isLast || (ch == '+' && cstart != c))
{
parts.Add(gesture.Substring(cstart, c - cstart));
var partSpan = gesture.AsSpan(cstart, c - cstart).Trim();
if (isLast)
{
key = ParseKey(partSpan.ToString());
}
else
{
keyModifiers |= ParseModifier(partSpan);
}
cstart = c + 1;
}
}
for (var c = 0; c < parts.Count; c++)
parts[c] = parts[c].Trim();
var rv = new KeyGesture();
for (var c = 0; c < parts.Count; c++)
{
if (c == parts.Count - 1)
rv.Key = ParseKey(parts[c]);
else
rv.Modifiers |= ParseModifier(parts[c]);
}
return rv;
return new KeyGesture(key, keyModifiers);
}
public override string ToString()
{
var parts = new List<string>();
foreach (var flag in Enum.GetValues(typeof (InputModifiers)).Cast<InputModifiers>())
foreach (var flag in Enum.GetValues(typeof(KeyModifiers)).Cast<KeyModifiers>())
{
if (Modifiers.HasFlag(flag) && flag != InputModifiers.None)
if (KeyModifiers.HasFlag(flag) && flag != KeyModifiers.None)
{
parts.Add(flag.ToString());
}
}
parts.Add(Key.ToString());
return string.Join(" + ", parts);
}
public bool Matches(KeyEventArgs keyEvent) => ResolveNumPadOperationKey(keyEvent.Key) == Key && keyEvent.Modifiers == Modifiers;
public bool Matches(KeyEventArgs keyEvent) => ResolveNumPadOperationKey(keyEvent.Key) == Key && keyEvent.KeyModifiers == KeyModifiers;
// TODO: Move that to external key parser
private static Key ParseKey(string key)
{
if (s_keySynonyms.TryGetValue(key.ToLower(), out Key rv))
return rv;
return (Key)Enum.Parse(typeof(Key), key, true);
}
private static KeyModifiers ParseModifier(ReadOnlySpan<char> modifier)
{
if (modifier.Equals("ctrl".AsSpan(), StringComparison.OrdinalIgnoreCase))
{
return KeyModifiers.Control;
}
return (KeyModifiers)Enum.Parse(typeof(KeyModifiers), modifier.ToString(), true);
}
private Key ResolveNumPadOperationKey(Key key)
{

57
src/Avalonia.Visuals/Rendering/DeferredRenderer.cs

@ -246,22 +246,7 @@ namespace Avalonia.Rendering
{
try
{
IDrawingContextImpl GetContext()
{
if (context != null)
return context;
if ((RenderTarget as IRenderTargetWithCorruptionInfo)?.IsCorrupted == true)
{
RenderTarget.Dispose();
RenderTarget = null;
}
if (RenderTarget == null)
RenderTarget = ((IRenderRoot)_root).CreateRenderTarget();
return context = RenderTarget.CreateDrawingContext(this);
}
var (scene, updated) = UpdateRenderLayersAndConsumeSceneIfNeeded(GetContext);
var (scene, updated) = UpdateRenderLayersAndConsumeSceneIfNeeded(ref context);
using (scene)
{
@ -271,9 +256,9 @@ namespace Avalonia.Rendering
if (DrawDirtyRects)
_dirtyRectsDisplay.Tick();
if (overlay)
RenderOverlay(scene.Item, GetContext());
RenderOverlay(scene.Item, ref context);
if (updated || forceComposite || overlay)
RenderComposite(scene.Item, GetContext());
RenderComposite(scene.Item, ref context);
}
}
}
@ -291,7 +276,7 @@ namespace Avalonia.Rendering
}
}
private (IRef<Scene> scene, bool updated) UpdateRenderLayersAndConsumeSceneIfNeeded(Func<IDrawingContextImpl> contextFactory,
private (IRef<Scene> scene, bool updated) UpdateRenderLayersAndConsumeSceneIfNeeded(ref IDrawingContextImpl context,
bool recursiveCall = false)
{
IRef<Scene> sceneRef;
@ -304,7 +289,8 @@ namespace Avalonia.Rendering
var scene = sceneRef.Item;
if (scene.Generation != _lastSceneId)
{
var context = contextFactory();
EnsureDrawingContext(ref context);
Layers.Update(scene, context);
RenderToLayers(scene);
@ -325,7 +311,7 @@ namespace Avalonia.Rendering
if (!recursiveCall && Dispatcher.UIThread.CheckAccess() && NeedsUpdate)
{
UpdateScene();
var (rs, _) = UpdateRenderLayersAndConsumeSceneIfNeeded(contextFactory, true);
var (rs, _) = UpdateRenderLayersAndConsumeSceneIfNeeded(ref context, true);
return (rs, true);
}
@ -432,8 +418,10 @@ namespace Avalonia.Rendering
}
private void RenderOverlay(Scene scene, IDrawingContextImpl parentContent)
private void RenderOverlay(Scene scene, ref IDrawingContextImpl parentContent)
{
EnsureDrawingContext(ref parentContent);
if (DrawDirtyRects)
{
var overlay = GetOverlay(parentContent, scene.Size, scene.Scaling);
@ -460,8 +448,10 @@ namespace Avalonia.Rendering
}
}
private void RenderComposite(Scene scene, IDrawingContextImpl context)
private void RenderComposite(Scene scene, ref IDrawingContextImpl context)
{
EnsureDrawingContext(ref context);
context.Clear(Colors.Transparent);
var clientRect = new Rect(scene.Size);
@ -503,6 +493,27 @@ namespace Avalonia.Rendering
}
}
private void EnsureDrawingContext(ref IDrawingContextImpl context)
{
if (context != null)
{
return;
}
if ((RenderTarget as IRenderTargetWithCorruptionInfo)?.IsCorrupted == true)
{
RenderTarget.Dispose();
RenderTarget = null;
}
if (RenderTarget == null)
{
RenderTarget = ((IRenderRoot)_root).CreateRenderTarget();
}
context = RenderTarget.CreateDrawingContext(this);
}
private void UpdateScene()
{
Dispatcher.UIThread.VerifyAccess();

14
src/Avalonia.Visuals/Rendering/RenderLoop.cs

@ -91,7 +91,19 @@ namespace Avalonia.Rendering
{
try
{
if (_items.Any(item => item.NeedsUpdate) &&
bool needsUpdate = false;
foreach (IRenderLoopTask item in _items)
{
if (item.NeedsUpdate)
{
needsUpdate = true;
break;
}
}
if (needsUpdate &&
Interlocked.CompareExchange(ref _inUpdate, 1, 0) == 0)
{
_dispatcher.Post(() =>

4
src/Avalonia.X11/X11KeyTransform.cs

@ -104,8 +104,8 @@ namespace Avalonia.X11
{X11Key.x, Key.X},
{X11Key.y, Key.Y},
{X11Key.z, Key.Z},
{X11Key.Meta_L, Key.LWin },
{X11Key.Meta_R, Key.RWin },
{X11Key.Super_L, Key.LWin },
{X11Key.Super_R, Key.RWin },
{X11Key.Menu, Key.Apps},
//{ X11Key.?, Key.Sleep }
{X11Key.KP_0, Key.NumPad0},

1
src/Shared/PlatformSupport/AssetLoader.cs

@ -242,6 +242,7 @@ namespace Avalonia.Shared.PlatformSupport
throw new InvalidOperationException(
$"Assembly {name} needs to be referenced and explicitly loaded before loading resources");
#else
name = Uri.UnescapeDataString(name);
AssemblyNameCache[name] = rv = new AssemblyDescriptor(Assembly.Load(name));
#endif
}

4
src/Windows/Avalonia.Win32/WindowsMountedVolumeInfoListener.cs

@ -32,9 +32,11 @@ namespace Avalonia.Win32
var allDrives = DriveInfo.GetDrives();
var mountVolInfos = allDrives
.Where(p => p.IsReady)
.Select(p => new MountedVolumeInfo()
{
VolumeLabel = p.VolumeLabel,
VolumeLabel = string.IsNullOrEmpty(p.VolumeLabel.Trim()) ? p.RootDirectory.FullName
: $"{p.VolumeLabel} ({p.Name})",
VolumePath = p.RootDirectory.FullName,
VolumeSizeBytes = (ulong)p.TotalSize
})

20
tests/Avalonia.Base.UnitTests/WeakEventHandlerManagerTests.cs

@ -36,7 +36,7 @@ namespace Avalonia.Base.UnitTests
}
[Fact]
public void EventShoudBePassedToSubscriber()
public void EventShouldBePassedToSubscriber()
{
bool handled = false;
var subscriber = new Subscriber(() => handled = true);
@ -47,7 +47,23 @@ namespace Avalonia.Base.UnitTests
Assert.True(handled);
}
[Fact]
public void EventShouldNotBeRaisedAfterUnsubscribe()
{
bool handled = false;
var subscriber = new Subscriber(() => handled = true);
var source = new EventSource();
WeakEventHandlerManager.Subscribe<EventSource, EventArgs, Subscriber>(source, "Event",
subscriber.OnEvent);
WeakEventHandlerManager.Unsubscribe<EventArgs, Subscriber>(source, "Event",
subscriber.OnEvent);
source.Fire();
Assert.False(handled);
}
[Fact]
public void EventHandlerShouldNotBeKeptAlive()
{

1
tests/Avalonia.Controls.UnitTests/AutoCompleteBoxTests.cs

@ -984,6 +984,7 @@ namespace Avalonia.Controls.UnitTests
TextBox textBox = GetTextBox(control);
var window = new Window {Content = control};
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
Dispatcher.UIThread.RunJobs();
test.Invoke(control, textBox);
}

40
tests/Avalonia.Controls.UnitTests/ContentControlTests.cs

@ -50,6 +50,7 @@ namespace Avalonia.Controls.UnitTests
root.Child = target;
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
styler.Verify(x => x.ApplyStyles(It.IsAny<ContentControl>()), Times.Once());
styler.Verify(x => x.ApplyStyles(It.IsAny<Border>()), Times.Once());
@ -331,6 +332,45 @@ namespace Avalonia.Controls.UnitTests
Assert.Null(textBlock.GetLogicalParent());
}
[Fact]
public void Should_Set_Child_LogicalParent_After_Removing_And_Adding_Back_To_Logical_Tree()
{
using (UnitTestApplication.Start(TestServices.RealStyler))
{
var target = new ContentControl();
var root = new TestRoot
{
Styles =
{
new Style(x => x.OfType<ContentControl>())
{
Setters =
{
new Setter(ContentControl.TemplateProperty, GetTemplate()),
}
}
},
Child = target
};
target.Content = "Foo";
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
Assert.Equal(target, target.Presenter.Child.LogicalParent);
root.Child = null;
Assert.Null(target.Template);
target.Content = null;
root.Child = target;
target.Content = "Bar";
Assert.Equal(target, target.Presenter.Child.LogicalParent);
}
}
private FuncControlTemplate GetTemplate()
{
return new FuncControlTemplate<ContentControl>((parent, scope) =>

12
tests/Avalonia.Controls.UnitTests/ContextMenuTests.cs

@ -27,7 +27,9 @@ namespace Avalonia.Controls.UnitTests
ContextMenu = sut
};
new Window { Content = target }.ApplyTemplate();
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
int openedCount = 0;
@ -53,7 +55,9 @@ namespace Avalonia.Controls.UnitTests
ContextMenu = sut
};
new Window { Content = target }.ApplyTemplate();
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
sut.Open(target);
@ -86,6 +90,7 @@ namespace Avalonia.Controls.UnitTests
var window = new Window {Content = target};
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
_mouse.Click(target, MouseButton.Right);
@ -115,7 +120,8 @@ namespace Avalonia.Controls.UnitTests
var window = new Window {Content = target};
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
_mouse.Click(target, MouseButton.Right);
Assert.True(sut.IsOpen);

107
tests/Avalonia.Controls.UnitTests/Mixins/ContentControlMixinTests.cs

@ -1,107 +0,0 @@
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using Avalonia.Collections;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.LogicalTree;
using Moq;
using Xunit;
namespace Avalonia.Controls.UnitTests.Mixins
{
public class ContentControlMixinTests
{
[Fact]
public void Multiple_Mixin_Usages_Should_Not_Throw()
{
var target = new TestControl()
{
Template = new FuncControlTemplate((_, scope) => new Panel
{
Children =
{
new ContentPresenter {Name = "Content_1_Presenter"}.RegisterInNameScope(scope),
new ContentPresenter {Name = "Content_2_Presenter"}.RegisterInNameScope(scope)
}
})
};
var ex = Record.Exception(() => target.ApplyTemplate());
Assert.Null(ex);
}
[Fact]
public void Replacing_Template_Releases_Events()
{
var p1 = new ContentPresenter { Name = "Content_1_Presenter" };
var p2 = new ContentPresenter { Name = "Content_2_Presenter" };
var target = new TestControl
{
Template = new FuncControlTemplate((_, scope) => new Panel
{
Children =
{
p1.RegisterInNameScope(scope),
p2.RegisterInNameScope(scope)
}
})
};
target.ApplyTemplate();
Control tc;
p1.Content = tc = new Control();
p1.UpdateChild();
Assert.Contains(tc, target.GetLogicalChildren());
p2.Content = tc = new Control();
p2.UpdateChild();
Assert.Contains(tc, target.GetLogicalChildren());
target.Template = null;
p1.Content = tc = new Control();
p1.UpdateChild();
Assert.DoesNotContain(tc, target.GetLogicalChildren());
p2.Content = tc = new Control();
p2.UpdateChild();
Assert.DoesNotContain(tc, target.GetLogicalChildren());
}
private class TestControl : TemplatedControl
{
public static readonly StyledProperty<object> Content1Property =
AvaloniaProperty.Register<TestControl, object>(nameof(Content1));
public static readonly StyledProperty<object> Content2Property =
AvaloniaProperty.Register<TestControl, object>(nameof(Content2));
static TestControl()
{
ContentControlMixin.Attach<TestControl>(Content1Property, x => x.LogicalChildren, "Content_1_Presenter");
ContentControlMixin.Attach<TestControl>(Content2Property, x => x.LogicalChildren, "Content_2_Presenter");
}
public object Content1
{
get { return GetValue(Content1Property); }
set { SetValue(Content1Property, value); }
}
public object Content2
{
get { return GetValue(Content2Property); }
set { SetValue(Content2Property, value); }
}
}
}
}

13
tests/Avalonia.Controls.UnitTests/Presenters/ContentPresenterTests_InTemplate.cs

@ -343,6 +343,19 @@ namespace Avalonia.Controls.UnitTests.Presenters
Assert.Same(logicalParent, ((IStyledElement)child).StylingParent);
}
[Fact]
public void Should_Clear_Host_When_Host_Template_Cleared()
{
var (target, host) = CreateTarget();
Assert.Same(host, target.Host);
host.Template = null;
host.ApplyTemplate();
Assert.Null(target.Host);
}
(ContentPresenter presenter, ContentControl templatedParent) CreateTarget()
{
var templatedParent = new ContentControl

2
tests/Avalonia.Controls.UnitTests/Primitives/PopupRootTests.cs

@ -51,6 +51,7 @@ namespace Avalonia.Controls.UnitTests.Primitives
window.Content = target;
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
target.ApplyTemplate();
target.Popup.Open();
@ -167,6 +168,7 @@ namespace Avalonia.Controls.UnitTests.Primitives
window.Content = target;
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
target.ApplyTemplate();
target.Popup.Open();
target.PopupContent = null;

47
tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests.cs

@ -894,6 +894,53 @@ namespace Avalonia.Controls.UnitTests.Primitives
Assert.Equal("Qux", target.SelectedItem);
}
[Fact]
public void AutoScrollToSelectedItem_Causes_Scroll_To_SelectedItem()
{
var items = new ObservableCollection<string>
{
"Foo",
"Bar",
"Baz"
};
var target = new ListBox
{
Template = Template(),
Items = items,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
var raised = false;
target.AddHandler(Control.RequestBringIntoViewEvent, (s, e) => raised = true);
target.SelectedIndex = 2;
Assert.True(raised);
}
[Fact]
public void Can_Set_Both_SelectedItem_And_SelectedItems_During_Initialization()
{
// Issue #2969.
var target = new ListBox();
var selectedItems = new List<object>();
target.BeginInit();
target.Template = Template();
target.Items = new[] { "Foo", "Bar", "Baz" };
target.SelectedItems = selectedItems;
target.SelectedItem = "Bar";
target.EndInit();
Assert.Equal("Bar", target.SelectedItem);
Assert.Equal(1, target.SelectedIndex);
Assert.Same(selectedItems, target.SelectedItems);
Assert.Equal(new[] { "Bar" }, selectedItems);
}
private FuncControlTemplate Template()
{
return new FuncControlTemplate<SelectingItemsControl>((control, scope) =>

25
tests/Avalonia.Controls.UnitTests/StackPanelTests.cs

@ -332,6 +332,31 @@ namespace Avalonia.Controls.UnitTests
Assert.Equal(sizeWithTwoChildren, sizeWithThreeChildren);
}
[Theory]
[InlineData(Orientation.Horizontal)]
[InlineData(Orientation.Vertical)]
public void Only_Arrange_Visible_Children(Orientation orientation)
{
var hiddenPanel = new Panel { Width = 10, Height = 10, IsVisible = false };
var panel = new Panel { Width = 10, Height = 10 };
var target = new StackPanel
{
Spacing = 40,
Orientation = orientation,
Children =
{
hiddenPanel,
panel
}
};
target.Measure(Size.Infinity);
target.Arrange(new Rect(target.DesiredSize));
Assert.Equal(new Rect(0, 0, 10, 10), panel.Bounds);
}
private class TestControl : Control
{
public Size MeasureConstraint { get; private set; }

12
tests/Avalonia.Controls.UnitTests/TabControlTests.cs

@ -183,27 +183,27 @@ namespace Avalonia.Controls.UnitTests
ApplyTemplate(target);
target.ContentPart.UpdateChild();
((ContentPresenter)target.ContentPart).UpdateChild();
var dataContext = ((TextBlock)target.ContentPart.Child).DataContext;
Assert.Equal(items[0], dataContext);
target.SelectedIndex = 1;
target.ContentPart.UpdateChild();
((ContentPresenter)target.ContentPart).UpdateChild();
dataContext = ((Button)target.ContentPart.Child).DataContext;
Assert.Equal(items[1], dataContext);
target.SelectedIndex = 2;
target.ContentPart.UpdateChild();
((ContentPresenter)target.ContentPart).UpdateChild();
dataContext = ((TextBlock)target.ContentPart.Child).DataContext;
Assert.Equal("Base", dataContext);
target.SelectedIndex = 3;
target.ContentPart.UpdateChild();
((ContentPresenter)target.ContentPart).UpdateChild();
dataContext = ((TextBlock)target.ContentPart.Child).DataContext;
Assert.Equal("Qux", dataContext);
target.SelectedIndex = 4;
target.ContentPart.UpdateChild();
((ContentPresenter)target.ContentPart).UpdateChild();
dataContext = target.ContentPart.DataContext;
Assert.Equal("Base", dataContext);
}
@ -279,7 +279,7 @@ namespace Avalonia.Controls.UnitTests
};
ApplyTemplate(target);
target.ContentPart.UpdateChild();
((ContentPresenter)target.ContentPart).UpdateChild();
var content = Assert.IsType<TextBlock>(target.ContentPart.Child);
Assert.Equal("bar", content.Tag);

3
tests/Avalonia.Controls.UnitTests/TopLevelTests.cs

@ -202,8 +202,9 @@ namespace Avalonia.Controls.UnitTests
target.Template = CreateTemplate();
target.Content = child;
target.ApplyTemplate();
Assert.Throws<InvalidOperationException>(() => target.ApplyTemplate());
Assert.Throws<InvalidOperationException>(() => target.Presenter.ApplyTemplate());
}
}

4
tests/Avalonia.Controls.UnitTests/Utils/HotKeyManagerTests.cs

@ -24,8 +24,8 @@ namespace Avalonia.Controls.UnitTests.Utils
.Bind<IWindowingPlatform>().ToConstant(new WindowingPlatformMock())
.Bind<IStyler>().ToConstant(styler.Object);
var gesture1 = new KeyGesture {Key = Key.A, Modifiers = InputModifiers.Control};
var gesture2 = new KeyGesture {Key = Key.B, Modifiers = InputModifiers.Control};
var gesture1 = new KeyGesture(Key.A, InputModifiers.Control);
var gesture2 = new KeyGesture(Key.B, InputModifiers.Control);
var tl = new Window();
var button = new Button();

20
tests/Avalonia.Input.UnitTests/KeyGestureTests.cs

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Avalonia.Input.UnitTests
@ -11,13 +7,11 @@ namespace Avalonia.Input.UnitTests
{
public static readonly IEnumerable<object[]> SampleData = new object[][]
{
new object[]{"Ctrl+A", new KeyGesture {Key = Key.A, Modifiers = InputModifiers.Control}},
new object[]{" \tShift\t+Alt +B", new KeyGesture {Key = Key.B, Modifiers = InputModifiers.Shift|InputModifiers.Alt} },
new object[]{"Control++", new KeyGesture {Key = Key.OemPlus, Modifiers = InputModifiers.Control} }
new object[]{"Ctrl+A", new KeyGesture(Key.A, InputModifiers.Control)},
new object[]{" \tShift\t+Alt +B", new KeyGesture(Key.B, InputModifiers.Shift | InputModifiers.Alt) },
new object[]{"Control++", new KeyGesture(Key.OemPlus, InputModifiers.Control) }
};
[Theory]
[MemberData(nameof(SampleData))]
public void Key_Gesture_Is_Able_To_Parse_Sample_Data(string text, KeyGesture gesture)
@ -31,10 +25,8 @@ namespace Avalonia.Input.UnitTests
[InlineData(Key.OemPeriod, Key.Decimal)]
public void Key_Gesture_Matches_NumPad_To_Regular_Digit(Key gestureKey, Key pressedKey)
{
var keyGesture = new KeyGesture
{
Key = gestureKey
};
var keyGesture = new KeyGesture(gestureKey);
Assert.True(keyGesture.Matches(new KeyEventArgs
{
Key = pressedKey

68
tests/Avalonia.Markup.UnitTests/Data/BindingTests.cs

@ -154,6 +154,18 @@ namespace Avalonia.Markup.UnitTests.Data
Assert.Equal("bar", source.Foo);
}
[Fact]
public void OneTime_Binding_Releases_Subscription_If_DataContext_Set_Later()
{
var target = new TextBlock();
var source = new Source { Foo = "foo" };
target.Bind(TextBlock.TextProperty, new Binding("Foo", BindingMode.OneTime));
target.DataContext = source;
Assert.Equal(0, source.SubscriberCount);
}
[Fact]
public void OneWayToSource_Binding_Should_Be_Set_Up()
{
@ -196,6 +208,30 @@ namespace Avalonia.Markup.UnitTests.Data
Assert.Equal("baz", target.Text);
}
[Fact]
public void OneWayToSource_Binding_Should_Not_StackOverflow_With_Null_Value()
{
// Issue #2912
var target = new TextBlock { Text = null };
var binding = new Binding
{
Path = "Foo",
Mode = BindingMode.OneWayToSource,
};
target.Bind(TextBox.TextProperty, binding);
var source = new Source { Foo = "foo" };
target.DataContext = source;
Assert.Null(source.Foo);
// When running tests under NCrunch, NCrunch replaces the standard StackOverflowException
// with its own, which will be caught by our code. Detect the stackoverflow anyway, by
// making sure the target property was only set once.
Assert.Equal(2, source.FooSetCount);
}
[Fact]
public void Default_BindingMode_Should_Be_Used()
{
@ -543,6 +579,23 @@ namespace Avalonia.Markup.UnitTests.Data
Assert.Equal(expected, child.DoubleValue);
}
[Fact]
public void Combined_OneTime_And_OneWayToSource_Bindings_Should_Release_Subscriptions()
{
var target1 = new TextBlock();
var target2 = new TextBlock();
var root = new Panel { Children = { target1, target2 } };
var source = new Source { Foo = "foo" };
using (target1.Bind(TextBlock.TextProperty, new Binding("Foo", BindingMode.OneTime)))
using (target2.Bind(TextBlock.TextProperty, new Binding("Foo", BindingMode.OneWayToSource)))
{
root.DataContext = source;
}
Assert.Equal(0, source.SubscriberCount);
}
private class StyledPropertyClass : AvaloniaObject
{
public static readonly StyledProperty<double> DoubleValueProperty =
@ -622,6 +675,7 @@ namespace Avalonia.Markup.UnitTests.Data
public class Source : INotifyPropertyChanged
{
private PropertyChangedEventHandler _propertyChanged;
private string _foo;
public string Foo
@ -630,15 +684,25 @@ namespace Avalonia.Markup.UnitTests.Data
set
{
_foo = value;
++FooSetCount;
RaisePropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public int FooSetCount { get; private set; }
public int SubscriberCount { get; private set; }
public event PropertyChangedEventHandler PropertyChanged
{
add { _propertyChanged += value; ++SubscriberCount; }
remove { _propertyChanged += value; --SubscriberCount; }
}
private void RaisePropertyChanged([CallerMemberName] string prop = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
_propertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
}

1
tests/Avalonia.Markup.Xaml.UnitTests/Xaml/BindingTests.cs

@ -142,6 +142,7 @@ namespace Avalonia.Markup.Xaml.UnitTests.Xaml
window.DataContext = new { Foo = "foo" };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
Assert.Equal("foo", border.DataContext);
}

3
tests/Avalonia.Markup.Xaml.UnitTests/Xaml/BindingTests_RelativeSource.cs

@ -73,6 +73,7 @@ namespace Avalonia.Markup.Xaml.UnitTests.Xaml
var button = window.FindControl<Button>("button");
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
Assert.Equal("border2", button.Content);
}
@ -169,6 +170,7 @@ namespace Avalonia.Markup.Xaml.UnitTests.Xaml
var button = window.FindControl<Button>("button");
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
Assert.Equal("border1", button.Content);
}
@ -293,6 +295,7 @@ namespace Avalonia.Markup.Xaml.UnitTests.Xaml
var button = window.FindControl<Button>("button");
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
Assert.Equal("title", button.Content);
}

Loading…
Cancel
Save