Browse Source

Merge branch 'master' into update-net-5.0

pull/6757/head
Dan Walmsley 5 years ago
committed by GitHub
parent
commit
bba17e075a
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      native/Avalonia.Native/src/OSX/window.mm
  2. 1
      packages/Avalonia/AvaloniaBuildTasks.targets
  3. 8
      readme.md
  4. 8
      samples/ControlCatalog/MainWindow.xaml
  5. 2
      samples/ControlCatalog/Pages/ButtonPage.xaml
  6. 6
      samples/ControlCatalog/Pages/CheckBoxPage.xaml
  7. 20
      samples/ControlCatalog/Pages/DialogsPage.xaml
  8. 24
      samples/ControlCatalog/Pages/ItemsRepeaterPage.xaml
  9. 11
      samples/ControlCatalog/Pages/ListBoxPage.xaml
  10. 6
      samples/ControlCatalog/Pages/RadioButtonPage.xaml
  11. 10
      samples/ControlCatalog/Pages/TextBoxPage.xaml
  12. 6
      samples/ControlCatalog/Pages/ToggleSwitchPage.xaml
  13. 18
      src/Avalonia.Controls.DataGrid/DataGrid.cs
  14. 30
      src/Avalonia.Controls.DataGrid/DataGridColumnHeader.cs
  15. 2
      src/Avalonia.Controls/Border.cs
  16. 10
      src/Avalonia.Controls/Button.cs
  17. 15
      src/Avalonia.Controls/ContextMenu.cs
  18. 43
      src/Avalonia.Controls/ItemsControl.cs
  19. 3
      src/Avalonia.Controls/NativeMenuItem.cs
  20. 2
      src/Avalonia.Controls/NumericUpDown/NumericUpDown.cs
  21. 24
      src/Avalonia.Controls/Panel.cs
  22. 41
      src/Avalonia.Controls/Presenters/ItemsPresenterBase.cs
  23. 2
      src/Avalonia.Controls/Primitives/AccessText.cs
  24. 2
      src/Avalonia.Controls/Primitives/Popup.cs
  25. 4
      src/Avalonia.Controls/Primitives/PopupPositioning/IPopupPositioner.cs
  26. 3
      src/Avalonia.Controls/ProgressBar.cs
  27. 2
      src/Avalonia.Controls/Remote/RemoteWidget.cs
  28. 10
      src/Avalonia.Controls/RepeatButton.cs
  29. 31
      src/Avalonia.Controls/Repeater/ItemsRepeater.cs
  30. 2
      src/Avalonia.Controls/TextBox.cs
  31. 49
      src/Avalonia.Controls/TrayIcon.cs
  32. 27
      src/Avalonia.Controls/Utils/IEnumerableUtils.cs
  33. 2
      src/Avalonia.Diagnostics/Diagnostics/Models/EventChainLink.cs
  34. 26
      src/Avalonia.Diagnostics/Diagnostics/ViewModels/EventTreeNode.cs
  35. 5
      src/Avalonia.Diagnostics/Diagnostics/ViewModels/FiredEvent.cs
  36. 6
      src/Avalonia.FreeDesktop/DBusHelper.cs
  37. 178
      src/Avalonia.FreeDesktop/DBusTrayIconImpl.cs
  38. 26
      src/Avalonia.Styling/LogicalTree/ChildIndexChangedEventArgs.cs
  39. 32
      src/Avalonia.Styling/LogicalTree/IChildIndexProvider.cs
  40. 56
      src/Avalonia.Styling/Styling/Activators/NthChildActivator.cs
  41. 145
      src/Avalonia.Styling/Styling/NthChildSelector.cs
  42. 23
      src/Avalonia.Styling/Styling/NthLastChildSelector.cs
  43. 16
      src/Avalonia.Styling/Styling/Selectors.cs
  44. 3
      src/Avalonia.Themes.Default/AutoCompleteBox.xaml
  45. 1
      src/Avalonia.Themes.Default/Button.xaml
  46. 1
      src/Avalonia.Themes.Default/CheckBox.xaml
  47. 3
      src/Avalonia.Themes.Default/ComboBox.xaml
  48. 1
      src/Avalonia.Themes.Default/ContextMenu.xaml
  49. 2
      src/Avalonia.Themes.Default/FlyoutPresenter.xaml
  50. 2
      src/Avalonia.Themes.Default/MenuFlyoutPresenter.xaml
  51. 4
      src/Avalonia.Themes.Default/MenuItem.xaml
  52. 28
      src/Avalonia.Themes.Default/OverlayPopupHost.xaml
  53. 12
      src/Avalonia.Themes.Default/PopupRoot.xaml
  54. 1
      src/Avalonia.Themes.Default/RadioButton.xaml
  55. 1
      src/Avalonia.Themes.Default/ToggleButton.xaml
  56. 1
      src/Avalonia.Themes.Default/ToggleSwitch.xaml
  57. 1
      src/Avalonia.Themes.Fluent/Controls/Button.xaml
  58. 1
      src/Avalonia.Themes.Fluent/Controls/CheckBox.xaml
  59. 23
      src/Avalonia.Themes.Fluent/Controls/OverlayPopupHost.xaml
  60. 7
      src/Avalonia.Themes.Fluent/Controls/PopupRoot.xaml
  61. 1
      src/Avalonia.Themes.Fluent/Controls/RadioButton.xaml
  62. 1
      src/Avalonia.Themes.Fluent/Controls/ToggleButton.xaml
  63. 1
      src/Avalonia.Themes.Fluent/Controls/ToggleSwitch.xaml
  64. 20
      src/Avalonia.Visuals/Rendering/SceneGraph/ClipNode.cs
  65. 12
      src/Avalonia.Visuals/Rendering/SceneGraph/DeferredDrawingContextImpl.cs
  66. 14
      src/Avalonia.Visuals/Rendering/SceneGraph/GeometryClipNode.cs
  67. 2
      src/Avalonia.X11/X11IconLoader.cs
  68. 19
      src/Avalonia.X11/X11Platform.cs
  69. 47
      src/Avalonia.X11/XEmbedTrayIconImpl.cs
  70. 35
      src/Markup/Avalonia.Markup.Xaml.Loader/CompilerExtensions/Transformers/AvaloniaXamlIlSelectorTransformer.cs
  71. 149
      src/Markup/Avalonia.Markup/Markup/Parsers/SelectorGrammar.cs
  72. 6
      src/Markup/Avalonia.Markup/Markup/Parsers/SelectorParser.cs
  73. 7
      src/Skia/Avalonia.Skia/SKTypefaceCollection.cs
  74. 8
      src/tools/MicroComGenerator/Program.cs
  75. 14
      tests/Avalonia.Controls.UnitTests/ButtonTests.cs
  76. 75
      tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs
  77. 159
      tests/Avalonia.Markup.UnitTests/Parsers/SelectorGrammarTests.cs
  78. 197
      tests/Avalonia.Markup.Xaml.UnitTests/Xaml/StyleTests.cs
  79. 48
      tests/Avalonia.RenderTests/Controls/CustomRenderTests.cs
  80. 22
      tests/Avalonia.Skia.UnitTests/Media/SKTypefaceCollectionCacheTests.cs
  81. 291
      tests/Avalonia.Styling.UnitTests/SelectorTests_NthChild.cs
  82. 220
      tests/Avalonia.Styling.UnitTests/SelectorTests_NthLastChild.cs
  83. 7
      tests/Avalonia.Styling.UnitTests/StyleActivatorExtensions.cs
  84. BIN
      tests/TestFiles/Direct2D1/Controls/CustomRender/Clip_With_Transform.expected.png
  85. BIN
      tests/TestFiles/Direct2D1/Controls/CustomRender/GeometryClip_With_Transform.expected.png
  86. BIN
      tests/TestFiles/Skia/Controls/CustomRender/Clip_With_Transform.expected.png
  87. BIN
      tests/TestFiles/Skia/Controls/CustomRender/GeometryClip_With_Transform.expected.png

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

@ -52,7 +52,6 @@ public:
[Window setBackingType:NSBackingStoreBuffered];
[Window setOpaque:false];
[Window setContentView: StandardContainer];
}
virtual HRESULT ObtainNSWindowHandle(void** ret) override
@ -125,6 +124,8 @@ public:
SetPosition(lastPositionSet);
UpdateStyle();
[Window setContentView: StandardContainer];
[Window setTitle:_lastTitle];
if(ShouldTakeFocusOnShow() && activate)
@ -323,6 +324,7 @@ public:
BaseEvents->Resized(AvnSize{x,y}, reason);
}
[StandardContainer setFrameSize:NSSize{x,y}];
[Window setContentSize:NSSize{x, y}];
}
@finally

1
packages/Avalonia/AvaloniaBuildTasks.targets

@ -54,6 +54,7 @@
<Output TaskParameter="HashResult" PropertyName="AvaloniaResourcesDependencyHash" />
</Hash>
<MakeDir Directories="$(IntermediateOutputPath)/Avalonia" />
<WriteLinesToFile Overwrite="true" File="$(IntermediateOutputPath)/Avalonia/Resources.Inputs.cache" Lines="$(AvaloniaResourcesDependencyHash)" WriteOnlyWhenDifferent="True" />
</Target>

8
readme.md

@ -60,6 +60,9 @@ See the [build instructions here](Documentation/build.md).
## Contributing
This project exists thanks to all the people who contribute.
<a href="https://github.com/AvaloniaUI/Avalonia/graphs/contributors"><img src="https://opencollective.com/Avalonia/contributors.svg?width=890&button=false" /></a>
Please read the [contribution guidelines](CONTRIBUTING.md) before submitting a pull request.
## Code of Conduct
@ -71,11 +74,6 @@ For more information see the [.NET Foundation Code of Conduct](https://dotnetfou
Avalonia is licenced under the [MIT licence](licence.md).
## Contributors
This project exists thanks to all the people who contribute. [[Contribute](https://avaloniaui.net/contributing)].
<a href="https://github.com/AvaloniaUI/Avalonia/graphs/contributors"><img src="https://opencollective.com/Avalonia/contributors.svg?width=890&button=false" /></a>
### Backers
Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/Avalonia#backer)]

8
samples/ControlCatalog/MainWindow.xaml

@ -63,11 +63,11 @@
<Panel Margin="{Binding #MainWindow.OffScreenMargin}">
<DockPanel LastChildFill="True" Margin="{Binding #MainWindow.WindowDecorationMargin}">
<Menu Name="MainMenu" DockPanel.Dock="Top">
<MenuItem Header="File">
<MenuItem Header="Exit" Command="{Binding ExitCommand}" />
<MenuItem Header="_File">
<MenuItem Header="E_xit" Command="{Binding ExitCommand}" />
</MenuItem>
<MenuItem Header="Help">
<MenuItem Header="About" Command="{Binding AboutCommand}" />
<MenuItem Header="_Help">
<MenuItem Header="_About" Command="{Binding AboutCommand}" />
</MenuItem>
</Menu>
<local:MainView />

2
samples/ControlCatalog/Pages/ButtonPage.xaml

@ -10,7 +10,7 @@
HorizontalAlignment="Center"
Spacing="16">
<StackPanel Orientation="Vertical" Spacing="8" Width="200">
<Button>Standard XAML Button</Button>
<Button>Standard _XAML Button</Button>
<Button Foreground="White">Foreground</Button>
<Button Background="{DynamicResource SystemAccentColor}">Background</Button>
<Button IsEnabled="False">Disabled</Button>

6
samples/ControlCatalog/Pages/CheckBoxPage.xaml

@ -11,9 +11,9 @@
Spacing="16">
<StackPanel Orientation="Vertical"
Spacing="16">
<CheckBox>Unchecked</CheckBox>
<CheckBox IsChecked="True">Checked</CheckBox>
<CheckBox IsChecked="{x:Null}">Indeterminate</CheckBox>
<CheckBox>_Unchecked</CheckBox>
<CheckBox IsChecked="True">_Checked</CheckBox>
<CheckBox IsChecked="{x:Null}">_Indeterminate</CheckBox>
<CheckBox IsChecked="True" IsEnabled="False">Disabled</CheckBox>
</StackPanel>
<StackPanel Orientation="Vertical"

20
samples/ControlCatalog/Pages/DialogsPage.xaml

@ -3,15 +3,15 @@
x:Class="ControlCatalog.Pages.DialogsPage">
<StackPanel Orientation="Vertical" Spacing="4" Margin="4">
<CheckBox Name="UseFilters">Use filters</CheckBox>
<Button Name="OpenFile">Open File</Button>
<Button Name="SaveFile">Save File</Button>
<Button Name="SelectFolder">Select Folder</Button>
<Button Name="OpenBoth">Select Both</Button>
<Button Name="DecoratedWindow">Decorated window</Button>
<Button Name="DecoratedWindowDialog">Decorated window (dialog)</Button>
<Button Name="Dialog">Dialog</Button>
<Button Name="DialogNoTaskbar">Dialog (No taskbar icon)</Button>
<Button Name="OwnedWindow">Owned window</Button>
<Button Name="OwnedWindowNoTaskbar">Owned window (No taskbar icon)</Button>
<Button Name="OpenFile">_Open File</Button>
<Button Name="SaveFile">_Save File</Button>
<Button Name="SelectFolder">Select Fo_lder</Button>
<Button Name="OpenBoth">Select _Both</Button>
<Button Name="DecoratedWindow">Decorated _window</Button>
<Button Name="DecoratedWindowDialog">Decorated w_indow (dialog)</Button>
<Button Name="Dialog">_Dialog</Button>
<Button Name="DialogNoTaskbar">Dialog (_No taskbar icon)</Button>
<Button Name="OwnedWindow">Own_ed window</Button>
<Button Name="OwnedWindowNoTaskbar">Owned window (No tas_kbar icon)</Button>
</StackPanel>
</UserControl>

24
samples/ControlCatalog/Pages/ItemsRepeaterPage.xaml

@ -1,17 +1,33 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ControlCatalog.Pages.ItemsRepeaterPage">
<UserControl.Styles>
<Style Selector="ItemsRepeater TextBlock.oddTemplate">
<Setter Property="Background" Value="Yellow" />
<Setter Property="Foreground" Value="Black" />
</Style>
<Style Selector="ItemsRepeater TextBlock.evenTemplate">
<Setter Property="Background" Value="Wheat" />
<Setter Property="Foreground" Value="Black" />
</Style>
<Style Selector="ItemsRepeater TextBlock:nth-child(5n+3)">
<Setter Property="Foreground" Value="Red" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
<Style Selector="ItemsRepeater TextBlock:nth-last-child(5n+4)">
<Setter Property="Foreground" Value="Blue" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
</UserControl.Styles>
<UserControl.Resources>
<RecyclePool x:Key="RecyclePool" />
<DataTemplate x:Key="odd">
<TextBlock Background="Yellow"
Foreground="Black"
<TextBlock Classes="oddTemplate"
Height="{Binding Height}"
Text="{Binding Text}"/>
</DataTemplate>
<DataTemplate x:Key="even">
<TextBlock Background="Wheat"
Foreground="Black"
<TextBlock Classes="evenTemplate"
Height="{Binding Height}"
Text="{Binding Text}"/>
</DataTemplate>

11
samples/ControlCatalog/Pages/ListBoxPage.xaml

@ -2,9 +2,20 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ControlCatalog.Pages.ListBoxPage">
<DockPanel>
<DockPanel.Styles>
<Style Selector="ListBox ListBoxItem:nth-child(5n+3)">
<Setter Property="Foreground" Value="Red" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
<Style Selector="ListBox ListBoxItem:nth-last-child(5n+4)">
<Setter Property="Foreground" Value="Blue" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
</DockPanel.Styles>
<StackPanel DockPanel.Dock="Top" Margin="4">
<TextBlock Classes="h1">ListBox</TextBlock>
<TextBlock Classes="h2">Hosts a collection of ListBoxItem.</TextBlock>
<TextBlock Classes="h2">Each 5th item is highlighted with nth-child(5n+3) and nth-last-child(5n+4) rules.</TextBlock>
</StackPanel>
<StackPanel DockPanel.Dock="Right" Margin="4">
<CheckBox IsChecked="{Binding Multiple}">Multiple</CheckBox>

6
samples/ControlCatalog/Pages/RadioButtonPage.xaml

@ -11,9 +11,9 @@
Spacing="16">
<StackPanel Orientation="Vertical"
Spacing="16">
<RadioButton IsChecked="True">Option 1</RadioButton>
<RadioButton>Option 2</RadioButton>
<RadioButton IsChecked="{x:Null}">Option 3</RadioButton>
<RadioButton IsChecked="True">_Option 1</RadioButton>
<RadioButton>O_ption 2</RadioButton>
<RadioButton IsChecked="{x:Null}">Op_tion 3</RadioButton>
<RadioButton IsEnabled="False">Disabled</RadioButton>
</StackPanel>
<StackPanel Orientation="Vertical"

10
samples/ControlCatalog/Pages/TextBoxPage.xaml

@ -11,7 +11,15 @@
HorizontalAlignment="Center"
Spacing="16">
<StackPanel Orientation="Vertical" Spacing="8">
<TextBox Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit." Width="200" />
<TextBox Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit." Width="200"
FontFamily="Comic Sans MS"
Foreground="Blue">
<TextBox.ContextFlyout>
<Flyout>
<TextBlock>Custom context flyout</TextBlock>
</Flyout>
</TextBox.ContextFlyout>
</TextBox>
<TextBox Width="200" Watermark="ReadOnly" IsReadOnly="True" Text="This is read only"/>
<TextBox Width="200" Watermark="Numeric Watermark" x:Name="numericWatermark"/>
<TextBox Width="200"

6
samples/ControlCatalog/Pages/ToggleSwitchPage.xaml

@ -14,7 +14,7 @@
<Border Classes="Thin">
<StackPanel>
<ToggleSwitch Content="headered" IsChecked="true" Margin="10"/>
<ToggleSwitch Content="h_eadered" IsChecked="true" Margin="10"/>
<TextBox Classes="CodeBox"
Text="&lt;ToggleSwitch&gt;headered&lt;/ToggleSwitch&gt;"/>
</StackPanel>
@ -24,7 +24,7 @@
<Border Classes="Thin">
<StackPanel>
<ToggleSwitch Content="Custom"
<ToggleSwitch Content="_Custom"
OnContent="On"
OffContent="Off"
Margin="10"/>
@ -40,7 +40,7 @@ ContentOff=&quot;Off&quot; /&gt;"
<Border Classes="Thin">
<StackPanel>
<ToggleSwitch Content="Just Click!" Margin="10">
<ToggleSwitch Content="_Just Click!" Margin="10">
<ToggleSwitch.OnContent>
<Image Source="/Assets/hirsch-899118_640.jpg" Height="32"/>
</ToggleSwitch.OnContent>

18
src/Avalonia.Controls.DataGrid/DataGrid.cs

@ -2223,6 +2223,7 @@ namespace Avalonia.Controls
if (IsEnabled && DisplayData.NumDisplayedScrollingElements > 0)
{
var handled = false;
var ignoreInvalidate = false;
var scrollHeight = 0d;
// Vertical scroll handling
@ -2252,8 +2253,7 @@ namespace Avalonia.Controls
// Horizontal scroll handling
if (delta.X != 0)
{
var originalHorizontalOffset = HorizontalOffset;
var horizontalOffset = originalHorizontalOffset - delta.X;
var horizontalOffset = HorizontalOffset - delta.X;
var widthNotVisible = Math.Max(0, ColumnsInternal.VisibleEdgedColumnsWidth - CellsWidth);
if (horizontalOffset < 0)
@ -2265,16 +2265,20 @@ namespace Avalonia.Controls
horizontalOffset = widthNotVisible;
}
if (horizontalOffset != originalHorizontalOffset)
if (UpdateHorizontalOffset(horizontalOffset))
{
HorizontalOffset = horizontalOffset;
// We don't need to invalidate once again after UpdateHorizontalOffset.
ignoreInvalidate = true;
handled = true;
}
}
if (handled)
{
InvalidateRowsMeasure(invalidateIndividualElements: false);
if (!ignoreInvalidate)
{
InvalidateRowsMeasure(invalidateIndividualElements: false);
}
return true;
}
}
@ -2932,7 +2936,7 @@ namespace Avalonia.Controls
return SetCurrentCellCore(columnIndex, slot, commitEdit: true, endRowEdit: true);
}
internal void UpdateHorizontalOffset(double newValue)
internal bool UpdateHorizontalOffset(double newValue)
{
if (HorizontalOffset != newValue)
{
@ -2940,7 +2944,9 @@ namespace Avalonia.Controls
InvalidateColumnHeadersMeasure();
InvalidateRowsMeasure(true);
return true;
}
return false;
}
internal bool UpdateSelectionAndCurrency(int columnIndex, int slot, DataGridSelectionAction action, bool scrollIntoView)

30
src/Avalonia.Controls.DataGrid/DataGridColumnHeader.cs

@ -35,6 +35,7 @@ namespace Avalonia.Controls
private const int DATAGRIDCOLUMNHEADER_resizeRegionWidth = 5;
private const double DATAGRIDCOLUMNHEADER_separatorThickness = 1;
private const int DATAGRIDCOLUMNHEADER_columnsDragTreshold = 5;
private bool _areHandlersSuspended;
private static DragMode _dragMode;
@ -448,19 +449,6 @@ namespace Avalonia.Controls
OnMouseMove_Reorder(ref handled, mousePosition, mousePositionHeaders, distanceFromLeft, distanceFromRight);
// if we still haven't done anything about moving the mouse while
// the button is down, we remember that we're dragging, but we don't
// claim to have actually handled the event
if (_dragMode == DragMode.MouseDown)
{
_dragMode = DragMode.Drag;
}
_lastMousePositionHeaders = mousePositionHeaders;
if (args.Pointer.Captured != this && _dragMode == DragMode.Drag)
args.Pointer.Capture(this);
SetDragCursor(mousePosition);
}
@ -732,15 +720,19 @@ namespace Avalonia.Controls
{
return;
}
//handle entry into reorder mode
if (_dragMode == DragMode.MouseDown && _dragColumn == null && (distanceFromRight > DATAGRIDCOLUMNHEADER_resizeRegionWidth && distanceFromLeft > DATAGRIDCOLUMNHEADER_resizeRegionWidth))
if (_dragMode == DragMode.MouseDown && _dragColumn == null && _lastMousePositionHeaders != null && (distanceFromRight > DATAGRIDCOLUMNHEADER_resizeRegionWidth && distanceFromLeft > DATAGRIDCOLUMNHEADER_resizeRegionWidth))
{
handled = CanReorderColumn(OwningColumn);
if (handled)
var distanceFromInitial = (Vector)(mousePositionHeaders - _lastMousePositionHeaders);
if (distanceFromInitial.Length > DATAGRIDCOLUMNHEADER_columnsDragTreshold)
{
OnMouseMove_BeginReorder(mousePosition);
handled = CanReorderColumn(OwningColumn);
if (handled)
{
OnMouseMove_BeginReorder(mousePosition);
}
}
}

2
src/Avalonia.Controls/Border.cs

@ -8,7 +8,9 @@ namespace Avalonia.Controls
/// <summary>
/// A control which decorates a child with a border and background.
/// </summary>
#pragma warning disable CS0618 // Type or member is obsolete
public partial class Border : Decorator, IVisualWithRoundRectClip
#pragma warning restore CS0618 // Type or member is obsolete
{
/// <summary>
/// Defines the <see cref="Background"/> property.

10
src/Avalonia.Controls/Button.cs

@ -99,6 +99,7 @@ namespace Avalonia.Controls
CommandParameterProperty.Changed.Subscribe(CommandParameterChanged);
IsDefaultProperty.Changed.Subscribe(IsDefaultChanged);
IsCancelProperty.Changed.Subscribe(IsCancelChanged);
AccessKeyHandler.AccessKeyPressedEvent.AddClassHandler<Button>((lbl, args) => lbl.OnAccessKey(args));
}
public Button()
@ -256,6 +257,8 @@ namespace Avalonia.Controls
}
}
protected virtual void OnAccessKey(RoutedEventArgs e) => OnClick();
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
@ -358,6 +361,13 @@ namespace Avalonia.Controls
IsPressed = false;
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
IsPressed = false;
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);

15
src/Avalonia.Controls/ContextMenu.cs

@ -329,16 +329,8 @@ namespace Avalonia.Controls
{
_popup = new Popup
{
HorizontalOffset = HorizontalOffset,
VerticalOffset = VerticalOffset,
PlacementAnchor = PlacementAnchor,
PlacementConstraintAdjustment = PlacementConstraintAdjustment,
PlacementGravity = PlacementGravity,
PlacementMode = PlacementMode,
PlacementRect = PlacementRect,
IsLightDismissEnabled = true,
OverlayDismissEventPassThrough = true,
WindowManagerAddShadowHint = WindowManagerAddShadowHint,
};
_popup.Opened += PopupOpened;
@ -358,6 +350,13 @@ namespace Avalonia.Controls
: PlacementMode;
_popup.PlacementTarget = placementTarget;
_popup.HorizontalOffset = HorizontalOffset;
_popup.VerticalOffset = VerticalOffset;
_popup.PlacementAnchor = PlacementAnchor;
_popup.PlacementConstraintAdjustment = PlacementConstraintAdjustment;
_popup.PlacementGravity = PlacementGravity;
_popup.PlacementRect = PlacementRect;
_popup.WindowManagerAddShadowHint = WindowManagerAddShadowHint;
_popup.Child = this;
IsOpen = true;
_popup.IsOpen = true;

43
src/Avalonia.Controls/ItemsControl.cs

@ -21,7 +21,7 @@ namespace Avalonia.Controls
/// Displays a collection of items.
/// </summary>
[PseudoClasses(":empty", ":singleitem")]
public class ItemsControl : TemplatedControl, IItemsPresenterHost, ICollectionChangedListener
public class ItemsControl : TemplatedControl, IItemsPresenterHost, ICollectionChangedListener, IChildIndexProvider
{
/// <summary>
/// The default value for the <see cref="ItemsPanel"/> property.
@ -56,6 +56,7 @@ namespace Avalonia.Controls
private IEnumerable _items = new AvaloniaList<object>();
private int _itemCount;
private IItemContainerGenerator _itemContainerGenerator;
private EventHandler<ChildIndexChangedEventArgs> _childIndexChanged;
/// <summary>
/// Initializes static members of the <see cref="ItemsControl"/> class.
@ -145,11 +146,28 @@ namespace Avalonia.Controls
protected set;
}
event EventHandler<ChildIndexChangedEventArgs> IChildIndexProvider.ChildIndexChanged
{
add => _childIndexChanged += value;
remove => _childIndexChanged -= value;
}
/// <inheritdoc/>
void IItemsPresenterHost.RegisterItemsPresenter(IItemsPresenter presenter)
{
if (Presenter is IChildIndexProvider oldInnerProvider)
{
oldInnerProvider.ChildIndexChanged -= PresenterChildIndexChanged;
}
Presenter = presenter;
ItemContainerGenerator.Clear();
if (Presenter is IChildIndexProvider innerProvider)
{
innerProvider.ChildIndexChanged += PresenterChildIndexChanged;
_childIndexChanged?.Invoke(this, new ChildIndexChangedEventArgs());
}
}
void ICollectionChangedListener.PreChanged(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e)
@ -506,5 +524,28 @@ namespace Avalonia.Controls
return null;
}
private void PresenterChildIndexChanged(object sender, ChildIndexChangedEventArgs e)
{
_childIndexChanged?.Invoke(this, e);
}
int IChildIndexProvider.GetChildIndex(ILogical child)
{
return Presenter is IChildIndexProvider innerProvider
? innerProvider.GetChildIndex(child) : -1;
}
bool IChildIndexProvider.TryGetTotalCount(out int count)
{
if (Presenter is IChildIndexProvider presenter
&& presenter.TryGetTotalCount(out count))
{
return true;
}
count = ItemCount;
return true;
}
}
}

3
src/Avalonia.Controls/NativeMenuItem.cs

@ -16,6 +16,7 @@ namespace Avalonia.Controls
private bool _isChecked = false;
private NativeMenuItemToggleType _toggleType;
private IBitmap _icon;
private readonly CanExecuteChangedSubscriber _canExecuteChangedSubscriber;
private NativeMenu _menu;
@ -47,8 +48,6 @@ namespace Avalonia.Controls
}
}
private readonly CanExecuteChangedSubscriber _canExecuteChangedSubscriber;
public NativeMenuItem()
{

2
src/Avalonia.Controls/NumericUpDown/NumericUpDown.cs

@ -332,7 +332,9 @@ namespace Avalonia.Controls
/// </summary>
static NumericUpDown()
{
#pragma warning disable CS0612 // Type or member is obsolete
CultureInfoProperty.Changed.Subscribe(OnCultureInfoChanged);
#pragma warning restore CS0612 // Type or member is obsolete
NumberFormatProperty.Changed.Subscribe(OnNumberFormatChanged);
FormatStringProperty.Changed.Subscribe(FormatStringChanged);
IncrementProperty.Changed.Subscribe(IncrementChanged);

24
src/Avalonia.Controls/Panel.cs

@ -2,8 +2,10 @@ using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Metadata;
using Avalonia.Styling;
namespace Avalonia.Controls
{
@ -14,7 +16,7 @@ namespace Avalonia.Controls
/// Controls can be added to a <see cref="Panel"/> by adding them to its <see cref="Children"/>
/// collection. All children are layed out to fill the panel.
/// </remarks>
public class Panel : Control, IPanel
public class Panel : Control, IPanel, IChildIndexProvider
{
/// <summary>
/// Defines the <see cref="Background"/> property.
@ -30,6 +32,8 @@ namespace Avalonia.Controls
AffectsRender<Panel>(BackgroundProperty);
}
private EventHandler<ChildIndexChangedEventArgs> _childIndexChanged;
/// <summary>
/// Initializes a new instance of the <see cref="Panel"/> class.
/// </summary>
@ -53,6 +57,12 @@ namespace Avalonia.Controls
set { SetValue(BackgroundProperty, value); }
}
event EventHandler<ChildIndexChangedEventArgs> IChildIndexProvider.ChildIndexChanged
{
add => _childIndexChanged += value;
remove => _childIndexChanged -= value;
}
/// <summary>
/// Renders the visual to a <see cref="DrawingContext"/>.
/// </summary>
@ -137,6 +147,7 @@ namespace Avalonia.Controls
throw new NotSupportedException();
}
_childIndexChanged?.Invoke(this, new ChildIndexChangedEventArgs());
InvalidateMeasureOnChildrenChanged();
}
@ -160,5 +171,16 @@ namespace Avalonia.Controls
var panel = control?.VisualParent as TPanel;
panel?.InvalidateMeasure();
}
int IChildIndexProvider.GetChildIndex(ILogical child)
{
return child is IControl control ? Children.IndexOf(control) : -1;
}
public bool TryGetTotalCount(out int count)
{
count = Children.Count;
return true;
}
}
}

41
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.LogicalTree;
using Avalonia.Styling;
namespace Avalonia.Controls.Presenters
@ -12,7 +13,7 @@ namespace Avalonia.Controls.Presenters
/// <summary>
/// Base class for controls that present items inside an <see cref="ItemsControl"/>.
/// </summary>
public abstract class ItemsPresenterBase : Control, IItemsPresenter, ITemplatedControl
public abstract class ItemsPresenterBase : Control, IItemsPresenter, ITemplatedControl, IChildIndexProvider
{
/// <summary>
/// Defines the <see cref="Items"/> property.
@ -36,6 +37,7 @@ namespace Avalonia.Controls.Presenters
private IDisposable _itemsSubscription;
private bool _createdPanel;
private IItemContainerGenerator _generator;
private EventHandler<ChildIndexChangedEventArgs> _childIndexChanged;
/// <summary>
/// Initializes static members of the <see cref="ItemsPresenter"/> class.
@ -129,6 +131,12 @@ namespace Avalonia.Controls.Presenters
protected bool IsHosted => TemplatedParent is IItemsPresenterHost;
event EventHandler<ChildIndexChangedEventArgs> IChildIndexProvider.ChildIndexChanged
{
add => _childIndexChanged += value;
remove => _childIndexChanged -= value;
}
/// <inheritdoc/>
public override sealed void ApplyTemplate()
{
@ -149,6 +157,8 @@ namespace Avalonia.Controls.Presenters
if (Panel != null)
{
ItemsChanged(e);
_childIndexChanged?.Invoke(this, new ChildIndexChangedEventArgs());
}
}
@ -169,9 +179,21 @@ namespace Avalonia.Controls.Presenters
result.ItemTemplate = ItemTemplate;
}
result.Materialized += ContainerActionHandler;
result.Dematerialized += ContainerActionHandler;
result.Recycled += ContainerActionHandler;
return result;
}
private void ContainerActionHandler(object sender, ItemContainerEventArgs e)
{
for (var i = 0; i < e.Containers.Count; i++)
{
_childIndexChanged?.Invoke(this, new ChildIndexChangedEventArgs(e.Containers[i].ContainerControl));
}
}
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
@ -248,5 +270,22 @@ namespace Avalonia.Controls.Presenters
{
(e.NewValue as IItemsPresenterHost)?.RegisterItemsPresenter(this);
}
int IChildIndexProvider.GetChildIndex(ILogical child)
{
if (child is IControl control && ItemContainerGenerator is { } generator)
{
var index = ItemContainerGenerator.IndexFromContainer(control);
return index;
}
return -1;
}
bool IChildIndexProvider.TryGetTotalCount(out int count)
{
return Items.TryGetCountFast(out count);
}
}
}

2
src/Avalonia.Controls/Primitives/AccessText.cs

@ -68,7 +68,7 @@ namespace Avalonia.Controls.Primitives
if (underscore != -1 && ShowAccessKey)
{
var rect = TextLayout.HitTestTextPosition(underscore);
var offset = new Vector(0, -0.5);
var offset = new Vector(0, -1.5);
context.DrawLine(
new Pen(Foreground, 1),
rect.BottomLeft + offset,

2
src/Avalonia.Controls/Primitives/Popup.cs

@ -20,7 +20,9 @@ namespace Avalonia.Controls.Primitives
/// <summary>
/// Displays a popup window.
/// </summary>
#pragma warning disable CS0612 // Type or member is obsolete
public class Popup : Control, IVisualTreeHost, IPopupHostProvider
#pragma warning restore CS0612 // Type or member is obsolete
{
public static readonly StyledProperty<bool> WindowManagerAddShadowHintProperty =
AvaloniaProperty.Register<PopupRoot, bool>(nameof(WindowManagerAddShadowHint), false);

4
src/Avalonia.Controls/Primitives/PopupPositioning/IPopupPositioner.cs

@ -447,8 +447,10 @@ namespace Avalonia.Controls.Primitives.PopupPositioning
PopupPositionerConstraintAdjustment constraintAdjustment, Rect? rect)
{
// We need a better way for tracking the last pointer position
#pragma warning disable CS0618 // Type or member is obsolete
var pointer = topLevel.PointToClient(topLevel.PlatformImpl.MouseDevice.Position);
#pragma warning restore CS0618 // Type or member is obsolete
positionerParameters.Offset = offset;
positionerParameters.ConstraintAdjustment = constraintAdjustment;
if (placement == PlacementMode.Pointer)

3
src/Avalonia.Controls/ProgressBar.cs

@ -218,9 +218,12 @@ namespace Avalonia.Controls
TemplateProperties.Container2AnimationStartPosition = barIndicatorWidth2 * -1.5; // Position at -150%
TemplateProperties.Container2AnimationEndPosition = barIndicatorWidth2 * 1.66; // Position at 166%
#pragma warning disable CS0618 // Type or member is obsolete
// Remove these properties when we switch to fluent as default and removed the old one.
IndeterminateStartingOffset = -dim;
IndeterminateEndingOffset = dim;
#pragma warning restore CS0618 // Type or member is obsolete
var padding = Padding;
var rectangle = new RectangleGeometry(

2
src/Avalonia.Controls/Remote/RemoteWidget.cs

@ -77,8 +77,10 @@ namespace Avalonia.Controls.Remote
_bitmap.PixelSize.Height != _lastFrame.Height)
{
_bitmap?.Dispose();
#pragma warning disable CS0618 // Type or member is obsolete
_bitmap = new WriteableBitmap(new PixelSize(_lastFrame.Width, _lastFrame.Height),
new Vector(96, 96), fmt);
#pragma warning restore CS0618 // Type or member is obsolete
}
using (var l = _bitmap.Lock())
{

10
src/Avalonia.Controls/RepeatButton.cs

@ -70,6 +70,16 @@ namespace Avalonia.Controls
_repeatTimer?.Stop();
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == IsPressedProperty && change.NewValue.GetValueOrDefault<bool>() == false)
{
StopTimer();
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);

31
src/Avalonia.Controls/Repeater/ItemsRepeater.cs

@ -10,6 +10,7 @@ using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Logging;
using Avalonia.LogicalTree;
using Avalonia.Utilities;
using Avalonia.VisualTree;
@ -19,7 +20,7 @@ namespace Avalonia.Controls
/// Represents a data-driven collection control that incorporates a flexible layout system,
/// custom views, and virtualization.
/// </summary>
public class ItemsRepeater : Panel
public class ItemsRepeater : Panel, IChildIndexProvider
{
/// <summary>
/// Defines the <see cref="HorizontalCacheLength"/> property.
@ -61,8 +62,9 @@ namespace Avalonia.Controls
private readonly ViewportManager _viewportManager;
private IEnumerable _items;
private VirtualizingLayoutContext _layoutContext;
private NotifyCollectionChangedEventArgs _processingItemsSourceChange;
private EventHandler<ChildIndexChangedEventArgs> _childIndexChanged;
private bool _isLayoutInProgress;
private NotifyCollectionChangedEventArgs _processingItemsSourceChange;
private ItemsRepeaterElementPreparedEventArgs _elementPreparedArgs;
private ItemsRepeaterElementClearingEventArgs _elementClearingArgs;
private ItemsRepeaterElementIndexChangedEventArgs _elementIndexChangedArgs;
@ -163,6 +165,25 @@ namespace Avalonia.Controls
}
}
event EventHandler<ChildIndexChangedEventArgs> IChildIndexProvider.ChildIndexChanged
{
add => _childIndexChanged += value;
remove => _childIndexChanged -= value;
}
int IChildIndexProvider.GetChildIndex(ILogical child)
{
return child is IControl control
? GetElementIndex(control)
: -1;
}
bool IChildIndexProvider.TryGetTotalCount(out int count)
{
count = ItemsSourceView.Count;
return true;
}
/// <summary>
/// Occurs each time an element is cleared and made available to be re-used.
/// </summary>
@ -545,6 +566,8 @@ namespace Avalonia.Controls
ElementPrepared(this, _elementPreparedArgs);
}
_childIndexChanged?.Invoke(this, new ChildIndexChangedEventArgs(element));
}
internal void OnElementClearing(IControl element)
@ -562,6 +585,8 @@ namespace Avalonia.Controls
ElementClearing(this, _elementClearingArgs);
}
_childIndexChanged?.Invoke(this, new ChildIndexChangedEventArgs(element));
}
internal void OnElementIndexChanged(IControl element, int oldIndex, int newIndex)
@ -579,6 +604,8 @@ namespace Avalonia.Controls
ElementIndexChanged(this, _elementIndexChangedArgs);
}
_childIndexChanged?.Invoke(this, new ChildIndexChangedEventArgs(element));
}
private void OnDataSourcePropertyChanged(ItemsSourceView oldValue, ItemsSourceView newValue)

2
src/Avalonia.Controls/TextBox.cs

@ -991,7 +991,9 @@ namespace Avalonia.Controls
{
var point = e.GetPosition(_presenter);
var index = CaretIndex = _presenter.GetCaretIndex(point);
#pragma warning disable CS0618 // Type or member is obsolete
switch (e.ClickCount)
#pragma warning restore CS0618 // Type or member is obsolete
{
case 1:
SelectionStart = SelectionEnd = index;

49
src/Avalonia.Controls/TrayIcon.cs

@ -1,10 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia.Collections;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Controls.Platform;
using Avalonia.Platform;
using Avalonia.Utilities;
#nullable enable
@ -13,10 +15,13 @@ namespace Avalonia.Controls
public sealed class TrayIcons : AvaloniaList<TrayIcon>
{
}
public class TrayIcon : AvaloniaObject, INativeMenuExporterProvider, IDisposable
{
private readonly ITrayIconImpl? _impl;
private ICommand? _command;
private TrayIcon(ITrayIconImpl? impl)
{
@ -26,7 +31,15 @@ namespace Avalonia.Controls
_impl.SetIsVisible(IsVisible);
_impl.OnClicked = () => Clicked?.Invoke(this, EventArgs.Empty);
_impl.OnClicked = () =>
{
Clicked?.Invoke(this, EventArgs.Empty);
if (Command?.CanExecute(CommandParameter) == true)
{
Command.Execute(CommandParameter);
}
};
}
}
@ -64,6 +77,21 @@ namespace Avalonia.Controls
/// on OSX this event is not raised.
/// </summary>
public event EventHandler? Clicked;
/// <summary>
/// Defines the <see cref="Command"/> property.
/// </summary>
public static readonly DirectProperty<TrayIcon, ICommand?> CommandProperty =
Button.CommandProperty.AddOwner<TrayIcon>(
trayIcon => trayIcon.Command,
(trayIcon, command) => trayIcon.Command = command,
enableDataValidation: true);
/// <summary>
/// Defines the <see cref="CommandParameter"/> property.
/// </summary>
public static readonly StyledProperty<object?> CommandParameterProperty =
Button.CommandParameterProperty.AddOwner<MenuItem>();
/// <summary>
/// Defines the <see cref="TrayIcons"/> attached property.
@ -98,6 +126,25 @@ namespace Avalonia.Controls
public static void SetIcons(AvaloniaObject o, TrayIcons trayIcons) => o.SetValue(IconsProperty, trayIcons);
public static TrayIcons GetIcons(AvaloniaObject o) => o.GetValue(IconsProperty);
/// <summary>
/// Gets or sets the <see cref="Command"/> property of a TrayIcon.
/// </summary>
public ICommand? Command
{
get => _command;
set => SetAndRaise(CommandProperty, ref _command, value);
}
/// <summary>
/// Gets or sets the parameter to pass to the <see cref="Command"/> property of a
/// <see cref="TrayIcon"/>.
/// </summary>
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
/// <summary>
/// Gets or sets the Menu of the TrayIcon.

27
src/Avalonia.Controls/Utils/IEnumerableUtils.cs

@ -12,23 +12,36 @@ namespace Avalonia.Controls.Utils
return items.IndexOf(item) != -1;
}
public static int Count(this IEnumerable items)
public static bool TryGetCountFast(this IEnumerable items, out int count)
{
if (items != null)
{
if (items is ICollection collection)
{
return collection.Count;
count = collection.Count;
return true;
}
else if (items is IReadOnlyCollection<object> readOnly)
{
return readOnly.Count;
}
else
{
return Enumerable.Count(items.Cast<object>());
count = readOnly.Count;
return true;
}
}
count = 0;
return false;
}
public static int Count(this IEnumerable items)
{
if (TryGetCountFast(items, out var count))
{
return count;
}
else if (items != null)
{
return Enumerable.Count(items.Cast<object>());
}
else
{
return 0;

2
src/Avalonia.Diagnostics/Diagnostics/Models/EventChainLink.cs

@ -29,7 +29,7 @@ namespace Avalonia.Diagnostics.Models
}
}
public bool Handled { get; }
public bool Handled { get; set; }
public RoutingStrategies Route { get; }
}

26
src/Avalonia.Diagnostics/Diagnostics/ViewModels/EventTreeNode.cs

@ -55,6 +55,8 @@ namespace Avalonia.Diagnostics.ViewModels
// FIXME: This leaks event handlers.
Event.AddClassHandler(typeof(object), HandleEvent, allRoutes, handledEventsToo: true);
Event.RouteFinished.Subscribe(HandleRouteFinished);
_isRegistered = true;
}
}
@ -92,6 +94,30 @@ namespace Avalonia.Diagnostics.ViewModels
else
handler();
}
private void HandleRouteFinished(RoutedEventArgs e)
{
if (!_isRegistered || IsEnabled == false)
return;
if (e.Source is IVisual v && BelongsToDevTool(v))
return;
var s = e.Source;
var handled = e.Handled;
var route = e.Route;
void handler()
{
if (_currentEvent != null && handled)
{
var linkIndex = _currentEvent.EventChain.Count - 1;
var link = _currentEvent.EventChain[linkIndex];
link.Handled = true;
_currentEvent.HandledBy = link;
}
}
}
private static bool BelongsToDevTool(IVisual v)
{

5
src/Avalonia.Diagnostics/Diagnostics/ViewModels/FiredEvent.cs

@ -63,8 +63,8 @@ namespace Avalonia.Diagnostics.ViewModels
{
if (EventChain.Count > 0)
{
var prevLink = EventChain[EventChain.Count-1];
var prevLink = EventChain[EventChain.Count - 1];
if (prevLink.Route != link.Route)
{
link.BeginsNewRoute = true;
@ -72,6 +72,7 @@ namespace Avalonia.Diagnostics.ViewModels
}
EventChain.Add(link);
if (HandledBy == null && link.Handled)
HandledBy = link;
}

6
src/Avalonia.FreeDesktop/DBusHelper.cs

@ -12,7 +12,7 @@ namespace Avalonia.FreeDesktop
/// This class uses synchronous execution at DBus connection establishment stage
/// then switches to using AvaloniaSynchronizationContext
/// </summary>
class DBusSyncContext : SynchronizationContext
private class DBusSyncContext : SynchronizationContext
{
private SynchronizationContext _ctx;
private object _lock = new object();
@ -51,10 +51,10 @@ namespace Avalonia.FreeDesktop
public static Connection TryInitialize(string dbusAddress = null)
{
return Connection ?? TryGetConnection(dbusAddress);
return Connection ?? TryCreateNewConnection(dbusAddress);
}
public static Connection TryGetConnection(string dbusAddress = null)
public static Connection TryCreateNewConnection(string dbusAddress = null)
{
var oldContext = SynchronizationContext.Current;
try

178
src/Avalonia.X11/X11TrayIconImpl.cs → src/Avalonia.FreeDesktop/DBusTrayIconImpl.cs

@ -6,55 +6,65 @@ using System.Reactive.Disposables;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Avalonia.Controls.Platform;
using Avalonia.FreeDesktop;
using Avalonia.Logging;
using Avalonia.Platform;
using Tmds.DBus;
[assembly: InternalsVisibleTo(Connection.DynamicAssemblyName)]
namespace Avalonia.X11
[assembly:
InternalsVisibleTo(
"Avalonia.X11, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c1bba1142285fe0419326fb25866ba62c47e6c2b5c1ab0c95b46413fad375471232cb81706932e1cef38781b9ebd39d5100401bacb651c6c5bbf59e571e81b3bc08d2a622004e08b1a6ece82a7e0b9857525c86d2b95fab4bc3dce148558d7f3ae61aa3a234086902aeface87d9dfdd32b9d2fe3c6dd4055b5ab4b104998bd87")]
namespace Avalonia.FreeDesktop
{
internal class X11TrayIconImpl : ITrayIconImpl
internal class DBusTrayIconImpl : ITrayIconImpl
{
private static int s_trayIconInstanceId;
private readonly ObjectPath _dbusMenuPath;
private StatusNotifierItemDbusObj? _statusNotifierItemDbusObj;
private readonly Connection? _connection;
private DbusPixmap _icon;
private IDisposable? _serviceWatchDisposable;
private StatusNotifierItemDbusObj? _statusNotifierItemDbusObj;
private IStatusNotifierWatcher? _statusNotifierWatcher;
private DbusPixmap _icon;
private string? _sysTrayServiceName;
private string? _tooltipText;
private bool _isActive;
private bool _isDisposed;
private readonly bool _ctorFinished;
private bool _serviceConnected;
private bool _isVisible = true;
public bool IsActive { get; private set; }
public INativeMenuExporter? MenuExporter { get; }
public Action? OnClicked { get; set; }
public Func<IWindowIconImpl?, uint[]>? IconConverterDelegate { get; set; }
public X11TrayIconImpl()
public DBusTrayIconImpl()
{
_connection = DBusHelper.TryGetConnection();
_connection = DBusHelper.TryCreateNewConnection();
if (_connection is null)
{
Logger.TryGet(LogEventLevel.Error, LogArea.X11Platform)
Logger.TryGet(LogEventLevel.Error, "DBUS")
?.Log(this, "Unable to get a dbus connection for system tray icons.");
return;
}
IsActive = true;
_dbusMenuPath = DBusMenuExporter.GenerateDBusMenuObjPath;
MenuExporter = DBusMenuExporter.TryCreateDetachedNativeMenu(_dbusMenuPath, _connection);
CreateTrayIcon();
_ctorFinished = true;
WatchAsync();
}
public async void CreateTrayIcon()
private void InitializeSNWService()
{
if (_connection is null)
return;
if (_connection is null || _isDisposed) return;
try
{
@ -64,12 +74,58 @@ namespace Avalonia.X11
}
catch
{
Logger.TryGet(LogEventLevel.Error, LogArea.X11Platform)
Logger.TryGet(LogEventLevel.Error, "DBUS")
?.Log(this,
"org.kde.StatusNotifierWatcher service is not available on this system. Tray Icons will not work without it.");
return;
}
_serviceConnected = true;
}
private async void WatchAsync()
{
try
{
_serviceWatchDisposable =
await _connection?.ResolveServiceOwnerAsync("org.kde.StatusNotifierWatcher", OnNameChange)!;
}
catch (Exception e)
{
Logger.TryGet(LogEventLevel.Error, "DBUS")
?.Log(this,
"DBUS: org.kde.StatusNotifierWatcher service is not available on this system. System Tray Icons will not work without it.");
$"Unable to hook watcher method on org.kde.StatusNotifierWatcher: {e}");
}
}
if (_statusNotifierWatcher is null)
private void OnNameChange(ServiceOwnerChangedEventArgs obj)
{
if (_isDisposed)
return;
if (!_serviceConnected & obj.NewOwner != null)
{
_serviceConnected = true;
InitializeSNWService();
DestroyTrayIcon();
if (_isVisible)
{
CreateTrayIcon();
}
}
else if (_serviceConnected & obj.NewOwner is null)
{
DestroyTrayIcon();
_serviceConnected = false;
}
}
private void CreateTrayIcon()
{
if (_connection is null || !_serviceConnected || _isDisposed)
return;
var pid = Process.GetCurrentProcess().Id;
@ -78,45 +134,61 @@ namespace Avalonia.X11
_sysTrayServiceName = $"org.kde.StatusNotifierItem-{pid}-{tid}";
_statusNotifierItemDbusObj = new StatusNotifierItemDbusObj(_dbusMenuPath);
await _connection.RegisterObjectAsync(_statusNotifierItemDbusObj);
await _connection.RegisterServiceAsync(_sysTrayServiceName);
try
{
_connection.RegisterObjectAsync(_statusNotifierItemDbusObj);
_connection.RegisterServiceAsync(_sysTrayServiceName);
_statusNotifierWatcher?.RegisterStatusNotifierItemAsync(_sysTrayServiceName);
}
catch (Exception e)
{
Logger.TryGet(LogEventLevel.Error, "DBUS")
?.Log(this, $"Error creating a DBus tray icon: {e}.");
await _statusNotifierWatcher.RegisterStatusNotifierItemAsync(_sysTrayServiceName);
_serviceConnected = false;
}
_statusNotifierItemDbusObj.SetTitleAndTooltip(_tooltipText);
_statusNotifierItemDbusObj.SetIcon(_icon);
_statusNotifierItemDbusObj.ActivationDelegate += OnClicked;
_isActive = true;
}
public async void DestroyTrayIcon()
private void DestroyTrayIcon()
{
if (_connection is null)
if (_connection is null || !_serviceConnected || _isDisposed || _statusNotifierItemDbusObj is null)
return;
_connection.UnregisterObject(_statusNotifierItemDbusObj);
await _connection.UnregisterServiceAsync(_sysTrayServiceName);
_isActive = false;
_connection.UnregisterServiceAsync(_sysTrayServiceName);
}
public void Dispose()
{
IsActive = false;
_isDisposed = true;
DestroyTrayIcon();
_connection?.Dispose();
_serviceWatchDisposable?.Dispose();
}
public void SetIcon(IWindowIconImpl? icon)
{
if (_isDisposed)
if (_isDisposed || IconConverterDelegate is null)
return;
if (!(icon is X11IconData x11icon))
if (icon is null)
{
_statusNotifierItemDbusObj?.SetIcon(DbusPixmap.EmptyPixmap);
return;
}
var x11iconData = IconConverterDelegate(icon);
if (x11iconData.Length == 0) return;
var w = (int)x11icon.Data[0];
var h = (int)x11icon.Data[1];
var w = (int)x11iconData[0];
var h = (int)x11iconData[1];
var pixLength = w * h;
var pixByteArrayCounter = 0;
@ -124,7 +196,7 @@ namespace Avalonia.X11
for (var i = 0; i < pixLength; i++)
{
var rawPixel = x11icon.Data[i + 2].ToUInt32();
var rawPixel = x11iconData[i + 2];
pixByteArray[pixByteArrayCounter++] = (byte)((rawPixel & 0xFF000000) >> 24);
pixByteArray[pixByteArrayCounter++] = (byte)((rawPixel & 0xFF0000) >> 16);
pixByteArray[pixByteArrayCounter++] = (byte)((rawPixel & 0xFF00) >> 8);
@ -137,18 +209,21 @@ namespace Avalonia.X11
public void SetIsVisible(bool visible)
{
if (_isDisposed || !_ctorFinished)
if (_isDisposed)
return;
if (visible & !_isActive)
{
DestroyTrayIcon();
CreateTrayIcon();
}
else if (!visible & _isActive)
switch (visible)
{
DestroyTrayIcon();
case true when !_isVisible:
DestroyTrayIcon();
CreateTrayIcon();
break;
case false when _isVisible:
DestroyTrayIcon();
break;
}
_isVisible = visible;
}
public void SetToolTipText(string? text)
@ -248,7 +323,20 @@ namespace Avalonia.X11
return Task.FromResult(Disposable.Create(() => NewStatusAsync -= handler));
}
public Task<object> GetAsync(string prop) => Task.FromResult(new object());
public Task<object?> GetAsync(string prop)
{
return Task.FromResult<object?>(prop switch
{
nameof(_backingProperties.Category) => _backingProperties.Category,
nameof(_backingProperties.Id) => _backingProperties.Id,
nameof(_backingProperties.Menu) => _backingProperties.Menu,
nameof(_backingProperties.IconPixmap) => _backingProperties.IconPixmap,
nameof(_backingProperties.Status) => _backingProperties.Status,
nameof(_backingProperties.Title) => _backingProperties.Title,
nameof(_backingProperties.ToolTip) => _backingProperties.ToolTip,
_ => null
});
}
public Task<StatusNotifierItemProperties> GetAllAsync() => Task.FromResult(_backingProperties);
@ -298,17 +386,17 @@ namespace Avalonia.X11
Task<IDisposable> WatchNewOverlayIconAsync(Action handler, Action<Exception> onError);
Task<IDisposable> WatchNewToolTipAsync(Action handler, Action<Exception> onError);
Task<IDisposable> WatchNewStatusAsync(Action<string> handler, Action<Exception> onError);
Task<object> GetAsync(string prop);
Task<object?> GetAsync(string prop);
Task<StatusNotifierItemProperties> GetAllAsync();
Task SetAsync(string prop, object val);
Task<IDisposable> WatchPropertiesAsync(Action<PropertyChanges> handler);
}
[Dictionary]
// This class is used by Tmds.Dbus to ferry properties
// from the SNI spec.
// Don't change this to actual C# properties since
// Tmds.Dbus will get confused.
[Dictionary]
internal class StatusNotifierItemProperties
{
public string? Category;
@ -363,5 +451,7 @@ namespace Avalonia.X11
Height = height;
Data = data;
}
public static DbusPixmap EmptyPixmap = new DbusPixmap(1, 1, new byte[] { 255, 0, 0, 0 });
}
}

26
src/Avalonia.Styling/LogicalTree/ChildIndexChangedEventArgs.cs

@ -0,0 +1,26 @@
#nullable enable
using System;
namespace Avalonia.LogicalTree
{
/// <summary>
/// Event args for <see cref="IChildIndexProvider.ChildIndexChanged"/> event.
/// </summary>
public class ChildIndexChangedEventArgs : EventArgs
{
public ChildIndexChangedEventArgs()
{
}
public ChildIndexChangedEventArgs(ILogical child)
{
Child = child;
}
/// <summary>
/// Logical child which index was changed.
/// If null, all children should be reset.
/// </summary>
public ILogical? Child { get; }
}
}

32
src/Avalonia.Styling/LogicalTree/IChildIndexProvider.cs

@ -0,0 +1,32 @@
#nullable enable
using System;
namespace Avalonia.LogicalTree
{
/// <summary>
/// Child's index and total count information provider used by list-controls (ListBox, StackPanel, etc.)
/// </summary>
/// <remarks>
/// Used by nth-child and nth-last-child selectors.
/// </remarks>
public interface IChildIndexProvider
{
/// <summary>
/// Gets child's actual index in order of the original source.
/// </summary>
/// <param name="child">Logical child.</param>
/// <returns>Index or -1 if child was not found.</returns>
int GetChildIndex(ILogical child);
/// <summary>
/// Total children count or null if source is infinite.
/// Some Avalonia features might not work if <see cref="TryGetTotalCount"/> returns false, for instance: nth-last-child selector.
/// </summary>
bool TryGetTotalCount(out int count);
/// <summary>
/// Notifies subscriber when child's index or total count was changed.
/// </summary>
event EventHandler<ChildIndexChangedEventArgs>? ChildIndexChanged;
}
}

56
src/Avalonia.Styling/Styling/Activators/NthChildActivator.cs

@ -0,0 +1,56 @@
#nullable enable
using Avalonia.LogicalTree;
namespace Avalonia.Styling.Activators
{
/// <summary>
/// An <see cref="IStyleActivator"/> which is active when control's index was changed.
/// </summary>
internal sealed class NthChildActivator : StyleActivatorBase
{
private readonly ILogical _control;
private readonly IChildIndexProvider _provider;
private readonly int _step;
private readonly int _offset;
private readonly bool _reversed;
public NthChildActivator(
ILogical control,
IChildIndexProvider provider,
int step, int offset, bool reversed)
{
_control = control;
_provider = provider;
_step = step;
_offset = offset;
_reversed = reversed;
}
protected override void Initialize()
{
PublishNext(IsMatching());
_provider.ChildIndexChanged += ChildIndexChanged;
}
protected override void Deinitialize()
{
_provider.ChildIndexChanged -= ChildIndexChanged;
}
private void ChildIndexChanged(object sender, ChildIndexChangedEventArgs e)
{
// Run matching again if:
// 1. Selector is reversed, so other item insertion/deletion might affect total count without changing subscribed item index.
// 2. e.Child is null, when all children indeces were changed.
// 3. Subscribed child index was changed.
if (_reversed
|| e.Child is null
|| e.Child == _control)
{
PublishNext(IsMatching());
}
}
private bool IsMatching() => NthChildSelector.Evaluate(_control, _provider, _step, _offset, _reversed).IsMatch;
}
}

145
src/Avalonia.Styling/Styling/NthChildSelector.cs

@ -0,0 +1,145 @@
#nullable enable
using System;
using System.Text;
using Avalonia.LogicalTree;
using Avalonia.Styling.Activators;
namespace Avalonia.Styling
{
/// <summary>
/// The :nth-child() pseudo-class matches elements based on their position in a group of siblings.
/// </summary>
/// <remarks>
/// Element indices are 1-based.
/// </remarks>
public class NthChildSelector : Selector
{
private const string NthChildSelectorName = "nth-child";
private const string NthLastChildSelectorName = "nth-last-child";
private readonly Selector? _previous;
private readonly bool _reversed;
internal protected NthChildSelector(Selector? previous, int step, int offset, bool reversed)
{
_previous = previous;
Step = step;
Offset = offset;
_reversed = reversed;
}
/// <summary>
/// Creates an instance of <see cref="NthChildSelector"/>
/// </summary>
/// <param name="previous">Previous selector.</param>
/// <param name="step">Position step.</param>
/// <param name="offset">Initial index offset.</param>
public NthChildSelector(Selector? previous, int step, int offset)
: this(previous, step, offset, false)
{
}
public override bool InTemplate => _previous?.InTemplate ?? false;
public override bool IsCombinator => false;
public override Type? TargetType => _previous?.TargetType;
public int Step { get; }
public int Offset { get; }
protected override SelectorMatch Evaluate(IStyleable control, bool subscribe)
{
if (!(control is ILogical logical))
{
return SelectorMatch.NeverThisType;
}
var controlParent = logical.LogicalParent;
if (controlParent is IChildIndexProvider childIndexProvider)
{
return subscribe
? new SelectorMatch(new NthChildActivator(logical, childIndexProvider, Step, Offset, _reversed))
: Evaluate(logical, childIndexProvider, Step, Offset, _reversed);
}
else
{
return SelectorMatch.NeverThisInstance;
}
}
internal static SelectorMatch Evaluate(
ILogical logical, IChildIndexProvider childIndexProvider,
int step, int offset, bool reversed)
{
var index = childIndexProvider.GetChildIndex(logical);
if (index < 0)
{
return SelectorMatch.NeverThisInstance;
}
if (reversed)
{
if (childIndexProvider.TryGetTotalCount(out var totalCountValue))
{
index = totalCountValue - index;
}
else
{
return SelectorMatch.NeverThisInstance;
}
}
else
{
// nth child index is 1-based
index += 1;
}
var n = Math.Sign(step);
var diff = index - offset;
var match = diff == 0 || (Math.Sign(diff) == n && diff % step == 0);
return match ? SelectorMatch.AlwaysThisInstance : SelectorMatch.NeverThisInstance;
}
protected override Selector? MovePrevious() => _previous;
public override string ToString()
{
var expectedCapacity = NthLastChildSelectorName.Length + 8;
var stringBuilder = new StringBuilder(_previous?.ToString(), expectedCapacity);
stringBuilder.Append(':');
stringBuilder.Append(_reversed ? NthLastChildSelectorName : NthChildSelectorName);
stringBuilder.Append('(');
var hasStep = false;
if (Step != 0)
{
hasStep = true;
stringBuilder.Append(Step);
stringBuilder.Append('n');
}
if (Offset > 0)
{
if (hasStep)
{
stringBuilder.Append('+');
}
stringBuilder.Append(Offset);
}
else if (Offset < 0)
{
stringBuilder.Append('-');
stringBuilder.Append(-Offset);
}
stringBuilder.Append(')');
return stringBuilder.ToString();
}
}
}

23
src/Avalonia.Styling/Styling/NthLastChildSelector.cs

@ -0,0 +1,23 @@
#nullable enable
namespace Avalonia.Styling
{
/// <summary>
/// The :nth-child() pseudo-class matches elements based on their position among a group of siblings, counting from the end.
/// </summary>
/// <remarks>
/// Element indices are 1-based.
/// </remarks>
public class NthLastChildSelector : NthChildSelector
{
/// <summary>
/// Creates an instance of <see cref="NthLastChildSelector"/>
/// </summary>
/// <param name="previous">Previous selector.</param>
/// <param name="step">Position step.</param>
/// <param name="offset">Initial index offset, counting from the end.</param>
public NthLastChildSelector(Selector? previous, int step, int offset) : base(previous, step, offset, true)
{
}
}
}

16
src/Avalonia.Styling/Styling/Selectors.cs

@ -123,6 +123,22 @@ namespace Avalonia.Styling
return new NotSelector(previous, argument);
}
/// <inheritdoc cref="NthChildSelector"/>
/// <inheritdoc cref="NthChildSelector(Selector?, int, int)"/>
/// <returns>The selector.</returns>
public static Selector NthChild(this Selector previous, int step, int offset)
{
return new NthChildSelector(previous, step, offset);
}
/// <inheritdoc cref="NthLastChildSelector"/>
/// <inheritdoc cref="NthLastChildSelector(Selector?, int, int)"/>
/// <returns>The selector.</returns>
public static Selector NthLastChild(this Selector previous, int step, int offset)
{
return new NthLastChildSelector(previous, step, offset);
}
/// <summary>
/// Returns a selector which matches a type.
/// </summary>

3
src/Avalonia.Themes.Default/AutoCompleteBox.xaml

@ -21,7 +21,8 @@
MaxHeight="{TemplateBinding MaxDropDownHeight}"
PlacementTarget="{TemplateBinding}"
IsLightDismissEnabled="True">
<Border BorderBrush="{DynamicResource ThemeBorderMidBrush}"
<Border Background="{DynamicResource ThemeBackgroundBrush}"
BorderBrush="{DynamicResource ThemeBorderMidBrush}"
BorderThickness="1">
<ListBox Name="PART_SelectingItemsControl"
BorderThickness="0"

1
src/Avalonia.Themes.Default/Button.xaml

@ -17,6 +17,7 @@
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}"
Padding="{TemplateBinding Padding}"
RecognizesAccessKey="True"
TextBlock.Foreground="{TemplateBinding Foreground}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>

1
src/Avalonia.Themes.Default/CheckBox.xaml

@ -41,6 +41,7 @@
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}"
Margin="{TemplateBinding Padding}"
RecognizesAccessKey="True"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
IsVisible="{TemplateBinding Content, Converter={x:Static ObjectConverters.IsNotNull}}"

3
src/Avalonia.Themes.Default/ComboBox.xaml

@ -69,7 +69,8 @@
MaxHeight="{TemplateBinding MaxDropDownHeight}"
PlacementTarget="{TemplateBinding}"
IsLightDismissEnabled="True">
<Border BorderBrush="{DynamicResource ThemeBorderMidBrush}"
<Border Background="{DynamicResource ThemeBackgroundBrush}"
BorderBrush="{DynamicResource ThemeBorderMidBrush}"
BorderThickness="1">
<ScrollViewer HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}"
VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}">

1
src/Avalonia.Themes.Default/ContextMenu.xaml

@ -1,4 +1,5 @@
<Style xmlns="https://github.com/avaloniaui" Selector="ContextMenu">
<Setter Property="Background" Value="{DynamicResource ThemeBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ThemeBorderMidBrush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Padding" Value="4,2"/>

2
src/Avalonia.Themes.Default/FlyoutPresenter.xaml

@ -2,7 +2,7 @@
<Style Selector="FlyoutPresenter">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Stretch" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Background" Value="{DynamicResource ThemeBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ThemeBorderMidBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Padding" Value="4" />

2
src/Avalonia.Themes.Default/MenuFlyoutPresenter.xaml

@ -1,6 +1,6 @@
<Styles xmlns="https://github.com/avaloniaui">
<Style Selector="MenuFlyoutPresenter">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Background" Value="{DynamicResource ThemeBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ThemeBorderMidBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" />

4
src/Avalonia.Themes.Default/MenuItem.xaml

@ -62,7 +62,7 @@
PlacementMode="Right"
IsLightDismissEnabled="False"
IsOpen="{TemplateBinding IsSubMenuOpen, Mode=TwoWay}">
<Border Background="{TemplateBinding Background}"
<Border Background="{DynamicResource ThemeBackgroundBrush}"
BorderBrush="{DynamicResource ThemeBorderMidBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Classes="menuscroller">
@ -113,7 +113,7 @@
IsLightDismissEnabled="True"
OverlayInputPassThroughElement="{Binding $parent[Menu]}"
IsOpen="{TemplateBinding IsSubMenuOpen, Mode=TwoWay}">
<Border Background="{TemplateBinding Background}"
<Border Background="{DynamicResource ThemeBackgroundBrush}"
BorderBrush="{DynamicResource ThemeBorderMidBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Classes="menuscroller">

28
src/Avalonia.Themes.Default/OverlayPopupHost.xaml

@ -1,17 +1,21 @@
<Style xmlns="https://github.com/avaloniaui" Selector="OverlayPopupHost">
<Setter Property="Background" Value="{DynamicResource ThemeBackgroundBrush}"/>
<Style xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Selector="OverlayPopupHost">
<Setter Property="Foreground" Value="{DynamicResource ThemeForegroundBrush}" />
<Setter Property="FontSize" Value="{DynamicResource FontSizeNormal}" />
<Setter Property="FontFamily" Value="{x:Static FontFamily.Default}" />
<Setter Property="FontWeight" Value="400" />
<Setter Property="FontStyle" Value="Normal" />
<Setter Property="Template">
<ControlTemplate>
<Panel>
<Border Name="PART_TransparencyFallback" IsHitTestVisible="False" />
<VisualLayerManager IsPopup="True">
<ContentPresenter Name="PART_ContentPresenter"
Background="{TemplateBinding Background}"
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}"
Padding="{TemplateBinding Padding}"/>
</VisualLayerManager>
</Panel>
<!-- Do not forget to update Templated_Control_With_Popup_In_Template_Should_Set_TemplatedParent test -->
<VisualLayerManager IsPopup="True">
<ContentPresenter Name="PART_ContentPresenter"
Background="{TemplateBinding Background}"
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}"
Padding="{TemplateBinding Padding}"/>
</VisualLayerManager>
</ControlTemplate>
</Setter>
</Style>

12
src/Avalonia.Themes.Default/PopupRoot.xaml

@ -1,5 +1,13 @@
<Style xmlns="https://github.com/avaloniaui" Selector="PopupRoot">
<Setter Property="Background" Value="{DynamicResource ThemeBackgroundBrush}"/>
<Style xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Selector="PopupRoot">
<Setter Property="Background" Value="{x:Null}"/>
<Setter Property="TransparencyLevelHint" Value="Transparent" />
<Setter Property="Foreground" Value="{DynamicResource ThemeForegroundBrush}"/>
<Setter Property="FontSize" Value="{DynamicResource FontSizeNormal}"/>
<Setter Property="FontFamily" Value="{x:Static FontFamily.Default}" />
<Setter Property="FontWeight" Value="400" />
<Setter Property="FontStyle" Value="Normal" />
<Setter Property="Template">
<ControlTemplate>
<Panel>

1
src/Avalonia.Themes.Default/RadioButton.xaml

@ -31,6 +31,7 @@
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}"
Margin="4,0,0,0"
RecognizesAccessKey="True"
VerticalAlignment="Center"
Grid.Column="1"/>
</Grid>

1
src/Avalonia.Themes.Default/ToggleButton.xaml

@ -17,6 +17,7 @@
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}"
Padding="{TemplateBinding Padding}"
RecognizesAccessKey="True"
TextBlock.Foreground="{TemplateBinding Foreground}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>

1
src/Avalonia.Themes.Default/ToggleSwitch.xaml

@ -87,6 +87,7 @@
Grid.Row="0"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
RecognizesAccessKey="True"
VerticalAlignment="Top"/>
<Grid Grid.Row="1"

1
src/Avalonia.Themes.Fluent/Controls/Button.xaml

@ -34,6 +34,7 @@
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
Padding="{TemplateBinding Padding}"
RecognizesAccessKey="True"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" />
</ControlTemplate>

1
src/Avalonia.Themes.Fluent/Controls/CheckBox.xaml

@ -44,6 +44,7 @@
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}"
Margin="{TemplateBinding Padding}"
RecognizesAccessKey="True"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Grid.Column="1" />

23
src/Avalonia.Themes.Fluent/Controls/OverlayPopupHost.xaml

@ -1,17 +1,18 @@
<Style xmlns="https://github.com/avaloniaui" Selector="OverlayPopupHost">
<Setter Property="Background" Value="{DynamicResource SystemControlBackgroundAltHighBrush}"/>
<Setter Property="Foreground" Value="{DynamicResource SystemControlForegroundBaseHighBrush}"/>
<Setter Property="FontSize" Value="{DynamicResource ControlContentThemeFontSize}"/>
<Setter Property="FontFamily" Value="{DynamicResource ContentControlThemeFontFamily}" />
<Setter Property="FontWeight" Value="400" />
<Setter Property="FontStyle" Value="Normal" />
<Setter Property="Template">
<ControlTemplate>
<Panel>
<Border Name="PART_TransparencyFallback" IsHitTestVisible="False" />
<VisualLayerManager IsPopup="True">
<ContentPresenter Name="PART_ContentPresenter"
Background="{TemplateBinding Background}"
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}"
Padding="{TemplateBinding Padding}"/>
</VisualLayerManager>
</Panel>
<VisualLayerManager IsPopup="True">
<ContentPresenter Name="PART_ContentPresenter"
Background="{TemplateBinding Background}"
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}"
Padding="{TemplateBinding Padding}"/>
</VisualLayerManager>
</ControlTemplate>
</Setter>
</Style>

7
src/Avalonia.Themes.Fluent/Controls/PopupRoot.xaml

@ -1,8 +1,13 @@
<Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style Selector="PopupRoot">
<Setter Property="Background" Value="{x:Null}"/>
<Setter Property="TransparencyLevelHint" Value="Transparent" />
<Setter Property="Background" Value="{x:Null}" />
<Setter Property="Foreground" Value="{DynamicResource SystemControlForegroundBaseHighBrush}"/>
<Setter Property="FontSize" Value="{DynamicResource ControlContentThemeFontSize}"/>
<Setter Property="FontFamily" Value="{DynamicResource ContentControlThemeFontFamily}" />
<Setter Property="FontWeight" Value="400" />
<Setter Property="FontStyle" Value="Normal" />
<Setter Property="Template">
<ControlTemplate>
<Panel>

1
src/Avalonia.Themes.Fluent/Controls/RadioButton.xaml

@ -51,6 +51,7 @@
ContentTemplate="{TemplateBinding ContentTemplate}"
TextBlock.Foreground="{TemplateBinding Foreground}"
Margin="{TemplateBinding Padding}"
RecognizesAccessKey="True"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Grid.Column="1" />

1
src/Avalonia.Themes.Fluent/Controls/ToggleButton.xaml

@ -34,6 +34,7 @@
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
Padding="{TemplateBinding Padding}"
RecognizesAccessKey="True"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" />
</ControlTemplate>

1
src/Avalonia.Themes.Fluent/Controls/ToggleSwitch.xaml

@ -53,6 +53,7 @@
Grid.Row="0"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
RecognizesAccessKey="True"
VerticalAlignment="Top"/>
<Grid Grid.Row="1"

20
src/Avalonia.Visuals/Rendering/SceneGraph/ClipNode.cs

@ -11,19 +11,23 @@ namespace Avalonia.Rendering.SceneGraph
/// Initializes a new instance of the <see cref="ClipNode"/> class that represents a
/// clip push.
/// </summary>
/// <param name="transform">The current transform.</param>
/// <param name="clip">The clip to push.</param>
public ClipNode(Rect clip)
public ClipNode(Matrix transform, Rect clip)
{
Transform = transform;
Clip = clip;
}
/// <summary>
/// Initializes a new instance of the <see cref="ClipNode"/> class that represents a
/// clip push.
/// </summary>
/// <param name="transform">The current transform.</param>
/// <param name="clip">The clip to push.</param>
public ClipNode(RoundedRect clip)
public ClipNode(Matrix transform, RoundedRect clip)
{
Transform = transform;
Clip = clip;
}
@ -43,23 +47,31 @@ namespace Avalonia.Rendering.SceneGraph
/// </summary>
public RoundedRect? Clip { get; }
/// <summary>
/// Gets the transform with which the node will be drawn.
/// </summary>
public Matrix Transform { get; }
/// <inheritdoc/>
public bool HitTest(Point p) => false;
/// <summary>
/// Determines if this draw operation equals another.
/// </summary>
/// <param name="transform">The transform of the other draw operation.</param>
/// <param name="clip">The clip of the other draw operation.</param>
/// <returns>True if the draw operations are the same, otherwise false.</returns>
/// <remarks>
/// The properties of the other draw operation are passed in as arguments to prevent
/// allocation of a not-yet-constructed draw operation object.
/// </remarks>
public bool Equals(RoundedRect? clip) => Clip == clip;
public bool Equals(Matrix transform, RoundedRect? clip) => Transform == transform && Clip == clip;
/// <inheritdoc/>
public void Render(IDrawingContextImpl context)
{
context.Transform = Transform;
if (Clip.HasValue)
{
context.PushClip(Clip.Value);

12
src/Avalonia.Visuals/Rendering/SceneGraph/DeferredDrawingContextImpl.cs

@ -303,9 +303,9 @@ namespace Avalonia.Rendering.SceneGraph
{
var next = NextDrawAs<ClipNode>();
if (next == null || !next.Item.Equals(clip))
if (next == null || !next.Item.Equals(Transform, clip))
{
Add(new ClipNode(clip));
Add(new ClipNode(Transform, clip));
}
else
{
@ -318,9 +318,9 @@ namespace Avalonia.Rendering.SceneGraph
{
var next = NextDrawAs<ClipNode>();
if (next == null || !next.Item.Equals(clip))
if (next == null || !next.Item.Equals(Transform, clip))
{
Add(new ClipNode(clip));
Add(new ClipNode(Transform, clip));
}
else
{
@ -333,9 +333,9 @@ namespace Avalonia.Rendering.SceneGraph
{
var next = NextDrawAs<GeometryClipNode>();
if (next == null || !next.Item.Equals(clip))
if (next == null || !next.Item.Equals(Transform, clip))
{
Add(new GeometryClipNode(clip));
Add(new GeometryClipNode(Transform, clip));
}
else
{

14
src/Avalonia.Visuals/Rendering/SceneGraph/GeometryClipNode.cs

@ -11,9 +11,11 @@ namespace Avalonia.Rendering.SceneGraph
/// Initializes a new instance of the <see cref="GeometryClipNode"/> class that represents a
/// geometry clip push.
/// </summary>
/// <param name="transform">The current transform.</param>
/// <param name="clip">The clip to push.</param>
public GeometryClipNode(IGeometryImpl clip)
public GeometryClipNode(Matrix transform, IGeometryImpl clip)
{
Transform = transform;
Clip = clip;
}
@ -33,23 +35,31 @@ namespace Avalonia.Rendering.SceneGraph
/// </summary>
public IGeometryImpl Clip { get; }
/// <summary>
/// Gets the transform with which the node will be drawn.
/// </summary>
public Matrix Transform { get; }
/// <inheritdoc/>
public bool HitTest(Point p) => false;
/// <summary>
/// Determines if this draw operation equals another.
/// </summary>
/// <param name="transform">The transform of the other draw operation.</param>
/// <param name="clip">The clip of the other draw operation.</param>
/// <returns>True if the draw operations are the same, otherwise false.</returns>
/// <remarks>
/// The properties of the other draw operation are passed in as arguments to prevent
/// allocation of a not-yet-constructed draw operation object.
/// </remarks>
public bool Equals(IGeometryImpl clip) => Clip == clip;
public bool Equals(Matrix transform, IGeometryImpl clip) => Transform == transform && Clip == clip;
/// <inheritdoc/>
public void Render(IDrawingContextImpl context)
{
context.Transform = Transform;
if (Clip != null)
{
context.PushGeometryClip(Clip);

2
src/Avalonia.X11/X11IconLoader.cs

@ -77,7 +77,9 @@ namespace Avalonia.X11
public void Save(Stream outputStream)
{
using (var wr =
#pragma warning disable CS0618 // Type or member is obsolete
new WriteableBitmap(new PixelSize(_width, _height), new Vector(96, 96), PixelFormat.Bgra8888))
#pragma warning restore CS0618 // Type or member is obsolete
{
using (var fb = wr.Lock())
{

19
src/Avalonia.X11/X11Platform.cs

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Avalonia.Controls;
@ -104,11 +105,25 @@ namespace Avalonia.X11
public IntPtr DeferredDisplay { get; set; }
public IntPtr Display { get; set; }
public ITrayIconImpl CreateTrayIcon ()
private static uint[] X11IconConverter(IWindowIconImpl icon)
{
return new X11TrayIconImpl();
if (!(icon is X11IconData x11icon))
return Array.Empty<uint>();
return x11icon.Data.Select(x => x.ToUInt32()).ToArray();
}
public ITrayIconImpl CreateTrayIcon()
{
var dbusTrayIcon = new DBusTrayIconImpl();
if (!dbusTrayIcon.IsActive) return new XEmbedTrayIconImpl();
dbusTrayIcon.IconConverterDelegate = X11IconConverter;
return dbusTrayIcon;
}
public IWindowImpl CreateWindow()
{
return new X11Window(this, null);

47
src/Avalonia.X11/XEmbedTrayIconImpl.cs

@ -0,0 +1,47 @@
using System;
using Avalonia.Controls.Platform;
using Avalonia.Logging;
using Avalonia.Platform;
namespace Avalonia.X11
{
internal class XEmbedTrayIconImpl : ITrayIconImpl
{
private bool _isCalled;
private void NotImplemented()
{
if(_isCalled) return;
Logger.TryGet(LogEventLevel.Error, LogArea.X11Platform)
?.Log(this,
"TODO: XEmbed System Tray Icons is not implemented yet. Tray icons won't be available on this system.");
_isCalled = true;
}
public void Dispose()
{
NotImplemented();
}
public void SetIcon(IWindowIconImpl icon)
{
NotImplemented();
}
public void SetToolTipText(string text)
{
NotImplemented();
}
public void SetIsVisible(bool visible)
{
NotImplemented();
}
public INativeMenuExporter MenuExporter { get; }
public Action OnClicked { get; set; }
}
}

35
src/Markup/Avalonia.Markup.Xaml.Loader/CompilerExtensions/Transformers/AvaloniaXamlIlSelectorTransformer.cs

@ -97,6 +97,12 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
case SelectorGrammar.NotSyntax not:
result = new XamlIlNotSelector(result, Create(not.Argument, typeResolver));
break;
case SelectorGrammar.NthChildSyntax nth:
result = new XamlIlNthChildSelector(result, nth.Step, nth.Offset, XamlIlNthChildSelector.SelectorType.NthChild);
break;
case SelectorGrammar.NthLastChildSyntax nth:
result = new XamlIlNthChildSelector(result, nth.Step, nth.Offset, XamlIlNthChildSelector.SelectorType.NthLastChild);
break;
case SelectorGrammar.CommaSyntax comma:
if (results == null)
results = new XamlIlOrSelectorNode(node, selectorType);
@ -273,6 +279,35 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
}
}
class XamlIlNthChildSelector : XamlIlSelectorNode
{
private readonly int _step;
private readonly int _offset;
private readonly SelectorType _type;
public enum SelectorType
{
NthChild,
NthLastChild
}
public XamlIlNthChildSelector(XamlIlSelectorNode previous, int step, int offset, SelectorType type) : base(previous)
{
_step = step;
_offset = offset;
_type = type;
}
public override IXamlType TargetType => Previous?.TargetType;
protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen)
{
codeGen.Ldc_I4(_step);
codeGen.Ldc_I4(_offset);
EmitCall(context, codeGen,
m => m.Name == _type.ToString() && m.Parameters.Count == 3);
}
}
class XamlIlPropertyEqualsSelector : XamlIlSelectorNode
{
public XamlIlPropertyEqualsSelector(XamlIlSelectorNode previous,

149
src/Markup/Avalonia.Markup/Markup/Parsers/SelectorGrammar.cs

@ -160,11 +160,13 @@ namespace Avalonia.Markup.Parsers
if (identifier.IsEmpty)
{
throw new ExpressionParseException(r.Position, "Expected class name or is selector after ':'.");
throw new ExpressionParseException(r.Position, "Expected class name, is, nth-child or nth-last-child selector after ':'.");
}
const string IsKeyword = "is";
const string NotKeyword = "not";
const string NthChildKeyword = "nth-child";
const string NthLastChildKeyword = "nth-last-child";
if (identifier.SequenceEqual(IsKeyword.AsSpan()) && r.TakeIf('('))
{
@ -181,6 +183,20 @@ namespace Avalonia.Markup.Parsers
var syntax = new NotSyntax { Argument = argument };
return (State.Middle, syntax);
}
if (identifier.SequenceEqual(NthChildKeyword.AsSpan()) && r.TakeIf('('))
{
var (step, offset) = ParseNthChildArguments(ref r);
var syntax = new NthChildSyntax { Step = step, Offset = offset };
return (State.Middle, syntax);
}
if (identifier.SequenceEqual(NthLastChildKeyword.AsSpan()) && r.TakeIf('('))
{
var (step, offset) = ParseNthChildArguments(ref r);
var syntax = new NthLastChildSyntax { Step = step, Offset = offset };
return (State.Middle, syntax);
}
else
{
return (
@ -191,7 +207,6 @@ namespace Avalonia.Markup.Parsers
});
}
}
private static (State, ISyntax?) ParseTraversal(ref CharacterReader r)
{
r.SkipWhitespace();
@ -302,6 +317,114 @@ namespace Avalonia.Markup.Parsers
return syntax;
}
private static (int step, int offset) ParseNthChildArguments(ref CharacterReader r)
{
int step = 0;
int offset = 0;
if (r.Peek == 'o')
{
var constArg = r.TakeUntil(')').ToString().Trim();
if (constArg.Equals("odd", StringComparison.Ordinal))
{
step = 2;
offset = 1;
}
else
{
throw new ExpressionParseException(r.Position, $"Expected nth-child(odd). Actual '{constArg}'.");
}
}
else if (r.Peek == 'e')
{
var constArg = r.TakeUntil(')').ToString().Trim();
if (constArg.Equals("even", StringComparison.Ordinal))
{
step = 2;
offset = 0;
}
else
{
throw new ExpressionParseException(r.Position, $"Expected nth-child(even). Actual '{constArg}'.");
}
}
else
{
r.SkipWhitespace();
var stepOrOffset = 0;
var stepOrOffsetStr = r.TakeWhile(c => char.IsDigit(c) || c == '-' || c == '+').ToString();
if (stepOrOffsetStr.Length == 0
|| (stepOrOffsetStr.Length == 1
&& stepOrOffsetStr[0] == '+'))
{
stepOrOffset = 1;
}
else if (stepOrOffsetStr.Length == 1
&& stepOrOffsetStr[0] == '-')
{
stepOrOffset = -1;
}
else if (!int.TryParse(stepOrOffsetStr.ToString(), out stepOrOffset))
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child step or offset value. Integer was expected.");
}
r.SkipWhitespace();
if (r.Peek == ')')
{
step = 0;
offset = stepOrOffset;
}
else
{
step = stepOrOffset;
if (r.Peek != 'n')
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child step value, \"xn+y\" pattern was expected.");
}
r.Skip(1); // skip 'n'
r.SkipWhitespace();
if (r.Peek != ')')
{
int sign;
var nextChar = r.Take();
if (nextChar == '+')
{
sign = 1;
}
else if (nextChar == '-')
{
sign = -1;
}
else
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child sign. '+' or '-' was expected.");
}
r.SkipWhitespace();
if (sign != 0
&& !int.TryParse(r.TakeUntil(')').ToString(), out offset))
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child offset value. Integer was expected.");
}
offset *= sign;
}
}
}
Expect(ref r, ')');
return (step, offset);
}
private static void Expect(ref CharacterReader r, char c)
{
if (r.End)
@ -419,6 +542,28 @@ namespace Avalonia.Markup.Parsers
}
}
public class NthChildSyntax : ISyntax
{
public int Offset { get; set; }
public int Step { get; set; }
public override bool Equals(object? obj)
{
return (obj is NthChildSyntax nth) && nth.Offset == Offset && nth.Step == Step;
}
}
public class NthLastChildSyntax : ISyntax
{
public int Offset { get; set; }
public int Step { get; set; }
public override bool Equals(object? obj)
{
return (obj is NthLastChildSyntax nth) && nth.Offset == Offset && nth.Step == Step;
}
}
public class CommaSyntax : ISyntax
{
public override bool Equals(object? obj)

6
src/Markup/Avalonia.Markup/Markup/Parsers/SelectorParser.cs

@ -104,6 +104,12 @@ namespace Avalonia.Markup.Parsers
case SelectorGrammar.NotSyntax not:
result = result.Not(x => Create(not.Argument));
break;
case SelectorGrammar.NthChildSyntax nth:
result = result.NthChild(nth.Step, nth.Offset);
break;
case SelectorGrammar.NthLastChildSyntax nth:
result = result.NthLastChild(nth.Step, nth.Offset);
break;
case SelectorGrammar.CommaSyntax comma:
if (results == null)
{

7
src/Skia/Avalonia.Skia/SKTypefaceCollection.cs

@ -27,15 +27,16 @@ namespace Avalonia.Skia
{
return typeface;
}
var initialWeight = (int)key.Weight;
var weight = (int)key.Weight;
weight -= weight % 100; // make sure we start at a full weight
weight -= weight % 50; // make sure we start at a full weight
for (var i = 0; i < 2; i++)
{
// only try 2 font weights in each direction
for (var j = 0; j < 200; j += 100)
for (var j = 0; j < initialWeight; j += 50)
{
if (weight - j >= 100)
{

8
src/tools/MicroComGenerator/Program.cs

@ -35,8 +35,16 @@ namespace MicroComGenerator
if (opts.CppOutput != null)
File.WriteAllText(opts.CppOutput, CppGen.GenerateCpp(ast));
if (opts.CSharpOutput != null)
{
File.WriteAllText(opts.CSharpOutput, new CSharpGen(ast).Generate());
// HACK: Can't work out how to get the VS project system's fast up-to-date checks
// to ignore the generated code, so as a workaround set the write time to that of
// the input.
File.SetLastWriteTime(opts.CSharpOutput, File.GetLastWriteTime(opts.Input));
}
return 0;
}

14
tests/Avalonia.Controls.UnitTests/ButtonTests.cs

@ -2,6 +2,7 @@
using System.Windows.Input;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Rendering;
@ -271,6 +272,19 @@ namespace Avalonia.Controls.UnitTests
[Fact]
public void Button_Invokes_CanExecute_When_CommandParameter_Changed()
{
var target = new Button();
var raised = 0;
target.Click += (s, e) => ++raised;
target.RaiseEvent(new RoutedEventArgs(AccessKeyHandler.AccessKeyPressedEvent));
Assert.Equal(1, raised);
}
[Fact]
public void Raises_Click_When_AccessKey_Raised()
{
var command = new TestCommand(p => p is bool value && value);
var target = new Button { Command = command };

75
tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs

@ -294,6 +294,7 @@ namespace Avalonia.Controls.UnitTests.Primitives
[Fact]
public void Templated_Control_With_Popup_In_Template_Should_Set_TemplatedParent()
{
// Test uses OverlayPopupHost default template
using (CreateServices())
{
PopupContentControl target;
@ -316,33 +317,63 @@ namespace Avalonia.Controls.UnitTests.Primitives
var children = popupRoot.GetVisualDescendants().ToList();
var types = children.Select(x => x.GetType().Name).ToList();
Assert.Equal(
new[]
{
"Panel",
"Border",
"VisualLayerManager",
"ContentPresenter",
"ContentPresenter",
"Border",
},
types);
if (UsePopupHost)
{
Assert.Equal(
new[]
{
"VisualLayerManager",
"ContentPresenter",
"ContentPresenter",
"Border",
},
types);
}
else
{
Assert.Equal(
new[]
{
"Panel",
"Border",
"VisualLayerManager",
"ContentPresenter",
"ContentPresenter",
"Border",
},
types);
}
var templatedParents = children
.OfType<IControl>()
.Select(x => x.TemplatedParent).ToList();
Assert.Equal(
new object[]
{
popupRoot,
popupRoot,
popupRoot,
popupRoot,
target,
null,
},
templatedParents);
if (UsePopupHost)
{
Assert.Equal(
new object[]
{
popupRoot,
popupRoot,
target,
null,
},
templatedParents);
}
else
{
Assert.Equal(
new object[]
{
popupRoot,
popupRoot,
popupRoot,
popupRoot,
target,
null,
},
templatedParents);
}
}
}

159
tests/Avalonia.Markup.UnitTests/Parsers/SelectorGrammarTests.cs

@ -236,6 +236,165 @@ namespace Avalonia.Markup.UnitTests.Parsers
result);
}
[Theory]
[InlineData(":nth-child(xn+2)")]
[InlineData(":nth-child(2n+b)")]
[InlineData(":nth-child(2n+)")]
[InlineData(":nth-child(2na)")]
[InlineData(":nth-child(2x+1)")]
public void NthChild_Invalid_Inputs(string input)
{
Assert.Throws<ExpressionParseException>(() => SelectorGrammar.Parse(input));
}
[Theory]
[InlineData(":nth-child(+1)", 0, 1)]
[InlineData(":nth-child(1)", 0, 1)]
[InlineData(":nth-child(-1)", 0, -1)]
[InlineData(":nth-child(2n+1)", 2, 1)]
[InlineData(":nth-child(n)", 1, 0)]
[InlineData(":nth-child(+n)", 1, 0)]
[InlineData(":nth-child(-n)", -1, 0)]
[InlineData(":nth-child(-2n)", -2, 0)]
[InlineData(":nth-child(n+5)", 1, 5)]
[InlineData(":nth-child(n-5)", 1, -5)]
[InlineData(":nth-child( 2n + 1 )", 2, 1)]
[InlineData(":nth-child( 2n - 1 )", 2, -1)]
public void NthChild_Variations(string input, int step, int offset)
{
var result = SelectorGrammar.Parse(input);
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.NthChildSyntax()
{
Step = step,
Offset = offset
}
},
result);
}
[Theory]
[InlineData(":nth-last-child(+1)", 0, 1)]
[InlineData(":nth-last-child(1)", 0, 1)]
[InlineData(":nth-last-child(-1)", 0, -1)]
[InlineData(":nth-last-child(2n+1)", 2, 1)]
[InlineData(":nth-last-child(n)", 1, 0)]
[InlineData(":nth-last-child(+n)", 1, 0)]
[InlineData(":nth-last-child(-n)", -1, 0)]
[InlineData(":nth-last-child(-2n)", -2, 0)]
[InlineData(":nth-last-child(n+5)", 1, 5)]
[InlineData(":nth-last-child(n-5)", 1, -5)]
[InlineData(":nth-last-child( 2n + 1 )", 2, 1)]
[InlineData(":nth-last-child( 2n - 1 )", 2, -1)]
public void NthLastChild_Variations(string input, int step, int offset)
{
var result = SelectorGrammar.Parse(input);
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.NthLastChildSyntax()
{
Step = step,
Offset = offset
}
},
result);
}
[Fact]
public void OfType_NthChild()
{
var result = SelectorGrammar.Parse("Button:nth-child(2n+1)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthChildSyntax()
{
Step = 2,
Offset = 1
}
},
result);
}
[Fact]
public void OfType_NthChild_Without_Offset()
{
var result = SelectorGrammar.Parse("Button:nth-child(2147483647n)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthChildSyntax()
{
Step = int.MaxValue,
Offset = 0
}
},
result);
}
[Fact]
public void OfType_NthLastChild()
{
var result = SelectorGrammar.Parse("Button:nth-last-child(2n+1)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthLastChildSyntax()
{
Step = 2,
Offset = 1
}
},
result);
}
[Fact]
public void OfType_NthChild_Odd()
{
var result = SelectorGrammar.Parse("Button:nth-child(odd)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthChildSyntax()
{
Step = 2,
Offset = 1
}
},
result);
}
[Fact]
public void OfType_NthChild_Even()
{
var result = SelectorGrammar.Parse("Button:nth-child(even)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthChildSyntax()
{
Step = 2,
Offset = 0
}
},
result);
}
[Fact]
public void Is_Descendent_Not_OfType_Class()
{

197
tests/Avalonia.Markup.Xaml.UnitTests/Xaml/StyleTests.cs

@ -1,6 +1,8 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Xml;
using Avalonia.Controls;
using Avalonia.Markup.Data;
using Avalonia.Markup.Xaml.Styling;
using Avalonia.Markup.Xaml.Templates;
using Avalonia.Media;
@ -267,6 +269,199 @@ namespace Avalonia.Markup.Xaml.UnitTests.Xaml
}
}
[Fact]
public void Style_Can_Use_NthChild_Selector()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Border.foo:nth-child(2n+1)'>
<Setter Property='Background' Value='Red'/>
</Style>
</Window.Styles>
<StackPanel>
<Border x:Name='b1' Classes='foo'/>
<Border x:Name='b2' />
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var b1 = window.FindControl<Border>("b1");
var b2 = window.FindControl<Border>("b2");
Assert.Equal(Brushes.Red, b1.Background);
Assert.Null(b2.Background);
}
}
[Fact]
public void Style_Can_Use_NthChild_Selector_After_Reoder()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Border:nth-child(2n)'>
<Setter Property='Background' Value='Red'/>
</Style>
</Window.Styles>
<StackPanel x:Name='parent'>
<Border x:Name='b1' />
<Border x:Name='b2' />
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var parent = window.FindControl<StackPanel>("parent");
var b1 = window.FindControl<Border>("b1");
var b2 = window.FindControl<Border>("b2");
Assert.Null(b1.Background);
Assert.Equal(Brushes.Red, b2.Background);
parent.Children.Remove(b1);
Assert.Null(b1.Background);
Assert.Null(b2.Background);
parent.Children.Add(b1);
Assert.Equal(Brushes.Red, b1.Background);
Assert.Null(b2.Background);
}
}
[Fact]
public void Style_Can_Use_NthLastChild_Selector_After_Reoder()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Border:nth-last-child(2n)'>
<Setter Property='Background' Value='Red'/>
</Style>
</Window.Styles>
<StackPanel x:Name='parent'>
<Border x:Name='b1' />
<Border x:Name='b2' />
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var parent = window.FindControl<StackPanel>("parent");
var b1 = window.FindControl<Border>("b1");
var b2 = window.FindControl<Border>("b2");
Assert.Equal(Brushes.Red, b1.Background);
Assert.Null(b2.Background);
parent.Children.Remove(b1);
Assert.Null(b1.Background);
Assert.Null(b2.Background);
parent.Children.Add(b1);
Assert.Null(b1.Background);
Assert.Equal(Brushes.Red, b2.Background);
}
}
[Fact]
public void Style_Can_Use_NthChild_Selector_With_ListBox()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='ListBoxItem:nth-child(2n)'>
<Setter Property='Background' Value='{Binding}'/>
</Style>
</Window.Styles>
<ListBox x:Name='list' />
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var collection = new ObservableCollection<IBrush>()
{
Brushes.Red, Brushes.Green, Brushes.Blue
};
var list = window.FindControl<ListBox>("list");
list.VirtualizationMode = ItemVirtualizationMode.Simple;
list.Items = collection;
window.Show();
IEnumerable<IBrush> GetColors() => list.Presenter.Panel.Children.Cast<ListBoxItem>().Select(t => t.Background);
Assert.Equal(new[] { Brushes.Transparent, Brushes.Green, Brushes.Transparent }, GetColors());
collection.Remove(Brushes.Green);
Assert.Equal(new[] { Brushes.Transparent, Brushes.Blue }, GetColors());
collection.Add(Brushes.Violet);
collection.Add(Brushes.Black);
Assert.Equal(new[] { Brushes.Transparent, Brushes.Blue, Brushes.Transparent, Brushes.Black }, GetColors());
}
}
[Fact]
public void Style_Can_Use_NthChild_Selector_With_ItemsRepeater()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='TextBlock'>
<Setter Property='Foreground' Value='Transparent'/>
</Style>
<Style Selector='TextBlock:nth-child(2n)'>
<Setter Property='Foreground' Value='{Binding}'/>
</Style>
</Window.Styles>
<ItemsRepeater x:Name='list' />
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var collection = new ObservableCollection<IBrush>()
{
Brushes.Red, Brushes.Green, Brushes.Blue
};
var list = window.FindControl<ItemsRepeater>("list");
list.Items = collection;
window.Show();
IEnumerable<IBrush> GetColors() => Enumerable.Range(0, list.ItemsSourceView.Count)
.Select(t => (list.GetOrCreateElement(t) as TextBlock)!.Foreground);
Assert.Equal(new[] { Brushes.Transparent, Brushes.Green, Brushes.Transparent }, GetColors());
collection.Remove(Brushes.Green);
Assert.Equal(new[] { Brushes.Transparent, Brushes.Blue }, GetColors());
collection.Add(Brushes.Violet);
collection.Add(Brushes.Black);
Assert.Equal(new[] { Brushes.Transparent, Brushes.Blue, Brushes.Transparent, Brushes.Black }, GetColors());
}
}
[Fact]
public void Style_Can_Use_Or_Selector_1()
{

48
tests/Avalonia.RenderTests/Controls/CustomRenderTests.cs

@ -78,6 +78,54 @@ namespace Avalonia.Direct2D1.RenderTests.Controls
CompareImages();
}
[Fact]
public async Task GeometryClip_With_Transform()
{
var target = new Border
{
Background = Brushes.White,
Width = 200,
Height = 200,
Child = new CustomRenderer((control, context) =>
{
using (var transform = context.PushPreTransform(Matrix.CreateTranslation(100, 100)))
using (var clip = context.PushClip(new Rect(0, 0, 100, 100)))
{
context.FillRectangle(Brushes.Blue, new Rect(0, 0, 200, 200));
}
context.FillRectangle(Brushes.Red, new Rect(0, 0, 100, 100));
}),
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Clip_With_Transform()
{
var target = new Border
{
Background = Brushes.White,
Width = 200,
Height = 200,
Child = new CustomRenderer((control, context) =>
{
using (var transform = context.PushPreTransform(Matrix.CreateTranslation(100, 100)))
using (var clip = context.PushClip(new Rect(0, 0, 100, 100)))
{
context.FillRectangle(Brushes.Blue, new Rect(0, 0, 200, 200));
}
context.FillRectangle(Brushes.Red, new Rect(0, 0, 100, 100));
}),
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Opacity()
{

22
tests/Avalonia.Skia.UnitTests/Media/SKTypefaceCollectionCacheTests.cs

@ -6,18 +6,24 @@ namespace Avalonia.Skia.UnitTests.Media
{
public class SKTypefaceCollectionCacheTests
{
[Fact]
public void Should_Get_Near_Matching_Typeface()
private const string s_notoMono =
"resm:Avalonia.Skia.UnitTests.Assets?assembly=Avalonia.Skia.UnitTests#Noto Mono";
[InlineData(s_notoMono, FontWeight.SemiLight, FontStyle.Normal)]
[InlineData(s_notoMono, FontWeight.Bold, FontStyle.Italic)]
[InlineData(s_notoMono, FontWeight.Heavy, FontStyle.Oblique)]
[Theory]
public void Should_Get_Near_Matching_Typeface(string familyName, FontWeight fontWeight, FontStyle fontStyle)
{
using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
{
var notoMono =
new FontFamily("resm:Avalonia.Skia.UnitTests.Assets?assembly=Avalonia.Skia.UnitTests#Noto Mono");
var notoMonoCollection = SKTypefaceCollectionCache.GetOrAddTypefaceCollection(notoMono);
var fontFamily = new FontFamily(familyName);
var typefaceCollection = SKTypefaceCollectionCache.GetOrAddTypefaceCollection(fontFamily);
Assert.Equal("Noto Mono",
notoMonoCollection.Get(new Typeface(notoMono, weight: FontWeight.Bold)).FamilyName);
var actual = typefaceCollection.Get(new Typeface(fontFamily, fontStyle, fontWeight))?.FamilyName;
Assert.Equal("Noto Mono", actual);
}
}

291
tests/Avalonia.Styling.UnitTests/SelectorTests_NthChild.cs

@ -0,0 +1,291 @@
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using Xunit;
namespace Avalonia.Styling.UnitTests
{
public class SelectorTests_NthChild
{
[Theory]
[InlineData(2, 0, ":nth-child(2n)")]
[InlineData(2, 1, ":nth-child(2n+1)")]
[InlineData(1, 0, ":nth-child(1n)")]
[InlineData(4, -1, ":nth-child(4n-1)")]
[InlineData(0, 1, ":nth-child(1)")]
[InlineData(0, -1, ":nth-child(-1)")]
[InlineData(int.MaxValue, int.MinValue + 1, ":nth-child(2147483647n-2147483647)")]
public void Not_Selector_Should_Have_Correct_String_Representation(int step, int offset, string expected)
{
var target = default(Selector).NthChild(step, offset);
Assert.Equal(expected, target.ToString());
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(2, 0);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.True(await target.Match(b2).Activator!.Take(1));
Assert.False(await target.Match(b3).Activator!.Take(1));
Assert.True(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(2, 1);
Assert.True(await target.Match(b1).Activator!.Take(1));
Assert.False(await target.Match(b2).Activator!.Take(1));
Assert.True(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(4, -1);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.False(await target.Match(b2).Activator!.Take(1));
Assert.True(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Singular_Step()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(1, 2);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.True(await target.Match(b2).Activator!.Take(1));
Assert.True(await target.Match(b3).Activator!.Take(1));
Assert.True(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Singular_Step_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(1, -1);
Assert.True(await target.Match(b1).Activator!.Take(1));
Assert.True(await target.Match(b2).Activator!.Take(1));
Assert.True(await target.Match(b3).Activator!.Take(1));
Assert.True(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Zero_Step_With_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(0, 2);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.True(await target.Match(b2).Activator!.Take(1));
Assert.False(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Doesnt_Match_Control_In_Panel_With_Zero_Step_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(0, -2);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.False(await target.Match(b2).Activator!.Take(1));
Assert.False(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Previous_Selector()
{
Border b1, b2;
Button b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new Control[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Button(),
b4 = new Button()
});
var previous = default(Selector).OfType<Border>();
var target = previous.NthChild(2, 0);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.True(await target.Match(b2).Activator!.Take(1));
Assert.Null(target.Match(b3).Activator);
Assert.Equal(SelectorMatchResult.NeverThisType, target.Match(b3).Result);
Assert.Null(target.Match(b4).Activator);
Assert.Equal(SelectorMatchResult.NeverThisType, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Doesnt_Match_Control_Out_Of_Panel_Parent()
{
Border b1;
var contentControl = new ContentControl();
contentControl.Content = b1 = new Border();
var target = default(Selector).NthChild(1, 0);
Assert.Equal(SelectorMatch.NeverThisInstance, target.Match(b1));
}
[Theory] // http://nthmaster.com/
[InlineData(+0, 8, false, false, false, false, false, false, false, true , false, false, false)]
[InlineData(+1, 6, false, false, false, false, false, true , true , true , true , true , true )]
[InlineData(-1, 9, true , true , true , true , true , true , true , true , true , false, false)]
public async Task Nth_Child_Master_Com_Test_Sigle_Selector(
int step, int offset, params bool[] items)
{
var panel = new StackPanel();
panel.Children.AddRange(items.Select(_ => new Border()));
var previous = default(Selector).OfType<Border>();
var target = previous.NthChild(step, offset);
var results = new bool[items.Length];
for (int index = 0; index < items.Length; index++)
{
var border = panel.Children[index];
results[index] = await target.Match(border).Activator!.Take(1);
}
Assert.Equal(items, results);
}
[Theory] // http://nthmaster.com/
[InlineData(+1, 4, -1, 8, false, false, false, true , true , true , true , true , false, false, false)]
[InlineData(+3, 1, +2, 0, false, false, false, true , false, false, false, false, false, true , false)]
public async Task Nth_Child_Master_Com_Test_Double_Selector(
int step1, int offset1, int step2, int offset2, params bool[] items)
{
var panel = new StackPanel();
panel.Children.AddRange(items.Select(_ => new Border()));
var previous = default(Selector).OfType<Border>();
var middle = previous.NthChild(step1, offset1);
var target = middle.NthChild(step2, offset2);
var results = new bool[items.Length];
for (int index = 0; index < items.Length; index++)
{
var border = panel.Children[index];
results[index] = await target.Match(border).Activator!.Take(1);
}
Assert.Equal(items, results);
}
[Theory] // http://nthmaster.com/
[InlineData(+1, 2, 2, 1, -1, 9, false, false, true , false, true , false, true , false, true , false, false)]
public async Task Nth_Child_Master_Com_Test_Triple_Selector(
int step1, int offset1, int step2, int offset2, int step3, int offset3, params bool[] items)
{
var panel = new StackPanel();
panel.Children.AddRange(items.Select(_ => new Border()));
var previous = default(Selector).OfType<Border>();
var middle1 = previous.NthChild(step1, offset1);
var middle2 = middle1.NthChild(step2, offset2);
var target = middle2.NthChild(step3, offset3);
var results = new bool[items.Length];
for (int index = 0; index < items.Length; index++)
{
var border = panel.Children[index];
results[index] = await target.Match(border).Activator!.Take(1);
}
Assert.Equal(items, results);
}
[Fact]
public void Returns_Correct_TargetType()
{
var target = new NthChildSelector(default(Selector).OfType<Control1>(), 1, 0);
Assert.Equal(typeof(Control1), target.TargetType);
}
public class Control1 : Control
{
}
}
}

220
tests/Avalonia.Styling.UnitTests/SelectorTests_NthLastChild.cs

@ -0,0 +1,220 @@
using System.Threading.Tasks;
using Avalonia.Controls;
using Xunit;
namespace Avalonia.Styling.UnitTests
{
public class SelectorTests_NthLastChild
{
[Theory]
[InlineData(2, 0, ":nth-last-child(2n)")]
[InlineData(2, 1, ":nth-last-child(2n+1)")]
[InlineData(1, 0, ":nth-last-child(1n)")]
[InlineData(4, -1, ":nth-last-child(4n-1)")]
[InlineData(0, 1, ":nth-last-child(1)")]
[InlineData(0, -1, ":nth-last-child(-1)")]
[InlineData(int.MaxValue, int.MinValue + 1, ":nth-last-child(2147483647n-2147483647)")]
public void Not_Selector_Should_Have_Correct_String_Representation(int step, int offset, string expected)
{
var target = default(Selector).NthLastChild(step, offset);
Assert.Equal(expected, target.ToString());
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(2, 0);
Assert.True(await target.Match(b1).Activator!.Take(1));
Assert.False(await target.Match(b2).Activator!.Take(1));
Assert.True(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(2, 1);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.True(await target.Match(b2).Activator!.Take(1));
Assert.False(await target.Match(b3).Activator!.Take(1));
Assert.True(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(4, -1);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.True(await target.Match(b2).Activator!.Take(1));
Assert.False(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Singular_Step()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(1, 2);
Assert.True(await target.Match(b1).Activator!.Take(1));
Assert.True(await target.Match(b2).Activator!.Take(1));
Assert.True(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Singular_Step_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(1, -2);
Assert.True(await target.Match(b1).Activator!.Take(1));
Assert.True(await target.Match(b2).Activator!.Take(1));
Assert.True(await target.Match(b3).Activator!.Take(1));
Assert.True(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Zero_Step_With_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(0, 2);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.False(await target.Match(b2).Activator!.Take(1));
Assert.True(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Doesnt_Match_Control_In_Panel_With_Zero_Step_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(0, -2);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.False(await target.Match(b2).Activator!.Take(1));
Assert.False(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Previous_Selector()
{
Border b1, b2;
Button b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new Control[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Button(),
b4 = new Button()
});
var previous = default(Selector).OfType<Border>();
var target = previous.NthLastChild(2, 0);
Assert.True(await target.Match(b1).Activator!.Take(1));
Assert.False(await target.Match(b2).Activator!.Take(1));
Assert.Null(target.Match(b3).Activator);
Assert.Equal(SelectorMatchResult.NeverThisType, target.Match(b3).Result);
Assert.Null(target.Match(b4).Activator);
Assert.Equal(SelectorMatchResult.NeverThisType, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Doesnt_Match_Control_Out_Of_Panel_Parent()
{
Border b1;
var contentControl = new ContentControl();
contentControl.Content = b1 = new Border();
var target = default(Selector).NthLastChild(1, 0);
Assert.Equal(SelectorMatch.NeverThisInstance, target.Match(b1));
}
[Fact]
public void Returns_Correct_TargetType()
{
var target = new NthLastChildSelector(default(Selector).OfType<Control1>(), 1, 0);
Assert.Equal(typeof(Control1), target.TargetType);
}
public class Control1 : Control
{
}
}
}

7
tests/Avalonia.Styling.UnitTests/StyleActivatorExtensions.cs

@ -20,13 +20,17 @@ namespace Avalonia.Styling.UnitTests
public static IObservable<bool> ToObservable(this IStyleActivator activator)
{
if (activator == null)
{
throw new ArgumentNullException(nameof(activator));
}
return new ObservableAdapter(activator);
}
private class ObservableAdapter : LightweightObservableBase<bool>, IStyleActivatorSink
{
private readonly IStyleActivator _source;
private bool _value;
public ObservableAdapter(IStyleActivator source) => _source = source;
protected override void Initialize() => _source.Subscribe(this);
@ -34,7 +38,6 @@ namespace Avalonia.Styling.UnitTests
void IStyleActivatorSink.OnNext(bool value, int tag)
{
_value = value;
PublishNext(value);
}
}

BIN
tests/TestFiles/Direct2D1/Controls/CustomRender/Clip_With_Transform.expected.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 634 B

BIN
tests/TestFiles/Direct2D1/Controls/CustomRender/GeometryClip_With_Transform.expected.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 634 B

BIN
tests/TestFiles/Skia/Controls/CustomRender/Clip_With_Transform.expected.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 621 B

BIN
tests/TestFiles/Skia/Controls/CustomRender/GeometryClip_With_Transform.expected.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 621 B

Loading…
Cancel
Save