Browse Source

Merge branch 'master' into feature/itemsrepeater-elementfactory

pull/4218/head
Steven Kirk 6 years ago
parent
commit
c421000997
  1. 2
      .gitmodules
  2. 52
      Avalonia.sln
  3. 4
      build/HarfBuzzSharp.props
  4. 4
      build/SkiaSharp.props
  5. 13
      native/Avalonia.Native/inc/avalonia-native.h
  6. 13
      native/Avalonia.Native/src/OSX/window.h
  7. 289
      native/Avalonia.Native/src/OSX/window.mm
  8. 2
      nukebuild/Build.cs
  9. 76
      nukebuild/BuildTasksPatcher.cs
  10. 3
      nukebuild/_build.csproj
  11. 2
      readme.md
  12. 5
      samples/BindingDemo/MainWindow.xaml
  13. 4
      samples/BindingDemo/ViewModels/MainWindowViewModel.cs
  14. 3
      samples/ControlCatalog.NetCore/ControlCatalog.NetCore.csproj
  15. 55
      samples/ControlCatalog.NetCore/Program.cs
  16. 16
      samples/ControlCatalog/App.xaml.cs
  17. 7
      samples/ControlCatalog/MainView.xaml
  18. 7
      samples/ControlCatalog/MainView.xaml.cs
  19. 41
      samples/ControlCatalog/MainWindow.xaml
  20. 139
      samples/ControlCatalog/Pages/AcrylicPage.xaml
  21. 19
      samples/ControlCatalog/Pages/AcrylicPage.xaml.cs
  22. 12
      samples/ControlCatalog/Pages/BorderPage.xaml
  23. 14
      samples/ControlCatalog/Pages/ButtonPage.xaml
  24. 2
      samples/ControlCatalog/Pages/ComboBoxPage.xaml
  25. 4
      samples/ControlCatalog/Pages/ContextMenuPage.xaml
  26. 6
      samples/ControlCatalog/Pages/DragAndDropPage.xaml
  27. 20
      samples/ControlCatalog/Pages/ItemsRepeaterPage.xaml.cs
  28. 8
      samples/ControlCatalog/Pages/LayoutTransformControlPage.xaml
  29. 60
      samples/ControlCatalog/Pages/RelativePanelPage.axaml
  30. 19
      samples/ControlCatalog/Pages/RelativePanelPage.axaml.cs
  31. 21
      samples/ControlCatalog/Pages/SliderPage.xaml
  32. 69
      samples/ControlCatalog/Pages/TextBlockPage.xaml
  33. 4
      samples/ControlCatalog/Pages/ToolTipPage.xaml
  34. 19
      samples/ControlCatalog/Pages/WindowCustomizationsPage.xaml
  35. 19
      samples/ControlCatalog/Pages/WindowCustomizationsPage.xaml.cs
  36. 6
      samples/ControlCatalog/SideBar.xaml
  37. 65
      samples/ControlCatalog/ViewModels/MainWindowViewModel.cs
  38. 4
      samples/RenderDemo/Pages/ClippingPage.xaml
  39. 4
      samples/RenderDemo/SideBar.xaml
  40. 1
      samples/interop/NativeEmbedSample/NativeEmbedSample.csproj
  41. 12
      src/Avalonia.Base/AvaloniaProperty.cs
  42. 4
      src/Avalonia.Base/AvaloniaPropertyRegistry.cs
  43. 2
      src/Avalonia.Base/Collections/Pooled/IReadOnlyPooledList.cs
  44. 3
      src/Avalonia.Base/Collections/Pooled/PooledList.cs
  45. 34
      src/Avalonia.Base/Data/BindingValue.cs
  46. 73
      src/Avalonia.Base/Data/Core/ClrPropertyInfo.cs
  47. 32
      src/Avalonia.Base/Data/Core/ExpressionObserver.cs
  48. 14
      src/Avalonia.Base/Data/Core/IPropertyInfo.cs
  49. 2
      src/Avalonia.Base/Data/Core/Plugins/TaskStreamPlugin.cs
  50. 32
      src/Avalonia.Base/Data/Core/PropertyAccessorNode.cs
  51. 91
      src/Avalonia.Base/Data/Core/PropertyPath.cs
  52. 37
      src/Avalonia.Base/Data/Core/StreamNode.cs
  53. 16
      src/Avalonia.Base/Data/Optional.cs
  54. 2
      src/Avalonia.Base/DirectPropertyBase.cs
  55. 2
      src/Avalonia.Base/IStyledPropertyMetadata.cs
  56. 140
      src/Avalonia.Base/Metadata/NullableAttributes.cs
  57. 7
      src/Avalonia.Base/PropertyStore/IPriorityValueEntry.cs
  58. 7
      src/Avalonia.Base/PropertyStore/LocalValueEntry.cs
  59. 3
      src/Avalonia.Base/StyledPropertyMetadata`1.cs
  60. 20
      src/Avalonia.Base/Utilities/CharacterReader.cs
  61. 46
      src/Avalonia.Base/Utilities/KeywordParser.cs
  62. 45
      src/Avalonia.Base/Utilities/StyleClassParser.cs
  63. 2
      src/Avalonia.Base/ValueStore.cs
  64. 45
      src/Avalonia.Build.Tasks/Avalonia.Build.Tasks.csproj
  65. 2
      src/Avalonia.Build.Tasks/XamlCompilerTaskExecutor.Helpers.cs
  66. 60
      src/Avalonia.Build.Tasks/XamlCompilerTaskExecutor.cs
  67. 2
      src/Avalonia.Controls.DataGrid/DataGrid.cs
  68. 5
      src/Avalonia.Controls.DataGrid/DataGridRow.cs
  69. 5
      src/Avalonia.Controls.DataGrid/Primitives/DataGridCellsPresenter.cs
  70. 2
      src/Avalonia.Controls.DataGrid/Themes/Default.xaml
  71. 23
      src/Avalonia.Controls/AcrylicPlatformCompensationLevels.cs
  72. 86
      src/Avalonia.Controls/Chrome/CaptionButtons.cs
  73. 117
      src/Avalonia.Controls/Chrome/TitleBar.cs
  74. 31
      src/Avalonia.Controls/ComboBox.cs
  75. 3
      src/Avalonia.Controls/Embedding/Offscreen/OffscreenTopLevelImpl.cs
  76. 117
      src/Avalonia.Controls/ExperimentalAcrylicBorder.cs
  77. 38
      src/Avalonia.Controls/Platform/ExtendClientAreaChromeHints.cs
  78. 5
      src/Avalonia.Controls/Platform/ITopLevelImpl.cs
  79. 46
      src/Avalonia.Controls/Platform/IWindowImpl.cs
  80. 1
      src/Avalonia.Controls/Presenters/ContentPresenter.cs
  81. 4
      src/Avalonia.Controls/Presenters/TextPresenter.cs
  82. 21
      src/Avalonia.Controls/Primitives/AccessText.cs
  83. 29
      src/Avalonia.Controls/Primitives/ChromeOverlayLayer.cs
  84. 9
      src/Avalonia.Controls/Primitives/Track.cs
  85. 15
      src/Avalonia.Controls/Primitives/VisualLayerManager.cs
  86. 1
      src/Avalonia.Controls/Properties/AssemblyInfo.cs
  87. 546
      src/Avalonia.Controls/RelativePanel.AttachedProperties.cs
  88. 353
      src/Avalonia.Controls/RelativePanel.cs
  89. 9
      src/Avalonia.Controls/ResolveByNameAttribute.cs
  90. 66
      src/Avalonia.Controls/Slider.cs
  91. 64
      src/Avalonia.Controls/TextBlock.cs
  92. 12
      src/Avalonia.Controls/TickBar.cs
  93. 118
      src/Avalonia.Controls/ToggleSwitch.cs
  94. 2
      src/Avalonia.Controls/TopLevel.cs
  95. 135
      src/Avalonia.Controls/Window.cs
  96. 24
      src/Avalonia.DesignerSupport/Remote/PreviewerWindowImpl.cs
  97. 26
      src/Avalonia.DesignerSupport/Remote/Stubs.cs
  98. 4
      src/Avalonia.Desktop/AppBuilderDesktopExtensions.cs
  99. 3
      src/Avalonia.Desktop/Avalonia.Desktop.csproj
  100. 12
      src/Avalonia.Headless.Vnc/Avalonia.Headless.Vnc.csproj

2
.gitmodules

@ -3,4 +3,4 @@
url = https://github.com/kekekeks/Numerge.git
[submodule "src/Markup/Avalonia.Markup.Xaml/XamlIl/xamlil.github"]
path = src/Markup/Avalonia.Markup.Xaml/XamlIl/xamlil.github
url = https://github.com/kekekeks/XamlIl.git
url = https://github.com/kekekeks/XamlX.git

52
Avalonia.sln

@ -207,6 +207,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NativeEmbedSample", "sample
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Avalonia.Themes.Fluent", "src\Avalonia.Themes.Fluent\Avalonia.Themes.Fluent.csproj", "{C42D2FC1-A531-4ED4-84B9-89AEC7C962FC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Avalonia.Headless", "src\Avalonia.Headless\Avalonia.Headless.csproj", "{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Avalonia.Headless.Vnc", "src\Avalonia.Headless.Vnc\Avalonia.Headless.Vnc.csproj", "{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}"
EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
src\Shared\RenderHelpers\RenderHelpers.projitems*{3c4c0cb4-0c0f-4450-a37b-148c84ff905f}*SharedItemsImports = 13
@ -1826,6 +1830,54 @@ Global
{3278F3A9-9509-4A3F-A15B-BDC8B5BFF632}.Release|iPhone.Build.0 = Release|Any CPU
{3278F3A9-9509-4A3F-A15B-BDC8B5BFF632}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU
{3278F3A9-9509-4A3F-A15B-BDC8B5BFF632}.Release|iPhoneSimulator.Build.0 = Release|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Ad-Hoc|Any CPU.ActiveCfg = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Ad-Hoc|Any CPU.Build.0 = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Ad-Hoc|iPhone.ActiveCfg = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Ad-Hoc|iPhone.Build.0 = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Ad-Hoc|iPhoneSimulator.Build.0 = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.AppStore|Any CPU.ActiveCfg = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.AppStore|Any CPU.Build.0 = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.AppStore|iPhone.ActiveCfg = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.AppStore|iPhone.Build.0 = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.AppStore|iPhoneSimulator.ActiveCfg = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.AppStore|iPhoneSimulator.Build.0 = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Debug|iPhone.ActiveCfg = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Debug|iPhone.Build.0 = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Release|Any CPU.Build.0 = Release|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Release|iPhone.ActiveCfg = Release|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Release|iPhone.Build.0 = Release|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU
{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Release|iPhoneSimulator.Build.0 = Release|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Ad-Hoc|Any CPU.ActiveCfg = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Ad-Hoc|Any CPU.Build.0 = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Ad-Hoc|iPhone.ActiveCfg = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Ad-Hoc|iPhone.Build.0 = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Ad-Hoc|iPhoneSimulator.Build.0 = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.AppStore|Any CPU.ActiveCfg = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.AppStore|Any CPU.Build.0 = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.AppStore|iPhone.ActiveCfg = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.AppStore|iPhone.Build.0 = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.AppStore|iPhoneSimulator.ActiveCfg = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.AppStore|iPhoneSimulator.Build.0 = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Debug|iPhone.ActiveCfg = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Debug|iPhone.Build.0 = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Release|Any CPU.Build.0 = Release|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Release|iPhone.ActiveCfg = Release|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Release|iPhone.Build.0 = Release|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU
{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Release|iPhoneSimulator.Build.0 = Release|Any CPU
{4D55985A-1EE2-4F25-AD39-6EA8BC04F8FB}.Ad-Hoc|Any CPU.ActiveCfg = Debug|Any CPU
{4D55985A-1EE2-4F25-AD39-6EA8BC04F8FB}.Ad-Hoc|Any CPU.Build.0 = Debug|Any CPU
{4D55985A-1EE2-4F25-AD39-6EA8BC04F8FB}.Ad-Hoc|iPhone.ActiveCfg = Debug|Any CPU

4
build/HarfBuzzSharp.props

@ -1,6 +1,6 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<PackageReference Include="HarfBuzzSharp" Version="2.6.1" />
<PackageReference Condition="'$(IncludeLinuxSkia)' == 'true'" Include="HarfBuzzSharp.NativeAssets.Linux" Version="2.6.1" />
<PackageReference Include="HarfBuzzSharp" Version="2.6.1.5" />
<PackageReference Condition="'$(IncludeLinuxSkia)' == 'true'" Include="HarfBuzzSharp.NativeAssets.Linux" Version="2.6.1.5" />
</ItemGroup>
</Project>

4
build/SkiaSharp.props

@ -1,6 +1,6 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<PackageReference Include="SkiaSharp" Version="1.68.2.1" />
<PackageReference Condition="'$(IncludeLinuxSkia)' == 'true'" Include="SkiaSharp.NativeAssets.Linux" Version="1.68.2.1" />
<PackageReference Include="SkiaSharp" Version="2.80.0" />
<PackageReference Condition="'$(IncludeLinuxSkia)' == 'true'" Include="SkiaSharp.NativeAssets.Linux" Version="2.80.0" />
</ItemGroup>
</Project>

13
native/Avalonia.Native/inc/avalonia-native.h

@ -205,6 +205,15 @@ enum AvnMenuItemToggleType
Radio
};
enum AvnExtendClientAreaChromeHints
{
AvnNoChrome = 0,
AvnSystemChrome = 0x01,
AvnPreferSystemChrome = 0x02,
AvnOSXThickTitleBar = 0x08,
AvnDefaultChrome = AvnSystemChrome,
};
AVNCOM(IAvaloniaNativeFactory, 01) : IUnknown
{
public:
@ -279,6 +288,10 @@ AVNCOM(IAvnWindow, 04) : virtual IAvnWindowBase
virtual HRESULT SetWindowState(AvnWindowState state) = 0;
virtual HRESULT GetWindowState(AvnWindowState*ret) = 0;
virtual HRESULT TakeFocusFromChildren() = 0;
virtual HRESULT SetExtendClientArea (bool enable) = 0;
virtual HRESULT SetExtendClientAreaHints (AvnExtendClientAreaChromeHints hints) = 0;
virtual HRESULT GetExtendTitleBarHeight (double*ret) = 0;
virtual HRESULT SetExtendTitleBarHeight (double value) = 0;
};
AVNCOM(IAvnWindowBaseEvents, 05) : IUnknown

13
native/Avalonia.Native/src/OSX/window.h

@ -3,9 +3,6 @@
class WindowBaseImpl;
@interface AutoFitContentVisualEffectView : NSVisualEffectView
@end
@interface AvnView : NSView<NSTextInputClient, NSDraggingDestination>
-(AvnView* _Nonnull) initWithParent: (WindowBaseImpl* _Nonnull) parent;
-(NSEvent* _Nonnull) lastMouseDownEvent;
@ -15,6 +12,14 @@ class WindowBaseImpl;
-(AvnPixelSize) getPixelSize;
@end
@interface AutoFitContentView : NSView
-(AutoFitContentView* _Nonnull) initWithContent: (NSView* _Nonnull) content;
-(void) ShowTitleBar: (bool) show;
-(void) SetTitleBarHeightHint: (double) height;
-(void) SetContent: (NSView* _Nonnull) content;
-(void) ShowBlur: (bool) show;
@end
@interface AvnWindow : NSWindow <NSWindowDelegate>
+(void) closeAll;
-(AvnWindow* _Nonnull) initWithParent: (WindowBaseImpl* _Nonnull) parent;
@ -27,6 +32,8 @@ class WindowBaseImpl;
-(void) showWindowMenuWithAppMenu;
-(void) applyMenu:(NSMenu* _Nullable)menu;
-(double) getScaling;
-(double) getExtendedTitleBarHeight;
-(void) setIsExtended:(bool)value;
@end
struct INSWindowHolder

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

@ -6,8 +6,6 @@
#include <OpenGL/gl.h>
#include "rendertarget.h"
class WindowBaseImpl : public virtual ComSingleObject<IAvnWindowBase, &IID_IAvnWindowBase>, public INSWindowHolder
{
private:
@ -20,7 +18,7 @@ public:
View = NULL;
Window = NULL;
}
NSVisualEffectView* VisualEffect;
AutoFitContentView* StandardContainer;
AvnView* View;
AvnWindow* Window;
ComPtr<IAvnWindowBaseEvents> BaseEvents;
@ -39,6 +37,7 @@ public:
_glContext = gl;
renderTarget = [[IOSurfaceRenderTarget alloc] initWithOpenGlContext: gl];
View = [[AvnView alloc] initWithParent:this];
StandardContainer = [[AutoFitContentView new] initWithContent:View];
Window = [[AvnWindow alloc] initWithParent:this];
@ -49,12 +48,8 @@ public:
[Window setStyleMask:NSWindowStyleMaskBorderless];
[Window setBackingType:NSBackingStoreBuffered];
VisualEffect = [AutoFitContentVisualEffectView new];
[VisualEffect setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
[VisualEffect setMaterial:NSVisualEffectMaterialLight];
[VisualEffect setAutoresizesSubviews:true];
[Window setContentView: View];
[Window setOpaque:false];
[Window setContentView: StandardContainer];
}
virtual HRESULT ObtainNSWindowHandle(void** ret) override
@ -410,12 +405,7 @@ public:
virtual HRESULT SetBlurEnabled (bool enable) override
{
[Window setContentView: enable ? VisualEffect : View];
if(enable)
{
[VisualEffect addSubview:View];
}
[StandardContainer ShowBlur:enable];
return S_OK;
}
@ -492,6 +482,8 @@ private:
bool _inSetWindowState;
NSRect _preZoomSize;
bool _transitioningWindowState;
bool _isClientAreaExtended;
AvnExtendClientAreaChromeHints _extendClientHints;
FORWARD_IUNKNOWN()
BEGIN_INTERFACE_MAP()
@ -505,6 +497,8 @@ private:
ComPtr<IAvnWindowEvents> WindowEvents;
WindowImpl(IAvnWindowEvents* events, IAvnGlContext* gl) : WindowBaseImpl(events, gl)
{
_isClientAreaExtended = false;
_extendClientHints = AvnDefaultChrome;
_fullScreenActive = false;
_canResize = true;
_decorations = SystemDecorationsFull;
@ -523,8 +517,20 @@ private:
if ([subview isKindOfClass:NSClassFromString(@"NSTitlebarContainerView")]) {
NSView *titlebarView = [subview subviews][0];
for (id button in titlebarView.subviews) {
if ([button isKindOfClass:[NSButton class]]) {
[button setHidden: (_decorations != SystemDecorationsFull)];
if ([button isKindOfClass:[NSButton class]])
{
if(_isClientAreaExtended)
{
auto wantsChrome = (_extendClientHints & AvnSystemChrome) || (_extendClientHints & AvnPreferSystemChrome);
[button setHidden: !wantsChrome];
}
else
{
[button setHidden: (_decorations != SystemDecorationsFull)];
}
[button setWantsLayer:true];
}
}
}
@ -600,6 +606,35 @@ private:
if(_lastWindowState != state)
{
if(_isClientAreaExtended)
{
if(_lastWindowState == FullScreen)
{
// we exited fs.
if(_extendClientHints & AvnOSXThickTitleBar)
{
Window.toolbar = [NSToolbar new];
Window.toolbar.showsBaselineSeparator = false;
}
[Window setTitlebarAppearsTransparent:true];
[StandardContainer setFrameSize: StandardContainer.frame.size];
}
else if(state == FullScreen)
{
// we entered fs.
if(_extendClientHints & AvnOSXThickTitleBar)
{
Window.toolbar = nullptr;
}
[Window setTitlebarAppearsTransparent:false];
[StandardContainer setFrameSize: StandardContainer.frame.size];
}
}
_lastWindowState = state;
WindowEvents->WindowStateChanged(state);
}
@ -656,8 +691,6 @@ private:
return S_OK;
}
auto currentFrame = [Window frame];
UpdateStyle();
HideOrShowTrafficLights();
@ -790,6 +823,81 @@ private:
return S_OK;
if([Window isKeyWindow])
[Window makeFirstResponder: View];
return S_OK;
}
virtual HRESULT SetExtendClientArea (bool enable) override
{
_isClientAreaExtended = enable;
if(enable)
{
Window.titleVisibility = NSWindowTitleHidden;
[Window setTitlebarAppearsTransparent:true];
auto wantsTitleBar = (_extendClientHints & AvnSystemChrome) || (_extendClientHints & AvnPreferSystemChrome);
if (wantsTitleBar)
{
[StandardContainer ShowTitleBar:true];
}
else
{
[StandardContainer ShowTitleBar:false];
}
if(_extendClientHints & AvnOSXThickTitleBar)
{
Window.toolbar = [NSToolbar new];
Window.toolbar.showsBaselineSeparator = false;
}
else
{
Window.toolbar = nullptr;
}
}
else
{
Window.titleVisibility = NSWindowTitleVisible;
Window.toolbar = nullptr;
[Window setTitlebarAppearsTransparent:false];
View.layer.zPosition = 0;
}
[Window setIsExtended:enable];
HideOrShowTrafficLights();
UpdateStyle();
return S_OK;
}
virtual HRESULT SetExtendClientAreaHints (AvnExtendClientAreaChromeHints hints) override
{
_extendClientHints = hints;
SetExtendClientArea(_isClientAreaExtended);
return S_OK;
}
virtual HRESULT GetExtendTitleBarHeight (double*ret) override
{
if(ret == nullptr)
{
return E_POINTER;
}
*ret = [Window getExtendedTitleBarHeight];
return S_OK;
}
virtual HRESULT SetExtendTitleBarHeight (double value) override
{
[StandardContainer SetTitleBarHeightHint:value];
return S_OK;
}
@ -802,8 +910,9 @@ private:
[Window setTitlebarAppearsTransparent:NO];
[Window setTitle:_lastTitle];
[Window setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskResizable];
Window.styleMask = Window.styleMask | NSWindowStyleMaskTitled | NSWindowStyleMaskResizable;
Window.styleMask = Window.styleMask & ~NSWindowStyleMaskFullSizeContentView;
[Window toggleFullScreen:nullptr];
}
@ -951,19 +1060,120 @@ protected:
{
s |= NSWindowStyleMaskMiniaturizable;
}
if(_isClientAreaExtended)
{
s |= NSWindowStyleMaskFullSizeContentView | NSWindowStyleMaskTexturedBackground;
}
return s;
}
};
NSArray* AllLoopModes = [NSArray arrayWithObjects: NSDefaultRunLoopMode, NSEventTrackingRunLoopMode, NSModalPanelRunLoopMode, NSRunLoopCommonModes, NSConnectionReplyMode, nil];
@implementation AutoFitContentVisualEffectView
@implementation AutoFitContentView
{
NSVisualEffectView* _titleBarMaterial;
NSBox* _titleBarUnderline;
NSView* _content;
NSVisualEffectView* _blurBehind;
double _titleBarHeightHint;
bool _settingSize;
}
-(AutoFitContentView* _Nonnull) initWithContent:(NSView *)content
{
_titleBarHeightHint = -1;
_content = content;
_settingSize = false;
[self setAutoresizesSubviews:true];
[self setWantsLayer:true];
_titleBarMaterial = [NSVisualEffectView new];
[_titleBarMaterial setBlendingMode:NSVisualEffectBlendingModeWithinWindow];
[_titleBarMaterial setMaterial:NSVisualEffectMaterialTitlebar];
[_titleBarMaterial setWantsLayer:true];
_titleBarMaterial.hidden = true;
_titleBarUnderline = [NSBox new];
_titleBarUnderline.boxType = NSBoxSeparator;
_titleBarUnderline.fillColor = [NSColor underPageBackgroundColor];
_titleBarUnderline.hidden = true;
[self addSubview:_titleBarMaterial];
[self addSubview:_titleBarUnderline];
_blurBehind = [NSVisualEffectView new];
[_blurBehind setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
[_blurBehind setMaterial:NSVisualEffectMaterialLight];
[_blurBehind setWantsLayer:true];
_blurBehind.hidden = true;
[self addSubview:_blurBehind];
[self addSubview:_content];
[self setWantsLayer:true];
return self;
}
-(void) ShowBlur:(bool)show
{
_blurBehind.hidden = !show;
}
-(void) ShowTitleBar: (bool) show
{
_titleBarMaterial.hidden = !show;
_titleBarUnderline.hidden = !show;
}
-(void) SetTitleBarHeightHint: (double) height
{
_titleBarHeightHint = height;
[self setFrameSize:self.frame.size];
}
-(void)setFrameSize:(NSSize)newSize
{
[super setFrameSize:newSize];
if([[self subviews] count] == 0)
if(_settingSize)
{
return;
[[self subviews][0] setFrameSize: newSize];
}
_settingSize = true;
[super setFrameSize:newSize];
[_blurBehind setFrameSize:newSize];
[_content setFrameSize:newSize];
auto window = objc_cast<AvnWindow>([self window]);
// TODO get actual titlebar size
double height = _titleBarHeightHint == -1 ? [window getExtendedTitleBarHeight] : _titleBarHeightHint;
NSRect tbar;
tbar.origin.x = 0;
tbar.origin.y = newSize.height - height;
tbar.size.width = newSize.width;
tbar.size.height = height;
[_titleBarMaterial setFrame:tbar];
tbar.size.height = height < 1 ? 0 : 1;
[_titleBarUnderline setFrame:tbar];
_settingSize = false;
}
-(void) SetContent: (NSView* _Nonnull) content
{
if(content != nullptr)
{
[content removeFromSuperview];
[self addSubview:content];
_content = content;
}
}
@end
@ -1523,15 +1733,43 @@ NSArray* AllLoopModes = [NSArray arrayWithObjects: NSDefaultRunLoopMode, NSEvent
bool _canBecomeKeyAndMain;
bool _closed;
bool _isEnabled;
bool _isExtended;
AvnMenu* _menu;
double _lastScaling;
}
-(void) setIsExtended:(bool)value;
{
_isExtended = value;
}
-(double) getScaling
{
return _lastScaling;
}
-(double) getExtendedTitleBarHeight
{
if(_isExtended)
{
for (id subview in self.contentView.superview.subviews)
{
if ([subview isKindOfClass:NSClassFromString(@"NSTitlebarContainerView")])
{
NSView *titlebarView = [subview subviews][0];
return (double)titlebarView.frame.size.height;
}
}
return -1;
}
else
{
return 0;
}
}
+(void)closeAll
{
NSArray<NSWindow*>* windows = [NSArray arrayWithArray:[NSApp windows]];
@ -1650,6 +1888,7 @@ NSArray* AllLoopModes = [NSArray arrayWithObjects: NSDefaultRunLoopMode, NSEvent
[self setOpaque:NO];
[self setBackgroundColor: [NSColor clearColor]];
[self invalidateShadow];
_isExtended = false;
return self;
}

2
nukebuild/Build.cs

@ -268,6 +268,8 @@ partial class Build : NukeBuild
.DependsOn(CreateIntermediateNugetPackages)
.Executes(() =>
{
BuildTasksPatcher.PatchBuildTasksInPackage(Parameters.NugetIntermediateRoot / "Avalonia.Build.Tasks." +
Parameters.Version + ".nupkg");
var config = Numerge.MergeConfiguration.LoadFile(RootDirectory / "nukebuild" / "numerge.config");
EnsureCleanDirectory(Parameters.NugetRoot);
if(!Numerge.NugetPackageMerger.Merge(Parameters.NugetIntermediateRoot, Parameters.NugetRoot, config,

76
nukebuild/BuildTasksPatcher.cs

@ -0,0 +1,76 @@
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using ILRepacking;
using Mono.Cecil;
public class BuildTasksPatcher
{
public static void PatchBuildTasksInPackage(string packagePath)
{
using (var archive = new ZipArchive(File.Open(packagePath, FileMode.Open, FileAccess.ReadWrite),
ZipArchiveMode.Update))
{
foreach (var entry in archive.Entries.ToList())
{
if (entry.Name == "Avalonia.Build.Tasks.dll")
{
var temp = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".dll");
var output = temp + ".output";
var patched = new MemoryStream();
try
{
entry.ExtractToFile(temp, true);
var repack = new ILRepacking.ILRepack(new RepackOptions()
{
Internalize = true,
InputAssemblies = new[]
{
temp, typeof(Mono.Cecil.AssemblyDefinition).Assembly.GetModules()[0]
.FullyQualifiedName
},
SearchDirectories = new string[0],
OutputFile = output
});
repack.Repack();
// 'hurr-durr assembly with the same name is already loaded' prevention
using (var asm = AssemblyDefinition.ReadAssembly(output,
new ReaderParameters { ReadWrite = true, InMemory = true, }))
{
asm.Name = new AssemblyNameDefinition(
"Avalonia.Build.Tasks."
+ Guid.NewGuid().ToString().Replace("-", ""),
new Version(0, 0, 0));
asm.Write(patched);
patched.Position = 0;
}
}
finally
{
try
{
if (File.Exists(temp))
File.Delete(temp);
if (File.Exists(output))
File.Delete(output);
}
catch
{
//ignore
}
}
var fn = entry.FullName;
entry.Delete();
var newEntry = archive.CreateEntry(fn, CompressionLevel.Optimal);
using (var s = newEntry.Open())
patched.CopyTo(s);
}
}
}
}
}

3
nukebuild/_build.csproj

@ -14,6 +14,9 @@
<PackageReference Include="xunit.runner.console" Version="2.3.1" />
<PackageReference Include="JetBrains.dotMemoryUnit" Version="3.0.20171219.105559" />
<PackageReference Include="vswhere" Version="2.6.7" Condition=" '$(OS)' == 'Windows_NT' " />
<PackageReference Include="ILRepack.NETStandard" Version="2.0.4" />
<!-- Keep in sync with Avalonia.Build.Tasks -->
<PackageReference Include="Avalonia.Unofficial.Cecil" Version="20190417.2.0" />
</ItemGroup>
<ItemGroup>

2
readme.md

@ -16,7 +16,7 @@ To see the status of some of our features, please see our [Roadmap](https://gith
## 🚀 Getting Started
The Avalonia [Visual Studio Extension](https://marketplace.visualstudio.com/items?itemName=AvaloniaTeam.AvaloniaforVisualStudio) contains project and control templates that will help you get started, or you can use the .NET Core CLI. For a starer guide see our [documentation](http://avaloniaui.net/docs/quickstart/create-new-project).
The Avalonia [Visual Studio Extension](https://marketplace.visualstudio.com/items?itemName=AvaloniaTeam.AvaloniaforVisualStudio) contains project and control templates that will help you get started, or you can use the .NET Core CLI. For a starter guide see our [documentation](http://avaloniaui.net/docs/quickstart/create-new-project).
Avalonia is delivered via <b>NuGet</b> package manager. You can find the packages here: https://www.nuget.org/packages/Avalonia/

5
samples/BindingDemo/MainWindow.xaml

@ -5,7 +5,8 @@
xmlns:local="clr-namespace:BindingDemo"
Title="AvaloniaUI Bindings Test"
Width="800"
Height="600">
Height="600"
x:DataType="vm:MainWindowViewModel">
<Window.Styles>
<Style Selector="TextBlock.h1">
<Setter Property="FontSize" Value="18"/>
@ -60,7 +61,7 @@
<TextBlock FontSize="16" Text="Scheduler"/>
<TextBox Watermark="Background Thread" Text="{Binding CurrentTime, Mode=OneWay}"/>
<TextBlock FontSize="16" Text="Stream Operator"/>
<TextBox Watermark="StreamOperator" Text="{Binding CurrentTimeObservable^, Mode=OneWay}"/>
<TextBox Watermark="StreamOperator" Text="{CompiledBinding CurrentTimeObservable^, Mode=OneWay}"/>
</StackPanel>
</StackPanel>
</StackPanel>

4
samples/BindingDemo/ViewModels/MainWindowViewModel.cs

@ -53,7 +53,7 @@ namespace BindingDemo.ViewModels
});
CurrentTimeObservable = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(1))
.Select(x => DateTimeOffset.Now.ToString());
.Select(x => DateTimeOffset.Now);
}
public ObservableCollection<TestItem> Items { get; }
@ -90,7 +90,7 @@ namespace BindingDemo.ViewModels
private set { this.RaiseAndSetIfChanged(ref _currentTime, value); }
}
public IObservable<string> CurrentTimeObservable { get; }
public IObservable<DateTimeOffset> CurrentTimeObservable { get; }
public ReactiveCommand<object, Unit> StringValueCommand { get; }
public DataAnnotationsErrorViewModel DataAnnotationsValidation { get; } = new DataAnnotationsErrorViewModel();

3
samples/ControlCatalog.NetCore/ControlCatalog.NetCore.csproj

@ -7,12 +7,13 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Avalonia.Headless.Vnc\Avalonia.Headless.Vnc.csproj" />
<ProjectReference Include="..\..\src\Avalonia.Dialogs\Avalonia.Dialogs.csproj" />
<ProjectReference Include="..\..\src\Linux\Avalonia.LinuxFramebuffer\Avalonia.LinuxFramebuffer.csproj" />
<ProjectReference Include="..\ControlCatalog\ControlCatalog.csproj" />
<ProjectReference Include="..\..\src\Avalonia.Desktop\Avalonia.Desktop.csproj" />
<ProjectReference Include="..\..\src\Avalonia.X11\Avalonia.X11.csproj" />
<PackageReference Include="Avalonia.Angle.Windows.Natives" Version="2.1.0.2019013001"/>
<PackageReference Include="Avalonia.Angle.Windows.Natives" Version="2.1.0.2019013001" />
</ItemGroup>

55
samples/ControlCatalog.NetCore/Program.cs

@ -3,9 +3,16 @@ using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Dialogs;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Headless;
using Avalonia.LogicalTree;
using Avalonia.Skia;
using Avalonia.ReactiveUI;
using Avalonia.Threading;
using Avalonia.Dialogs;
namespace ControlCatalog.NetCore
{
@ -40,6 +47,52 @@ namespace ControlCatalog.NetCore
SilenceConsole();
return builder.StartLinuxFbDev(args, scaling: GetScaling());
}
else if (args.Contains("--vnc"))
{
return builder.StartWithHeadlessVncPlatform(null, 5901, args, ShutdownMode.OnMainWindowClose);
}
else if (args.Contains("--full-headless"))
{
return builder
.UseHeadless(true)
.AfterSetup(_ =>
{
DispatcherTimer.RunOnce(async () =>
{
var window = ((IClassicDesktopStyleApplicationLifetime)Application.Current.ApplicationLifetime)
.MainWindow;
var tc = window.GetLogicalDescendants().OfType<TabControl>().First();
foreach (var page in tc.Items.Cast<TabItem>().ToList())
{
// Skip DatePicker because of some layout bug in grid
if (page.Header.ToString() == "DatePicker")
continue;
Console.WriteLine("Selecting " + page.Header);
tc.SelectedItem = page;
await Task.Delay(500);
}
Console.WriteLine("Selecting the first page");
tc.SelectedItem = tc.Items.OfType<object>().First();
await Task.Delay(500);
Console.WriteLine("Clicked through all pages, triggering GC");
for (var c = 0; c < 3; c++)
{
GC.Collect(2, GCCollectionMode.Forced);
await Task.Delay(500);
}
void FormatMem(string metric, long bytes)
{
Console.WriteLine(metric + ": " + bytes / 1024 / 1024 + "MB");
}
FormatMem("GC allocated bytes", GC.GetTotalMemory(true));
FormatMem("WorkingSet64", Process.GetCurrentProcess().WorkingSet64);
}, TimeSpan.FromSeconds(1));
})
.StartWithClassicDesktopLifetime(args);
}
else if (args.Contains("--drm"))
{
SilenceConsole();

16
samples/ControlCatalog/App.xaml.cs

@ -11,25 +11,17 @@ namespace ControlCatalog
{
public static Styles FluentDark = new Styles
{
new StyleInclude(new Uri("resm:Styles?assembly=ControlCatalog"))
{
Source = new Uri("resm:Avalonia.Themes.Default.Accents.BaseDark.xaml?assembly=Avalonia.Themes.Default")
},
new StyleInclude(new Uri("resm:Styles?assembly=ControlCatalog"))
new StyleInclude(new Uri("avares://ControlCatalog/Styles"))
{
Source = new Uri("resm:Avalonia.Themes.Fluent.Accents.FluentDark.xaml?assembly=Avalonia.Themes.Fluent")
Source = new Uri("avares://Avalonia.Themes.Fluent/Accents/FluentDark.xaml")
},
};
public static Styles FluentLight = new Styles
{
new StyleInclude(new Uri("resm:Styles?assembly=ControlCatalog"))
{
Source = new Uri("resm:Avalonia.Themes.Default.Accents.BaseLight.xaml?assembly=Avalonia.Themes.Default")
},
new StyleInclude(new Uri("resm:Styles?assembly=ControlCatalog"))
new StyleInclude(new Uri("avares://ControlCatalog/Styles"))
{
Source = new Uri("resm:Avalonia.Themes.Fluent.Accents.FluentLight.xaml?assembly=Avalonia.Themes.Fluent")
Source = new Uri("avares://Avalonia.Themes.Fluent/Accents/FluentLight.xaml")
},
};

7
samples/ControlCatalog/MainView.xaml

@ -2,7 +2,7 @@
xmlns:pages="clr-namespace:ControlCatalog.Pages"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ControlCatalog.MainView"
Background="Transparent"
Background="Black"
Foreground="{DynamicResource ThemeForegroundBrush}"
FontSize="{DynamicResource FontSizeNormal}">
<Grid>
@ -14,6 +14,7 @@
</Style>
</Grid.Styles>
<TabControl Classes="sidebar" Name="Sidebar">
<TabItem Header="Acrylic"><pages:AcrylicPage/></TabItem>
<TabItem Header="AutoCompleteBox"><pages:AutoCompleteBoxPage/></TabItem>
<TabItem Header="Border"><pages:BorderPage/></TabItem>
<TabItem Header="Button"><pages:ButtonPage/></TabItem>
@ -55,6 +56,7 @@
<TabItem Header="Pointers (Touch)"><pages:PointersPage/></TabItem>
<TabItem Header="ProgressBar"><pages:ProgressBarPage/></TabItem>
<TabItem Header="RadioButton"><pages:RadioButtonPage/></TabItem>
<TabItem Header="RelativePanel"><pages:RelativePanelPage/></TabItem>
<TabItem Header="ScrollViewer"><pages:ScrollViewerPage/></TabItem>
<TabItem Header="Slider"><pages:SliderPage/></TabItem>
<TabItem Header="SplitView"><pages:SplitViewPage/></TabItem>
@ -66,6 +68,7 @@
<TabItem Header="ToolTip"><pages:ToolTipPage/></TabItem>
<TabItem Header="TreeView"><pages:TreeViewPage/></TabItem>
<TabItem Header="Viewbox"><pages:ViewboxPage/></TabItem>
<TabItem Header="Window Customizations"><pages:WindowCustomizationsPage/></TabItem>
<TabControl.Tag>
<StackPanel Width="115" Spacing="4" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="8">
<ComboBox x:Name="Decorations" SelectedIndex="0">
@ -79,7 +82,7 @@
<ComboBoxItem>Simple - Light</ComboBoxItem>
<ComboBoxItem>Simple - Dark</ComboBoxItem>
</ComboBox>
<ComboBox x:Name="TransparencyLevels" SelectedIndex="0">
<ComboBox x:Name="TransparencyLevels" SelectedIndex="{Binding TransparencyLevel}">
<ComboBoxItem>None</ComboBoxItem>
<ComboBoxItem>Transparent</ComboBoxItem>
<ComboBoxItem>Blur</ComboBoxItem>

7
samples/ControlCatalog/MainView.xaml.cs

@ -58,13 +58,6 @@ namespace ControlCatalog
if (VisualRoot is Window window)
window.SystemDecorations = (SystemDecorations)decorations.SelectedIndex;
};
var transparencyLevels = this.Find<ComboBox>("TransparencyLevels");
transparencyLevels.SelectionChanged += (sender, e) =>
{
if (VisualRoot is Window window)
window.TransparencyLevelHint = (WindowTransparencyLevel)transparencyLevels.SelectedIndex;
};
}
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)

41
samples/ControlCatalog/MainWindow.xaml

@ -7,7 +7,12 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:ControlCatalog.ViewModels"
xmlns:v="clr-namespace:ControlCatalog.Views"
x:Class="ControlCatalog.MainWindow" WindowState="{Binding WindowState, Mode=TwoWay}" Background="{DynamicResource SystemControlPageBackgroundAltHighBrush}">
ExtendClientAreaToDecorationsHint="{Binding ExtendClientAreaEnabled}"
ExtendClientAreaChromeHints="{Binding ChromeHints}"
ExtendClientAreaTitleBarHeightHint="{Binding TitleBarHeight}"
TransparencyLevelHint="{Binding TransparencyLevel}"
x:Name="MainWindow"
x:Class="ControlCatalog.MainWindow" WindowState="{Binding WindowState, Mode=TwoWay}">
<NativeMenu.Menu>
<NativeMenu>
<NativeMenuItem Header="File">
@ -56,20 +61,30 @@
</NativeMenu>
</NativeMenu.Menu>
<Window.DataTemplates>
<Window.DataTemplates>
<DataTemplate DataType="vm:NotificationViewModel">
<v:CustomNotificationView />
</DataTemplate>
</Window.DataTemplates>
<DockPanel LastChildFill="True">
<Menu Name="MainMenu" DockPanel.Dock="Top">
<MenuItem Header="File">
<MenuItem Header="Exit" Command="{Binding ExitCommand}" />
</MenuItem>
<MenuItem Header="Help">
<MenuItem Header="About" Command="{Binding AboutCommand}" />
</MenuItem>
</Menu>
<local:MainView />
</DockPanel>
<Panel>
<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>
<MenuItem Header="Help">
<MenuItem Header="About" Command="{Binding AboutCommand}" />
</MenuItem>
</Menu>
<local:MainView />
</DockPanel>
</Panel>
<Border IsVisible="{Binding ExtendClientAreaEnabled}" BorderThickness="1 1 1 0" CornerRadius="4 4 0 0" BorderBrush="#55000000" Height="22" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="250 8 0 0">
<Border.Background>
<SolidColorBrush Color="White" Opacity="0.7" />
</Border.Background>
<TextBlock Margin="5 5 5 0" Text="Content In Title Bar" />
</Border>
</Panel>
</Window>

139
samples/ControlCatalog/Pages/AcrylicPage.xaml

@ -0,0 +1,139 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="ControlCatalog.Pages.AcrylicPage">
<Border Padding="20" HorizontalAlignment="Center">
<StackPanel Spacing="20">
<ExperimentalAcrylicBorder Width="660" CornerRadius="5">
<ExperimentalAcrylicBorder.Material>
<ExperimentalAcrylicMaterial
TintColor="White"
BackgroundSource="Digger" />
</ExperimentalAcrylicBorder.Material>
<StackPanel Spacing="5" Margin="40 10">
<StackPanel Orientation="Horizontal">
<TextBlock Text="TintOpacity" Foreground="Black" />
<Slider Name="TintOpacitySlider" Minimum="0" Maximum="1" Value="0.9" Width="400" />
<TextBlock Text="{Binding #TintOpacitySlider.Value}" Foreground="Black" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="MaterialOpacity" Foreground="Black" />
<Slider Name="MaterialOpacitySlider" Minimum="0" Maximum="1" Value="0.8" Width="400" />
<TextBlock Text="{Binding #MaterialOpacitySlider.Value}" Foreground="Black" />
</StackPanel>
</StackPanel>
</ExperimentalAcrylicBorder>
<StackPanel Orientation="Horizontal" Spacing="20">
<ExperimentalAcrylicBorder Height="200" Width="200" CornerRadius="5">
<ExperimentalAcrylicBorder.Material>
<ExperimentalAcrylicMaterial
TintColor="#FF0000"
TintOpacity="{Binding #TintOpacitySlider.Value}"
MaterialOpacity="{Binding #MaterialOpacitySlider.Value}"
BackgroundSource="Digger" />
</ExperimentalAcrylicBorder.Material>
</ExperimentalAcrylicBorder>
<ExperimentalAcrylicBorder Height="200" Width="200" CornerRadius="5">
<ExperimentalAcrylicBorder.Material>
<ExperimentalAcrylicMaterial
TintColor="#00FF00"
TintOpacity="{Binding #TintOpacitySlider.Value}"
MaterialOpacity="{Binding #MaterialOpacitySlider.Value}"
BackgroundSource="Digger" />
</ExperimentalAcrylicBorder.Material>
</ExperimentalAcrylicBorder>
<ExperimentalAcrylicBorder Height="200" Width="200" CornerRadius="5">
<ExperimentalAcrylicBorder.Material>
<ExperimentalAcrylicMaterial
TintColor="#000000"
TintOpacity="{Binding #TintOpacitySlider.Value}"
MaterialOpacity="{Binding #MaterialOpacitySlider.Value}"
BackgroundSource="Digger" />
</ExperimentalAcrylicBorder.Material>
</ExperimentalAcrylicBorder>
</StackPanel>
<StackPanel Orientation="Horizontal" Spacing="20">
<ExperimentalAcrylicBorder Height="200" Width="200" CornerRadius="5">
<ExperimentalAcrylicBorder.Material>
<ExperimentalAcrylicMaterial
TintColor="#0000FF"
TintOpacity="{Binding #TintOpacitySlider.Value}"
MaterialOpacity="{Binding #MaterialOpacitySlider.Value}"
BackgroundSource="Digger" />
</ExperimentalAcrylicBorder.Material>
</ExperimentalAcrylicBorder>
<ExperimentalAcrylicBorder Height="200" Width="200" CornerRadius="5">
<ExperimentalAcrylicBorder.Material>
<ExperimentalAcrylicMaterial
TintColor="#FFFF00"
TintOpacity="{Binding #TintOpacitySlider.Value}"
MaterialOpacity="{Binding #MaterialOpacitySlider.Value}"
BackgroundSource="Digger" />
</ExperimentalAcrylicBorder.Material>
</ExperimentalAcrylicBorder>
<ExperimentalAcrylicBorder Height="200" Width="200" CornerRadius="5">
<ExperimentalAcrylicBorder.Material>
<ExperimentalAcrylicMaterial
TintColor="#000000"
TintOpacity="{Binding #TintOpacitySlider.Value}"
MaterialOpacity="{Binding #MaterialOpacitySlider.Value}"
BackgroundSource="Digger" />
</ExperimentalAcrylicBorder.Material>
</ExperimentalAcrylicBorder>
</StackPanel>
<StackPanel Orientation="Horizontal" Spacing="20">
<ExperimentalAcrylicBorder Height="200" Width="200" CornerRadius="5">
<ExperimentalAcrylicBorder.Material>
<ExperimentalAcrylicMaterial
TintColor="White"
TintOpacity="{Binding #TintOpacitySlider.Value}"
MaterialOpacity="{Binding #MaterialOpacitySlider.Value}"
BackgroundSource="Digger" />
</ExperimentalAcrylicBorder.Material>
</ExperimentalAcrylicBorder>
<ExperimentalAcrylicBorder Height="200" Width="200" CornerRadius="5">
<ExperimentalAcrylicBorder.Material>
<ExperimentalAcrylicMaterial
TintColor="#3c3c3c"
TintOpacity="{Binding #TintOpacitySlider.Value}"
MaterialOpacity="{Binding #MaterialOpacitySlider.Value}"
BackgroundSource="Digger" />
</ExperimentalAcrylicBorder.Material>
</ExperimentalAcrylicBorder>
<ExperimentalAcrylicBorder Height="200" Width="200" CornerRadius="5">
<ExperimentalAcrylicBorder.Material>
<ExperimentalAcrylicMaterial
TintColor="White"
TintOpacity="{Binding #TintOpacitySlider.Value}"
MaterialOpacity="{Binding #MaterialOpacitySlider.Value}"
BackgroundSource="Digger" />
</ExperimentalAcrylicBorder.Material>
</ExperimentalAcrylicBorder>
</StackPanel>
<ExperimentalAcrylicBorder Height="200" Width="660" CornerRadius="5">
<ExperimentalAcrylicBorder.Material>
<ExperimentalAcrylicMaterial
TintColor="Red"
TintOpacity="{Binding #TintOpacitySlider.Value}"
MaterialOpacity="{Binding #MaterialOpacitySlider.Value}"
BackgroundSource="Digger" />
</ExperimentalAcrylicBorder.Material>
</ExperimentalAcrylicBorder>
</StackPanel>
</Border>
</UserControl>

19
samples/ControlCatalog/Pages/AcrylicPage.xaml.cs

@ -0,0 +1,19 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace ControlCatalog.Pages
{
public class AcrylicPage : UserControl
{
public AcrylicPage()
{
this.InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}

12
samples/ControlCatalog/Pages/BorderPage.xaml

@ -9,27 +9,27 @@
Margin="0,16,0,0"
HorizontalAlignment="Center"
Spacing="16">
<Border BorderBrush="{DynamicResource ThemeAccentBrush}" BorderThickness="2" Padding="16">
<Border BorderBrush="{DynamicResource SystemAccentColor}" BorderThickness="2" Padding="16">
<TextBlock>Border</TextBlock>
</Border>
<Border Background="{DynamicResource ThemeAccentBrush2}"
BorderBrush="{DynamicResource ThemeAccentBrush}"
<Border Background="{DynamicResource SystemAccentColorDark1}"
BorderBrush="{DynamicResource SystemAccentColor}"
BorderThickness="4"
Padding="16">
<TextBlock>Border and Background</TextBlock>
</Border>
<Border BorderBrush="{DynamicResource ThemeAccentBrush}"
<Border BorderBrush="{DynamicResource SystemAccentColor}"
BorderThickness="4"
CornerRadius="8"
Padding="16">
<TextBlock>Rounded Corners</TextBlock>
</Border>
<Border Background="{DynamicResource ThemeAccentBrush2}"
<Border Background="{DynamicResource SystemAccentColor}"
CornerRadius="8"
Padding="16">
<TextBlock>Rounded Corners</TextBlock>
</Border>
<Border BorderBrush="{DynamicResource ThemeAccentBrush2}" Width="100" Height="100"
<Border Width="100" Height="100"
BorderThickness="0"
Background="White"
CornerRadius="100" ClipToBounds="True">

14
samples/ControlCatalog/Pages/ButtonPage.xaml

@ -9,10 +9,10 @@
Margin="0,16,0,0"
HorizontalAlignment="Center"
Spacing="16">
<StackPanel Orientation="Vertical" Spacing="8" Width="150">
<Button>Button</Button>
<StackPanel Orientation="Vertical" Spacing="8" Width="200">
<Button>Standard XAML Button</Button>
<Button Foreground="White">Foreground</Button>
<Button Background="{DynamicResource ThemeAccentBrush}">Background</Button>
<Button Background="{DynamicResource SystemAccentColor}">Background</Button>
<Button IsEnabled="False">Disabled</Button>
<Button Content="Re-themed">
<Button.Styles>
@ -32,10 +32,10 @@
<StackPanel Orientation="Vertical" Spacing="8" Width="150">
<Button BorderThickness="0">No Border</Button>
<Button BorderBrush="{DynamicResource ThemeAccentBrush}">Border Color</Button>
<Button BorderBrush="{DynamicResource ThemeAccentBrush}" BorderThickness="4">Thick Border</Button>
<Button BorderBrush="{DynamicResource ThemeAccentBrush}" BorderThickness="4" IsEnabled="False">Disabled</Button>
<Button BorderBrush="{DynamicResource ThemeAccentBrush}" KeyboardNavigation.IsTabStop="False">IsTabStop=False</Button>
<Button BorderBrush="{DynamicResource SystemAccentColor}">Border Color</Button>
<Button BorderBrush="{DynamicResource SystemAccentColor}" BorderThickness="4">Thick Border</Button>
<Button BorderBrush="{DynamicResource SystemAccentColor}" BorderThickness="4" IsEnabled="False">Disabled</Button>
<Button BorderBrush="{DynamicResource SystemAccentColor}" KeyboardNavigation.IsTabStop="False">IsTabStop=False</Button>
</StackPanel>
</StackPanel>
</StackPanel>

2
samples/ControlCatalog/Pages/ComboBoxPage.xaml

@ -16,7 +16,7 @@
<ComboBox SelectedIndex="0">
<ComboBoxItem>
<Panel>
<Rectangle Fill="{DynamicResource ThemeAccentBrush}"/>
<Rectangle Fill="{DynamicResource SystemAccentColor}"/>
<TextBlock Margin="8">Control Items</TextBlock>
</Panel>
</ComboBoxItem>

4
samples/ControlCatalog/Pages/ContextMenuPage.xaml

@ -9,7 +9,7 @@
Margin="0,16,0,0"
HorizontalAlignment="Center"
Spacing="16">
<Border Background="{DynamicResource ThemeAccentBrush}"
<Border Background="{DynamicResource SystemAccentColor}"
Margin="16"
Padding="48,48,48,48">
<Border.ContextMenu>
@ -34,7 +34,7 @@
</Border.ContextMenu>
<TextBlock Text="Defined in XAML"/>
</Border>
<Border Background="{DynamicResource ThemeAccentBrush}"
<Border Background="{DynamicResource SystemAccentColor}"
Margin="16"
Padding="48,48,48,48">
<Border.ContextMenu>

6
samples/ControlCatalog/Pages/DragAndDropPage.xaml

@ -10,15 +10,15 @@
HorizontalAlignment="Center"
Spacing="16">
<StackPanel>
<Border BorderBrush="{DynamicResource ThemeAccentBrush}" BorderThickness="2" Padding="16" Name="DragMeText">
<Border BorderBrush="{DynamicResource SystemAccentColor}" BorderThickness="2" Padding="16" Name="DragMeText">
<TextBlock Name="DragStateText">Drag Me</TextBlock>
</Border>
<Border BorderBrush="{DynamicResource ThemeAccentBrush}" BorderThickness="2" Padding="16" Name="DragMeCustom">
<Border BorderBrush="{DynamicResource SystemAccentColor}" BorderThickness="2" Padding="16" Name="DragMeCustom">
<TextBlock Name="DragStateCustom">Drag Me (custom)</TextBlock>
</Border>
</StackPanel>
<Border Background="{DynamicResource ThemeAccentBrush2}" Padding="16"
<Border Background="{DynamicResource SystemAccentColorDark1}" Padding="16"
DragDrop.AllowDrop="True">
<TextBlock Name="DropState">Drop some text or files here</TextBlock>
</Border>

20
samples/ControlCatalog/Pages/ItemsRepeaterPage.xaml.cs

@ -85,6 +85,26 @@ namespace ControlCatalog.Pages
MinItemHeight = 200,
};
break;
case 4:
_scroller.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
_scroller.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
_repeater.Layout = new WrapLayout
{
Orientation = Orientation.Vertical,
HorizontalSpacing = 20,
VerticalSpacing = 20
};
break;
case 5:
_scroller.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
_scroller.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
_repeater.Layout = new WrapLayout
{
Orientation = Orientation.Horizontal,
HorizontalSpacing = 20,
VerticalSpacing = 20
};
break;
}
}

8
samples/ControlCatalog/Pages/LayoutTransformControlPage.xaml

@ -11,10 +11,10 @@
RowDefinitions="24,Auto,24"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<Border Background="{DynamicResource ThemeAccentBrush}" Grid.Column="1" Grid.Row="0"/>
<Border Background="{DynamicResource ThemeAccentBrush}" Grid.Column="0" Grid.Row="1"/>
<Border Background="{DynamicResource ThemeAccentBrush}" Grid.Column="2" Grid.Row="1"/>
<Border Background="{DynamicResource ThemeAccentBrush}" Grid.Column="1" Grid.Row="2"/>
<Border Background="{DynamicResource SystemAccentColor}" Grid.Column="1" Grid.Row="0"/>
<Border Background="{DynamicResource SystemAccentColor}" Grid.Column="0" Grid.Row="1"/>
<Border Background="{DynamicResource SystemAccentColor}" Grid.Column="2" Grid.Row="1"/>
<Border Background="{DynamicResource SystemAccentColor}" Grid.Column="1" Grid.Row="2"/>
<LayoutTransformControl Name="layoutTransform" Grid.Column="1" Grid.Row="1">
<LayoutTransformControl.LayoutTransform>

60
samples/ControlCatalog/Pages/RelativePanelPage.axaml

@ -0,0 +1,60 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="ControlCatalog.Pages.RelativePanelPage">
<RelativePanel Width="620" Height="700" Margin="32">
<Border Name="Rect1" Background="Red" Height="50" Width="50">
<TextBlock Text="Rect1" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Border Name="Rect2" Background="Blue" Height="50" Width="50" RelativePanel.AlignHorizontalCenterWithPanel="True">
<TextBlock Text="Rect2" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Border Name="Rect3" Background="Green" Height="50" Width="50" RelativePanel.AlignRightWithPanel="True">
<TextBlock Text="Rect3" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Border Name="Rect4" Background="Red" Height="50" Width="50" RelativePanel.AlignBottomWithPanel="True">
<TextBlock Text="Rect4" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Border Name="Rect5" Background="Blue" Height="50" Width="50" RelativePanel.AlignBottomWithPanel="True" RelativePanel.AlignHorizontalCenterWithPanel="True">
<TextBlock Text="Rect5" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Border Name="Rect6" Background="Green" Height="50" Width="50" RelativePanel.AlignBottomWithPanel="True" RelativePanel.AlignRightWithPanel="True">
<TextBlock Text="Rect6" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Border Name="Rect7" Background="Blue" Height="50" RelativePanel.RightOf="{Binding ElementName=Rect1}">
<TextBlock Text="Rect7 (RightOf Rect1)" Padding="10,0" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Border Name="Rect8" Background="Green" Height="50" RelativePanel.Below="{Binding ElementName=Rect7}">
<TextBlock Text="Rect8 (Below Rect7)" Padding="10,0" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Border Name="Rect9" Background="Blue" Height="140" Width="460" RelativePanel.AlignHorizontalCenterWithPanel="True" RelativePanel.AlignVerticalCenterWithPanel="True">
<TextBlock Text="Rect9" Padding="10" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Top"/>
</Border>
<Border Name="Rect10" Background="Red" Width="50" RelativePanel.RightOf="{Binding ElementName=Rect9}" RelativePanel.AlignVerticalCenterWith="{Binding ElementName=Rect9}">
<TextBlock Text="Rect14 (RightOf Rect9, AlignVerticalCenterWith Rect9)" Padding="10,0" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock.RenderTransform>
<TransformGroup>
<RotateTransform Angle="-90"/>
</TransformGroup>
</TextBlock.RenderTransform>
</TextBlock>
</Border>
<Border Name="Rect11" Background="Red" Height="50" RelativePanel.AlignBottomWith="{Binding ElementName=Rect9}" RelativePanel.AlignHorizontalCenterWith="{Binding ElementName=Rect9}">
<TextBlock Text="Rect11 (AlignBottomWith Rect9, AlignHorizontalCenterWith Rect9)" Padding="10,0" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Border Name="Rect12" Background="Red" Height="50" RelativePanel.Below="{Binding ElementName=Rect8}" RelativePanel.AlignLeftWith="{Binding ElementName=Rect7}">
<TextBlock Text="Rect12 (Below Rect8, AlignLeftWith Rect7)" Padding="10,0" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Border Name="Rect13" Background="Blue" Height="50" RelativePanel.Below="{Binding ElementName=Rect12}" RelativePanel.AlignRightWith="{Binding ElementName=Rect12}">
<TextBlock Text="Rect13 (Below Rect12, AlignRightWith Rect12)" Padding="10,0" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Border Name="Rect14" Background="Green" Height="50" RelativePanel.Above="{Binding ElementName=Rect9}" RelativePanel.AlignRightWith="{Binding ElementName=Rect9}">
<TextBlock Text="Rect14 (Above Rect9, AlignRightWith Rect9)" Padding="10,0" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Border Name="Rect15" Background="Red" Height="50" RelativePanel.LeftOf="{Binding ElementName=Rect2}" RelativePanel.AlignTopWith="{Binding ElementName=Rect9}">
<TextBlock Text="Rect15 (LeftOf Rect2, AlignTopWith Rect9)" Padding="10,0" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</RelativePanel>
</UserControl>

19
samples/ControlCatalog/Pages/RelativePanelPage.axaml.cs

@ -0,0 +1,19 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace ControlCatalog.Pages
{
public class RelativePanelPage : UserControl
{
public RelativePanelPage()
{
this.InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}

21
samples/ControlCatalog/Pages/SliderPage.xaml

@ -6,11 +6,22 @@
<TextBlock Classes="h2">A control that lets the user select from a range of values by moving a Thumb control along a Track.</TextBlock>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0 16 0 0" Spacing="16">
<Slider Value="0"
Minimum="0"
Maximum="100"
TickFrequency="10"
Width="300"/>
<StackPanel Orientation="Vertical"
HorizontalAlignment="Center">
<Slider Value="0"
Minimum="0"
Maximum="100"
TickFrequency="10"
Width="300" />
<Slider Name="CustomTickedSlider"
Value="0"
Minimum="0"
Maximum="100"
TickPlacement="BottomRight"
IsSnapToTickEnabled="True"
Ticks="0,20,25,40,75,100"
Width="300" />
</StackPanel>
<Slider Value="0"
Minimum="0"
Maximum="100"

69
samples/ControlCatalog/Pages/TextBlockPage.xaml

@ -64,51 +64,42 @@
<TextDecorationCollection>
<TextDecoration
Location="Overline"
PenThicknessUnit="Pixel">
<TextDecoration.Pen>
<Pen Thickness="2">
<Pen.Brush>
<LinearGradientBrush StartPoint="0%,0%" EndPoint="100%,100%">
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0" Color="Red"/>
<GradientStop Offset="1" Color="Green"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Pen.Brush>
</Pen>
</TextDecoration.Pen>
StrokeThicknessUnit="Pixel"
StrokeThickness="2">
<TextDecoration.Stroke>
<LinearGradientBrush StartPoint="0%,0%" EndPoint="100%,100%">
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0" Color="Red"/>
<GradientStop Offset="1" Color="Green"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</TextDecoration.Stroke>
</TextDecoration>
<TextDecoration
Location="Strikethrough"
PenThicknessUnit="Pixel">
<TextDecoration.Pen>
<Pen Thickness="1">
<Pen.Brush>
<LinearGradientBrush StartPoint="0%,0%" EndPoint="100%,100%">
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0" Color="Green"/>
<GradientStop Offset="1" Color="Blue"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Pen.Brush>
</Pen>
</TextDecoration.Pen>
StrokeThicknessUnit="Pixel"
StrokeThickness="1">
<TextDecoration.Stroke>
<LinearGradientBrush StartPoint="0%,0%" EndPoint="100%,100%">
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0" Color="Green"/>
<GradientStop Offset="1" Color="Blue"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</TextDecoration.Stroke>
</TextDecoration>
<TextDecoration
Location="Underline"
PenThicknessUnit="Pixel">
<TextDecoration.Pen>
<Pen Thickness="2">
<Pen.Brush>
<LinearGradientBrush StartPoint="0%,0%" EndPoint="100%,100%">
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0" Color="Blue"/>
<GradientStop Offset="1" Color="Red"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Pen.Brush>
</Pen>
</TextDecoration.Pen>
StrokeThicknessUnit="Pixel"
StrokeThickness="2">
<TextDecoration.Stroke>
<LinearGradientBrush StartPoint="0%,0%" EndPoint="100%,100%">
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0" Color="Blue"/>
<GradientStop Offset="1" Color="Red"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</TextDecoration.Stroke>
</TextDecoration>
</TextDecorationCollection>
</TextBlock.TextDecorations>

4
samples/ControlCatalog/Pages/ToolTipPage.xaml

@ -12,7 +12,7 @@
HorizontalAlignment="Center">
<Border Grid.Column="0"
Grid.Row="1"
Background="{DynamicResource ThemeAccentBrush}"
Background="{DynamicResource SystemAccentColor}"
Margin="5"
Padding="50"
ToolTip.Tip="This is a ToolTip">
@ -26,7 +26,7 @@
<Border Name="Border"
Grid.Column="1"
Grid.Row="1"
Background="{DynamicResource ThemeAccentBrush}"
Background="{DynamicResource SystemAccentColor}"
Margin="5"
Padding="50"
ToolTip.Placement="Bottom">

19
samples/ControlCatalog/Pages/WindowCustomizationsPage.xaml

@ -0,0 +1,19 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="ControlCatalog.Pages.WindowCustomizationsPage">
<StackPanel Spacing="10" Margin="25">
<CheckBox Content="Extend Client Area to Decorations" IsChecked="{Binding ExtendClientAreaEnabled}" />
<CheckBox Content="Title Bar" IsChecked="{Binding SystemTitleBarEnabled}" />
<CheckBox Content="Prefer System Chrome" IsChecked="{Binding PreferSystemChromeEnabled}" />
<Slider Minimum="-1" Maximum="200" Value="{Binding TitleBarHeight}" />
<ComboBox x:Name="TransparencyLevels" SelectedIndex="{Binding TransparencyLevel}">
<ComboBoxItem>None</ComboBoxItem>
<ComboBoxItem>Transparent</ComboBoxItem>
<ComboBoxItem>Blur</ComboBoxItem>
<ComboBoxItem>AcrylicBlur</ComboBoxItem>
</ComboBox>
</StackPanel>
</UserControl>

19
samples/ControlCatalog/Pages/WindowCustomizationsPage.xaml.cs

@ -0,0 +1,19 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace ControlCatalog.Pages
{
public class WindowCustomizationsPage : UserControl
{
public WindowCustomizationsPage()
{
this.InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}

6
samples/ControlCatalog/SideBar.xaml

@ -12,7 +12,7 @@
<Style Selector="TabControl.sidebar">
<Setter Property="TabStripPlacement" Value="Left"/>
<Setter Property="Padding" Value="8 0 0 0"/>
<Setter Property="Background" Value="{DynamicResource ThemeAccentBrush}"/>
<Setter Property="Background" Value="{DynamicResource SystemAccentColor}"/>
<Setter Property="Template">
<ControlTemplate>
<Border
@ -74,12 +74,12 @@
<Setter Property="Opacity" Value="1"/>
</Style>
<Style Selector="TabControl.sidebar > TabItem:pointerover">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Background" Value="{DynamicResource SystemAccentColorLight2}"/>
</Style>
<Style Selector="TabControl.sidebar > TabItem:selected">
<Setter Property="Opacity" Value="1"/>
</Style>
<Style Selector="TabControl.sidebar > TabItem:selected">
<Setter Property="Background" Value="{DynamicResource ThemeAccentBrush2}"/>
<Setter Property="Background" Value="{DynamicResource SystemAccentColorLight1}"/>
</Style>
</Styles>

65
samples/ControlCatalog/ViewModels/MainWindowViewModel.cs

@ -3,6 +3,8 @@ using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Controls.Notifications;
using Avalonia.Dialogs;
using Avalonia.Platform;
using System;
using ReactiveUI;
namespace ControlCatalog.ViewModels
@ -14,6 +16,12 @@ namespace ControlCatalog.ViewModels
private bool _isMenuItemChecked = true;
private WindowState _windowState;
private WindowState[] _windowStates;
private int _transparencyLevel;
private ExtendClientAreaChromeHints _chromeHints;
private bool _extendClientAreaEnabled;
private bool _systemTitleBarEnabled;
private bool _preferSystemChromeEnabled;
private double _titleBarHeight;
public MainWindowViewModel(IManagedNotificationManager notificationManager)
{
@ -62,6 +70,63 @@ namespace ControlCatalog.ViewModels
WindowState.Maximized,
WindowState.FullScreen,
};
this.WhenAnyValue(x => x.SystemTitleBarEnabled, x=>x.PreferSystemChromeEnabled)
.Subscribe(x =>
{
var hints = ExtendClientAreaChromeHints.NoChrome | ExtendClientAreaChromeHints.OSXThickTitleBar;
if(x.Item1)
{
hints |= ExtendClientAreaChromeHints.SystemChrome;
}
if(x.Item2)
{
hints |= ExtendClientAreaChromeHints.PreferSystemChrome;
}
ChromeHints = hints;
});
SystemTitleBarEnabled = true;
TitleBarHeight = -1;
}
public int TransparencyLevel
{
get { return _transparencyLevel; }
set { this.RaiseAndSetIfChanged(ref _transparencyLevel, value); }
}
public ExtendClientAreaChromeHints ChromeHints
{
get { return _chromeHints; }
set { this.RaiseAndSetIfChanged(ref _chromeHints, value); }
}
public bool ExtendClientAreaEnabled
{
get { return _extendClientAreaEnabled; }
set { this.RaiseAndSetIfChanged(ref _extendClientAreaEnabled, value); }
}
public bool SystemTitleBarEnabled
{
get { return _systemTitleBarEnabled; }
set { this.RaiseAndSetIfChanged(ref _systemTitleBarEnabled, value); }
}
public bool PreferSystemChromeEnabled
{
get { return _preferSystemChromeEnabled; }
set { this.RaiseAndSetIfChanged(ref _preferSystemChromeEnabled, value); }
}
public double TitleBarHeight
{
get { return _titleBarHeight; }
set { this.RaiseAndSetIfChanged(ref _titleBarHeight, value); }
}
public WindowState WindowState

4
samples/RenderDemo/Pages/ClippingPage.xaml

@ -43,7 +43,7 @@
C 72.078834 28.113269 74.047517 25.960974 74.931641 23.777344
C 78.93827 14.586564 73.049722 2.8815081 63.248047 0.67382812
C 61.721916 0.22817968 60.165597 0.038541919 58.625 0.07421875 z ">
<Border Name="clipChild" Background="{DynamicResource ThemeAccentBrush}" Margin="4">
<Border Name="clipChild" Background="Red" Margin="4">
<!-- Setting opacity puts the TextBox on a new layer -->
<TextBox Text="Avalonia" Opacity="0.9" VerticalAlignment="Center"/>
<Border.RenderTransform>
@ -53,4 +53,4 @@
</Border>
<CheckBox Name="useMask" IsChecked="True" Grid.Row="1">Apply Geometry Clip</CheckBox>
</Grid>
</UserControl>
</UserControl>

4
samples/RenderDemo/SideBar.xaml

@ -3,7 +3,7 @@
<Style Selector="TabControl.sidebar">
<Setter Property="TabStripPlacement" Value="Left"/>
<Setter Property="Padding" Value="8 0 0 0"/>
<Setter Property="Background" Value="{DynamicResource ThemeAccentBrush}"/>
<Setter Property="Background" Value="{DynamicResource SystemAccentColor}"/>
<Setter Property="Template">
<ControlTemplate>
<Border
@ -60,6 +60,6 @@
<Setter Property="Opacity" Value="1"/>
</Style>
<Style Selector="TabControl.sidebar > TabItem:selected /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{DynamicResource ThemeAccentBrush2}"/>
<Setter Property="Background" Value="{DynamicResource SystemAccentColorLight1}"/>
</Style>
</Styles>

1
samples/interop/NativeEmbedSample/NativeEmbedSample.csproj

@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="MonoMac.NetStandard" Version="0.0.4" />
<ProjectReference Include="..\..\..\src\Avalonia.Desktop\Avalonia.Desktop.csproj" />
<ProjectReference Include="..\..\..\src\Windows\Avalonia.Direct2D1\Avalonia.Direct2D1.csproj" />
<ProjectReference Include="..\..\..\src\Avalonia.Diagnostics\Avalonia.Diagnostics.csproj" />
<ProjectReference Include="..\..\..\src\Avalonia.X11\Avalonia.X11.csproj" />
<PackageReference Include="Avalonia.Angle.Windows.Natives" Version="2.1.0.2019013001" />

12
src/Avalonia.Base/AvaloniaProperty.cs

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Reactive.Subjects;
using Avalonia.Data;
using Avalonia.Data.Core;
using Avalonia.Utilities;
namespace Avalonia
@ -9,7 +10,7 @@ namespace Avalonia
/// <summary>
/// Base class for avalonia properties.
/// </summary>
public abstract class AvaloniaProperty : IEquatable<AvaloniaProperty>
public abstract class AvaloniaProperty : IEquatable<AvaloniaProperty>, IPropertyInfo
{
/// <summary>
/// Represents an unset property value.
@ -159,8 +160,6 @@ namespace Avalonia
/// </summary>
internal int Id { get; }
internal bool HasChangedSubscriptions => _changed?.HasObservers ?? false;
/// <summary>
/// Provides access to a property's binding via the <see cref="AvaloniaObject"/>
/// indexer.
@ -512,7 +511,7 @@ namespace Avalonia
/// <returns>
/// An <see cref="IDisposable"/> if setting the property can be undone, otherwise null.
/// </returns>
internal abstract IDisposable? RouteSetValue(
internal abstract IDisposable RouteSetValue(
IAvaloniaObject o,
object value,
BindingPriority priority);
@ -584,6 +583,11 @@ namespace Avalonia
return _defaultMetadata;
}
bool IPropertyInfo.CanGet => true;
bool IPropertyInfo.CanSet => true;
object IPropertyInfo.Get(object target) => ((AvaloniaObject)target).GetValue(this);
void IPropertyInfo.Set(object target, object value) => ((AvaloniaObject)target).SetValue(this, value);
}
/// <summary>

4
src/Avalonia.Base/AvaloniaPropertyRegistry.cs

@ -362,7 +362,7 @@ namespace Avalonia
/// <param name="property">The property.</param>
/// <remarks>
/// You won't usually want to call this method directly, instead use the
/// <see cref="AvaloniaProperty.Register{TOwner, TValue}(string, TValue, bool, Data.BindingMode, Func{TOwner, TValue, TValue}, Action{IAvaloniaObject, bool})"/>
/// <see cref="AvaloniaProperty.Register{TOwner, TValue}(string, TValue, bool, Data.BindingMode, Func{TValue, bool}, Func{IAvaloniaObject, TValue, TValue}, Action{IAvaloniaObject, bool})"/>
/// method.
/// </remarks>
public void Register(Type type, AvaloniaProperty property)
@ -413,7 +413,7 @@ namespace Avalonia
/// <param name="property">The property.</param>
/// <remarks>
/// You won't usually want to call this method directly, instead use the
/// <see cref="AvaloniaProperty.RegisterAttached{THost, TValue}(string, Type, TValue, bool, Data.BindingMode, Func{THost, TValue, TValue})"/>
/// <see cref="AvaloniaProperty.RegisterAttached{THost, TValue}(string, Type, TValue, bool, Data.BindingMode, Func{TValue, bool}, Func{IAvaloniaObject, TValue, TValue})"/>
/// method.
/// </remarks>
public void RegisterAttached(Type type, AvaloniaProperty property)

2
src/Avalonia.Base/Collections/Pooled/IReadOnlyPooledList.cs

@ -13,9 +13,11 @@ namespace Avalonia.Collections.Pooled
public interface IReadOnlyPooledList<T> : IReadOnlyList<T>
{
#pragma warning disable CS0419
/// <summary>
/// Gets a <see cref="System.ReadOnlySpan{T}"/> for the items currently in the collection.
/// </summary>
#pragma warning restore CS0419
ReadOnlySpan<T> Span { get; }
}
}

3
src/Avalonia.Base/Collections/Pooled/PooledList.cs

@ -138,7 +138,6 @@ namespace Avalonia.Collections.Pooled
/// initially empty, but will have room for the given number of elements
/// before any reallocations are required.
/// </summary>
/// <param name="sizeToCapacity">If true, Count of list equals capacity. Depending on ClearMode, rented items may or may not hold dirty values.</param>
public PooledList(int capacity, ClearMode clearMode, ArrayPool<T> customPool, bool sizeToCapacity)
{
if (capacity < 0)
@ -499,11 +498,13 @@ namespace Avalonia.Collections.Pooled
public void AddRange(T[] array)
=> AddRange(array.AsSpan());
#pragma warning disable CS0419
/// <summary>
/// Adds the elements of the given <see cref="ReadOnlySpan{T}"/> to the end of this list. If
/// required, the capacity of the list is increased to twice the previous
/// capacity or the new size, whichever is larger.
/// </summary>
#pragma warning restore CS0419
public void AddRange(ReadOnlySpan<T> span)
{
var newSpan = InsertSpan(_size, span.Length, false);

34
src/Avalonia.Base/Data/BindingValue.cs

@ -1,4 +1,5 @@
using System;
using System.Diagnostics.CodeAnalysis;
using Avalonia.Utilities;
#nullable enable
@ -81,14 +82,14 @@ namespace Avalonia.Data
/// </remarks>
public readonly struct BindingValue<T>
{
private readonly T _value;
[AllowNull] private readonly T _value;
/// <summary>
/// Initializes a new instance of the <see cref="BindingValue{T}"/> struct with a type of
/// <see cref="BindingValueType.Value"/>
/// </summary>
/// <param name="value">The value.</param>
public BindingValue(T value)
public BindingValue([AllowNull] T value)
{
ValidateValue(value);
_value = value;
@ -96,7 +97,7 @@ namespace Avalonia.Data
Error = null;
}
private BindingValue(BindingValueType type, T value, Exception? error)
private BindingValue(BindingValueType type, [AllowNull] T value, Exception? error)
{
_value = value;
Type = type;
@ -154,7 +155,7 @@ namespace Avalonia.Data
BindingValueType.UnsetValue => AvaloniaProperty.UnsetValue,
BindingValueType.DoNothing => BindingOperations.DoNothing,
BindingValueType.Value => _value,
BindingValueType.BindingError =>
BindingValueType.BindingError =>
new BindingNotification(Error, BindingErrorType.Error),
BindingValueType.BindingErrorWithFallback =>
new BindingNotification(Error, BindingErrorType.Error, Value),
@ -175,7 +176,7 @@ namespace Avalonia.Data
/// The binding type is <see cref="BindingValueType.UnsetValue"/> or
/// <see cref="BindingValueType.DoNothing"/>.
/// </exception>
public BindingValue<T> WithValue(T value)
public BindingValue<T> WithValue([AllowNull] T value)
{
if (Type == BindingValueType.DoNothing)
{
@ -190,6 +191,7 @@ namespace Avalonia.Data
/// Gets the value of the binding value if present, otherwise the default value.
/// </summary>
/// <returns>The value.</returns>
[return: MaybeNull]
public T GetValueOrDefault() => HasValue ? _value : default;
/// <summary>
@ -206,6 +208,7 @@ namespace Avalonia.Data
/// The value if present and of the correct type, `default(TResult)` if the value is
/// not present or of an incorrect type.
/// </returns>
[return: MaybeNull]
public TResult GetValueOrDefault<TResult>()
{
return HasValue ?
@ -222,7 +225,8 @@ namespace Avalonia.Data
/// present but not of the correct type or null, or <paramref name="defaultValue"/> if the
/// value is not present.
/// </returns>
public TResult GetValueOrDefault<TResult>(TResult defaultValue)
[return: MaybeNull]
public TResult GetValueOrDefault<TResult>([AllowNull] TResult defaultValue)
{
return HasValue ?
_value is TResult result ? result : default
@ -242,7 +246,7 @@ namespace Avalonia.Data
UnsetValueType _ => Unset,
DoNothingType _ => DoNothing,
BindingNotification n => n.ToBindingValue().Cast<T>(),
_ => (T)value
_ => new BindingValue<T>((T)value)
};
}
@ -250,7 +254,7 @@ namespace Avalonia.Data
/// Creates a binding value from an instance of the underlying value type.
/// </summary>
/// <param name="value">The value.</param>
public static implicit operator BindingValue<T>(T value) => new BindingValue<T>(value);
public static implicit operator BindingValue<T>([AllowNull] T value) => new BindingValue<T>(value);
/// <summary>
/// Creates a binding value from an <see cref="Optional{T}"/>.
@ -278,7 +282,7 @@ namespace Avalonia.Data
/// <param name="e">The binding error.</param>
public static BindingValue<T> BindingError(Exception e)
{
e = e ?? throw new ArgumentNullException("e");
e = e ?? throw new ArgumentNullException(nameof(e));
return new BindingValue<T>(BindingValueType.BindingError, default, e);
}
@ -290,7 +294,7 @@ namespace Avalonia.Data
/// <param name="fallbackValue">The fallback value.</param>
public static BindingValue<T> BindingError(Exception e, T fallbackValue)
{
e = e ?? throw new ArgumentNullException("e");
e = e ?? throw new ArgumentNullException(nameof(e));
return new BindingValue<T>(BindingValueType.BindingErrorWithFallback, fallbackValue, e);
}
@ -303,7 +307,7 @@ namespace Avalonia.Data
/// <param name="fallbackValue">The fallback value.</param>
public static BindingValue<T> BindingError(Exception e, Optional<T> fallbackValue)
{
e = e ?? throw new ArgumentNullException("e");
e = e ?? throw new ArgumentNullException(nameof(e));
return new BindingValue<T>(
fallbackValue.HasValue ?
@ -319,7 +323,7 @@ namespace Avalonia.Data
/// <param name="e">The data validation error.</param>
public static BindingValue<T> DataValidationError(Exception e)
{
e = e ?? throw new ArgumentNullException("e");
e = e ?? throw new ArgumentNullException(nameof(e));
return new BindingValue<T>(BindingValueType.DataValidationError, default, e);
}
@ -331,7 +335,7 @@ namespace Avalonia.Data
/// <param name="fallbackValue">The fallback value.</param>
public static BindingValue<T> DataValidationError(Exception e, T fallbackValue)
{
e = e ?? throw new ArgumentNullException("e");
e = e ?? throw new ArgumentNullException(nameof(e));
return new BindingValue<T>(BindingValueType.DataValidationErrorWithFallback, fallbackValue, e);
}
@ -344,7 +348,7 @@ namespace Avalonia.Data
/// <param name="fallbackValue">The fallback value.</param>
public static BindingValue<T> DataValidationError(Exception e, Optional<T> fallbackValue)
{
e = e ?? throw new ArgumentNullException("e");
e = e ?? throw new ArgumentNullException(nameof(e));
return new BindingValue<T>(
fallbackValue.HasValue ?
@ -354,7 +358,7 @@ namespace Avalonia.Data
e);
}
private static void ValidateValue(T value)
private static void ValidateValue([AllowNull] T value)
{
if (value is UnsetValueType)
{

73
src/Avalonia.Base/Data/Core/ClrPropertyInfo.cs

@ -0,0 +1,73 @@
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Avalonia.Data.Core
{
public class ClrPropertyInfo : IPropertyInfo
{
private readonly Func<object, object> _getter;
private readonly Action<object, object> _setter;
public ClrPropertyInfo(string name, Func<object, object> getter, Action<object, object> setter, Type propertyType)
{
_getter = getter;
_setter = setter;
PropertyType = propertyType;
Name = name;
}
public string Name { get; }
public Type PropertyType { get; }
public object Get(object target)
{
if (_getter == null)
throw new NotSupportedException("Property " + Name + " doesn't have a getter");
return _getter(target);
}
public void Set(object target, object value)
{
if (_setter == null)
throw new NotSupportedException("Property " + Name + " doesn't have a setter");
_setter(target, value);
}
public bool CanSet => _setter != null;
public bool CanGet => _getter != null;
}
public class ReflectionClrPropertyInfo : ClrPropertyInfo
{
static Action<object, object> CreateSetter(PropertyInfo info)
{
if (info.SetMethod == null)
return null;
var target = Expression.Parameter(typeof(object), "target");
var value = Expression.Parameter(typeof(object), "value");
return Expression.Lambda<Action<object, object>>(
Expression.Call(Expression.Convert(target, info.DeclaringType), info.SetMethod,
Expression.Convert(value, info.SetMethod.GetParameters()[0].ParameterType)),
target, value)
.Compile();
}
static Func<object, object> CreateGetter(PropertyInfo info)
{
if (info.GetMethod == null)
return null;
var target = Expression.Parameter(typeof(object), "target");
return Expression.Lambda<Func<object, object>>(
Expression.Convert(Expression.Call(Expression.Convert(target, info.DeclaringType), info.GetMethod),
typeof(object)))
.Compile();
}
public ReflectionClrPropertyInfo(PropertyInfo info) : base(info.Name,
CreateGetter(info), CreateSetter(info), info.PropertyType)
{
}
}
}

32
src/Avalonia.Base/Data/Core/ExpressionObserver.cs

@ -54,6 +54,7 @@ namespace Avalonia.Data.Core
private object _root;
private IDisposable _rootSubscription;
private WeakReference<object> _value;
private IReadOnlyList<ITransformNode> _transformNodes;
/// <summary>
/// Initializes a new instance of the <see cref="ExpressionObserver"/> class.
@ -188,6 +189,24 @@ namespace Avalonia.Data.Core
description ?? expression.ToString());
}
private IReadOnlyList<ITransformNode> GetTransformNodesFromChain()
{
LinkedList<ITransformNode> transforms = new LinkedList<ITransformNode>();
var node = _node;
while (node != null)
{
if (node is ITransformNode transform)
{
transforms.AddFirst(transform);
}
node = node.Next;
}
return new List<ITransformNode>(transforms);
}
private IReadOnlyList<ITransformNode> TransformNodes => (_transformNodes ?? (_transformNodes = GetTransformNodesFromChain()));
/// <summary>
/// Attempts to set the value of a property expression.
/// </summary>
@ -203,18 +222,13 @@ namespace Avalonia.Data.Core
{
if (Leaf is SettableNode settable)
{
var node = _node;
while (node != null)
foreach (var transform in TransformNodes)
{
if (node is ITransformNode transform)
value = transform.Transform(value);
if (value is BindingNotification)
{
value = transform.Transform(value);
if (value is BindingNotification)
{
return false;
}
return false;
}
node = node.Next;
}
return settable.SetTargetValue(value, priority);
}

14
src/Avalonia.Base/Data/Core/IPropertyInfo.cs

@ -0,0 +1,14 @@
using System;
namespace Avalonia.Data.Core
{
public interface IPropertyInfo
{
string Name { get; }
object Get(object target);
void Set(object target, object value);
bool CanSet { get; }
bool CanGet { get; }
Type PropertyType { get; }
}
}

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

@ -59,7 +59,7 @@ namespace Avalonia.Data.Core.Plugins
return Observable.Empty<object>();
}
protected IObservable<object> HandleCompleted(Task task)
private IObservable<object> HandleCompleted(Task task)
{
var resultProperty = task.GetType().GetRuntimeProperty("Result");

32
src/Avalonia.Base/Data/Core/PropertyAccessorNode.cs

@ -7,6 +7,7 @@ namespace Avalonia.Data.Core
public class PropertyAccessorNode : SettableNode
{
private readonly bool _enableValidation;
private IPropertyAccessorPlugin _customPlugin;
private IPropertyAccessor _accessor;
public PropertyAccessorNode(string propertyName, bool enableValidation)
@ -15,6 +16,13 @@ namespace Avalonia.Data.Core
_enableValidation = enableValidation;
}
public PropertyAccessorNode(string propertyName, bool enableValidation, IPropertyAccessorPlugin customPlugin)
{
PropertyName = propertyName;
_enableValidation = enableValidation;
_customPlugin = customPlugin;
}
public override string Description => PropertyName;
public string PropertyName { get; }
public override Type PropertyType => _accessor?.PropertyType;
@ -37,17 +45,7 @@ namespace Avalonia.Data.Core
{
reference.TryGetTarget(out object target);
IPropertyAccessorPlugin plugin = null;
foreach (IPropertyAccessorPlugin x in ExpressionObserver.PropertyAccessors)
{
if (x.Match(target, PropertyName))
{
plugin = x;
break;
}
}
var plugin = _customPlugin ?? GetPropertyAccessorPluginForObject(target);
var accessor = plugin?.Start(reference, PropertyName);
// We need to handle accessor fallback before handling validation. Validators do not support null accessors.
@ -82,6 +80,18 @@ namespace Avalonia.Data.Core
accessor.Subscribe(ValueChanged);
}
private IPropertyAccessorPlugin GetPropertyAccessorPluginForObject(object target)
{
foreach (IPropertyAccessorPlugin x in ExpressionObserver.PropertyAccessors)
{
if (x.Match(target, PropertyName))
{
return x;
}
}
return null;
}
protected override void StopListeningCore()
{
_accessor.Dispose();

91
src/Avalonia.Base/Data/Core/PropertyPath.cs

@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Avalonia.Data.Core
{
public class PropertyPath
{
public IReadOnlyList<IPropertyPathElement> Elements { get; }
public PropertyPath(IEnumerable<IPropertyPathElement> elements)
{
Elements = elements.ToList();
}
}
public class PropertyPathBuilder
{
readonly List<IPropertyPathElement> _elements = new List<IPropertyPathElement>();
public PropertyPathBuilder Property(IPropertyInfo property)
{
_elements.Add(new PropertyPropertyPathElement(property));
return this;
}
public PropertyPathBuilder ChildTraversal()
{
_elements.Add(new ChildTraversalPropertyPathElement());
return this;
}
public PropertyPathBuilder EnsureType(Type type)
{
_elements.Add(new EnsureTypePropertyPathElement(type));
return this;
}
public PropertyPathBuilder Cast(Type type)
{
_elements.Add(new CastTypePropertyPathElement(type));
return this;
}
public PropertyPath Build()
{
return new PropertyPath(_elements);
}
}
public interface IPropertyPathElement
{
}
public class PropertyPropertyPathElement : IPropertyPathElement
{
public IPropertyInfo Property { get; }
public PropertyPropertyPathElement(IPropertyInfo property)
{
Property = property;
}
}
public class ChildTraversalPropertyPathElement : IPropertyPathElement
{
}
public class EnsureTypePropertyPathElement : IPropertyPathElement
{
public Type Type { get; }
public EnsureTypePropertyPathElement(Type type)
{
Type = type;
}
}
public class CastTypePropertyPathElement : IPropertyPathElement
{
public CastTypePropertyPathElement(Type type)
{
Type = type;
}
public Type Type { get; }
}
}

37
src/Avalonia.Base/Data/Core/StreamNode.cs

@ -1,35 +1,54 @@
using System;
using System.Reactive.Linq;
using Avalonia.Data.Core.Plugins;
namespace Avalonia.Data.Core
{
public class StreamNode : ExpressionNode
{
private IStreamPlugin _customPlugin = null;
private IDisposable _subscription;
public override string Description => "^";
public StreamNode() { }
public StreamNode(IStreamPlugin customPlugin)
{
_customPlugin = customPlugin;
}
protected override void StartListeningCore(WeakReference<object> reference)
{
GetPlugin(reference)?.Start(reference).Subscribe(ValueChanged);
}
protected override void StopListeningCore()
{
_subscription?.Dispose();
_subscription = null;
}
private IStreamPlugin GetPlugin(WeakReference<object> reference)
{
if (_customPlugin != null)
{
return _customPlugin;
}
foreach (var plugin in ExpressionObserver.StreamHandlers)
{
if (plugin.Match(reference))
{
_subscription = plugin.Start(reference).Subscribe(ValueChanged);
return;
return plugin;
}
}
// TODO: Improve error.
// TODO: Improve error
ValueChanged(new BindingNotification(
new MarkupBindingChainException("Stream operator applied to unsupported type", Description),
BindingErrorType.Error));
}
protected override void StopListeningCore()
{
_subscription?.Dispose();
_subscription = null;
return null;
}
}
}

16
src/Avalonia.Base/Data/Optional.cs

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#nullable enable
@ -22,13 +23,13 @@ namespace Avalonia.Data
/// </remarks>
public readonly struct Optional<T> : IEquatable<Optional<T>>
{
private readonly T _value;
[AllowNull] private readonly T _value;
/// <summary>
/// Initializes a new instance of the <see cref="Optional{T}"/> struct with value.
/// </summary>
/// <param name="value">The value.</param>
public Optional(T value)
public Optional([AllowNull] T value)
{
_value = value;
HasValue = true;
@ -48,7 +49,7 @@ namespace Avalonia.Data
public T Value => HasValue ? _value : throw new InvalidOperationException("Optional has no value.");
/// <inheritdoc/>
public override bool Equals(object obj) => obj is Optional<T> o && this == o;
public override bool Equals(object? obj) => obj is Optional<T> o && this == o;
/// <inheritdoc/>
public bool Equals(Optional<T> other) => this == other;
@ -69,6 +70,7 @@ namespace Avalonia.Data
/// Gets the value if present, otherwise the default value.
/// </summary>
/// <returns>The value.</returns>
[return: MaybeNull]
public T GetValueOrDefault() => HasValue ? _value : default;
/// <summary>
@ -85,6 +87,7 @@ namespace Avalonia.Data
/// The value if present and of the correct type, `default(TResult)` if the value is
/// not present or of an incorrect type.
/// </returns>
[return: MaybeNull]
public TResult GetValueOrDefault<TResult>()
{
return HasValue ?
@ -101,7 +104,8 @@ namespace Avalonia.Data
/// present but not of the correct type or null, or <paramref name="defaultValue"/> if the
/// value is not present.
/// </returns>
public TResult GetValueOrDefault<TResult>(TResult defaultValue)
[return: MaybeNull]
public TResult GetValueOrDefault<TResult>([AllowNull] TResult defaultValue)
{
return HasValue ?
_value is TResult result ? result : default
@ -112,7 +116,7 @@ namespace Avalonia.Data
/// Creates an <see cref="Optional{T}"/> from an instance of the underlying value type.
/// </summary>
/// <param name="value">The value.</param>
public static implicit operator Optional<T>(T value) => new Optional<T>(value);
public static implicit operator Optional<T>([AllowNull] T value) => new Optional<T>(value);
/// <summary>
/// Compares two <see cref="Optional{T}"/>s for inequality.
@ -128,7 +132,7 @@ namespace Avalonia.Data
/// <param name="x">The first value.</param>
/// <param name="y">The second value.</param>
/// <returns>True if the values are equal; otherwise false.</returns>
public static bool operator==(Optional<T> x, Optional<T> y)
public static bool operator ==(Optional<T> x, Optional<T> y)
{
if (!x.HasValue && !y.HasValue)
{

2
src/Avalonia.Base/DirectPropertyBase.cs

@ -120,7 +120,7 @@ namespace Avalonia
return o.GetValue<TValue>(this);
}
internal override object RouteGetBaseValue(IAvaloniaObject o, BindingPriority maxPriority)
internal override object? RouteGetBaseValue(IAvaloniaObject o, BindingPriority maxPriority)
{
return o.GetValue<TValue>(this);
}

2
src/Avalonia.Base/IStyledPropertyMetadata.cs

@ -1,5 +1,3 @@
using System;
namespace Avalonia
{
/// <summary>

140
src/Avalonia.Base/Metadata/NullableAttributes.cs

@ -0,0 +1,140 @@
#pragma warning disable MA0048 // File name must match type name
#define INTERNAL_NULLABLE_ATTRIBUTES
#if NETSTANDARD2_0 || NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 || NET45 || NET451 || NET452 || NET6 || NET461 || NET462 || NET47 || NET471 || NET472 || NET48
// https://github.com/dotnet/corefx/blob/48363ac826ccf66fbe31a5dcb1dc2aab9a7dd768/src/Common/src/CoreLib/System/Diagnostics/CodeAnalysis/NullableAttributes.cs
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>Specifies that null is allowed as an input even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class AllowNullAttribute : Attribute
{ }
/// <summary>Specifies that null is disallowed as an input even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class DisallowNullAttribute : Attribute
{ }
/// <summary>Specifies that an output may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class MaybeNullAttribute : Attribute
{ }
/// <summary>Specifies that an output will not be null even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class NotNullAttribute : Attribute
{ }
/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class MaybeNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter may be null.
/// </param>
public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;
/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}
/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter will not be null even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class NotNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;
/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}
/// <summary>Specifies that the output will be non-null if the named parameter is non-null.</summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class NotNullIfNotNullAttribute : Attribute
{
/// <summary>Initializes the attribute with the associated parameter name.</summary>
/// <param name="parameterName">
/// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null.
/// </param>
public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName;
/// <summary>Gets the associated parameter name.</summary>
public string ParameterName { get; }
}
/// <summary>Applied to a method that will never return under any circumstance.</summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class DoesNotReturnAttribute : Attribute
{ }
/// <summary>Specifies that the method will not return if the associated Boolean parameter is passed the specified value.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class DoesNotReturnIfAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified parameter value.</summary>
/// <param name="parameterValue">
/// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to
/// the associated parameter matches this value.
/// </param>
public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue;
/// <summary>Gets the condition parameter value.</summary>
public bool ParameterValue { get; }
}
}
#endif

7
src/Avalonia.Base/PropertyStore/IPriorityValueEntry.cs

@ -1,7 +1,4 @@
using System;
using Avalonia.Data;
#nullable enable
#nullable enable
namespace Avalonia.PropertyStore
{
@ -10,8 +7,6 @@ namespace Avalonia.PropertyStore
/// </summary>
internal interface IPriorityValueEntry : IValue
{
BindingPriority Priority { get; }
void Reparent(IValueSink sink);
}

7
src/Avalonia.Base/PropertyStore/LocalValueEntry.cs

@ -1,4 +1,5 @@
using Avalonia.Data;
using System.Diagnostics.CodeAnalysis;
using Avalonia.Data;
#nullable enable
@ -11,9 +12,9 @@ namespace Avalonia.PropertyStore
/// <typeparam name="T">The property type.</typeparam>
internal class LocalValueEntry<T> : IValue<T>
{
private T _value;
[AllowNull] private T _value;
public LocalValueEntry(T value) => _value = value;
public LocalValueEntry([AllowNull] T value) => _value = value;
public BindingPriority Priority => BindingPriority.LocalValue;
Optional<object> IValue.GetValue() => new Optional<object>(_value);

3
src/Avalonia.Base/StyledPropertyMetadata`1.cs

@ -1,5 +1,4 @@
using System;
using System.Diagnostics;
using Avalonia.Data;
namespace Avalonia
@ -35,7 +34,7 @@ namespace Avalonia
/// <summary>
/// Gets the value coercion callback, if any.
/// </summary>
public Func<IAvaloniaObject, TValue, TValue>? CoerceValue { get; private set; }
public Func<IAvaloniaObject, TValue, TValue> CoerceValue { get; private set; }
object IStyledPropertyMetadata.DefaultValue => DefaultValue;

20
src/Avalonia.Base/Utilities/CharacterReader.cs

@ -79,5 +79,25 @@ namespace Avalonia.Utilities
Position += len;
return span;
}
public ReadOnlySpan<char> TryPeek(int count)
{
if (_s.Length < count)
return ReadOnlySpan<char>.Empty;
return _s.Slice(0, count);
}
public ReadOnlySpan<char> PeekWhitespace()
{
var trimmed = _s.TrimStart();
return _s.Slice(0, _s.Length - trimmed.Length);
}
public void Skip(int count)
{
if (_s.Length < count)
throw new IndexOutOfRangeException();
_s = _s.Slice(count);
}
}
}

46
src/Avalonia.Base/Utilities/KeywordParser.cs

@ -0,0 +1,46 @@
using System;
namespace Avalonia.Utilities
{
#if !BUILDTASK
public
#endif
static class KeywordParser
{
public static bool CheckKeyword(this ref CharacterReader r, string keyword)
{
return (CheckKeywordInternal(ref r, keyword) >= 0);
}
static int CheckKeywordInternal(this ref CharacterReader r, string keyword)
{
var ws = r.PeekWhitespace();
var chars = r.TryPeek(ws.Length + keyword.Length);
if (chars.IsEmpty)
return -1;
if (SpanEquals(chars.Slice(ws.Length), keyword.AsSpan()))
return chars.Length;
return -1;
}
static bool SpanEquals(ReadOnlySpan<char> left, ReadOnlySpan<char> right)
{
if (left.Length != right.Length)
return false;
for(var c=0; c<left.Length;c++)
if (left[c] != right[c])
return false;
return true;
}
public static bool TakeIfKeyword(this ref CharacterReader r, string keyword)
{
var l = CheckKeywordInternal(ref r, keyword);
if (l < 0)
return false;
r.Skip(l);
return true;
}
}
}

45
src/Avalonia.Base/Utilities/StyleClassParser.cs

@ -0,0 +1,45 @@
using System;
using System.Globalization;
namespace Avalonia.Utilities
{
#if !BUILDTASK
public
#endif
static class StyleClassParser
{
public static ReadOnlySpan<char> ParseStyleClass(this ref CharacterReader r)
{
if (IsValidIdentifierStart(r.Peek))
{
return r.TakeWhile(c => IsValidIdentifierChar(c));
}
else
{
return ReadOnlySpan<char>.Empty;
}
}
private static bool IsValidIdentifierStart(char c)
{
return char.IsLetter(c) || c == '_';
}
private static bool IsValidIdentifierChar(char c)
{
if (IsValidIdentifierStart(c) || c == '-')
{
return true;
}
else
{
var cat = CharUnicodeInfo.GetUnicodeCategory(c);
return cat == UnicodeCategory.NonSpacingMark ||
cat == UnicodeCategory.SpacingCombiningMark ||
cat == UnicodeCategory.ConnectorPunctuation ||
cat == UnicodeCategory.Format ||
cat == UnicodeCategory.DecimalDigitNumber;
}
}
}
}

2
src/Avalonia.Base/ValueStore.cs

@ -162,7 +162,7 @@ namespace Avalonia
_sink.ValueChanged(new AvaloniaPropertyChangedEventArgs<T>(
_owner,
property,
old,
new Optional<T>(old),
default,
BindingPriority.Unset));
}

45
src/Avalonia.Build.Tasks/Avalonia.Build.Tasks.csproj

@ -5,7 +5,7 @@
<OutputType>exe</OutputType>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<BuildOutputTargetFolder>tools</BuildOutputTargetFolder>
<DefineConstants>$(DefineConstants);BUILDTASK;XAMLIL_CECIL_INTERNAL;XAMLIL_INTERNAL</DefineConstants>
<DefineConstants>$(DefineConstants);BUILDTASK;XAMLX_CECIL_INTERNAL;XAMLX_INTERNAL</DefineConstants>
<CopyLocalLockFileAssemblies Condition="$(TargetFramework) == 'netstandard2.0'">true</CopyLocalLockFileAssemblies>
<NoWarn>NU1605</NoWarn>
</PropertyGroup>
@ -21,15 +21,18 @@
<Link>XamlIlExtensions/%(RecursiveDir)%(FileName)%(Extension)</Link>
</Compile>
<Compile Remove="external/cecil/**/*.*" />
<Compile Include="../Markup/Avalonia.Markup.Xaml/XamlIl\xamlil.github\src\XamlIl\**\*.cs">
<Compile Include="../Markup/Avalonia.Markup.Xaml/XamlIl\xamlil.github\src\XamlX\**\*.cs">
<Link>XamlIl/%(RecursiveDir)%(FileName)%(Extension)</Link>
</Compile>
<Compile Include="../Markup/Avalonia.Markup.Xaml/XamlIl\xamlil.github\src\XamlIl.Cecil\**\*.cs">
<Compile Include="../Markup/Avalonia.Markup.Xaml/XamlIl\xamlil.github\src\XamlX.IL.Cecil\**\*.cs">
<Link>XamlIl.Cecil/%(RecursiveDir)%(FileName)%(Extension)</Link>
</Compile>
<Compile Include="../Markup/Avalonia.Markup\Markup\Parsers\SelectorGrammar.cs">
<Link>Markup/%(RecursiveDir)%(FileName)%(Extension)</Link>
</Compile>
<Compile Include="../Markup/Avalonia.Markup\Markup\Parsers\PropertyPathGrammar.cs">
<Link>Markup/%(RecursiveDir)%(FileName)%(Extension)</Link>
</Compile>
<Compile Include="../Markup/Avalonia.Markup.Xaml/Parsers/PropertyParser.cs">
<Link>Markup/%(RecursiveDir)%(FileName)%(Extension)</Link>
</Compile>
@ -38,33 +41,25 @@
</Compile>
<Compile Include="../Avalonia.Base/Utilities/CharacterReader.cs">
<Link>Markup/%(RecursiveDir)%(FileName)%(Extension)</Link>
</Compile>
</Compile>
<Compile Include="../Avalonia.Base/Utilities/IdentifierParser.cs">
<Link>Markup/%(RecursiveDir)%(FileName)%(Extension)</Link>
</Compile>
<Compile Include="..\Markup\Avalonia.Markup\Markup\Parsers\ArgumentListParser.cs">
<Link>Markup/%(RecursiveDir)%(FileName)%(Extension)</Link>
</Compile>
<Compile Include="../Avalonia.Base/Utilities/KeywordParser.cs">
<Link>Markup/%(RecursiveDir)%(FileName)%(Extension)</Link>
</Compile>
<Compile Include="..\Markup\Avalonia.Markup\Markup\Parsers\BindingExpressionGrammar.cs">
<Link>Markup/%(RecursiveDir)%(FileName)%(Extension)</Link>
</Compile>
<Compile Include="../Avalonia.Base/Utilities/StyleClassParser.cs">
<Link>Markup/%(RecursiveDir)%(FileName)%(Extension)</Link>
</Compile>
<Compile Remove="../Markup/Avalonia.Markup.Xaml/XamlIl\xamlil.github\**\obj\**\*.cs" />
<Compile Remove="../Markup/Avalonia.Markup.Xaml/XamlIl\xamlil.github\src\XamlIl\TypeSystem\SreTypeSystem.cs" />
<Compile Remove="../Markup/Avalonia.Markup.Xaml/XamlIl\xamlil.github\src\XamlX\IL\SreTypeSystem.cs" />
<PackageReference Include="Avalonia.Unofficial.Cecil" Version="20190417.2.0" PrivateAssets="All" />
<PackageReference Condition="$(TargetFramework) == 'netstandard2.0'" Include="ILRepack.MSBuild.Task" Version="2.0.13" PrivateAssets="All" />
<PackageReference Include="Microsoft.Build.Framework" Version="15.1.548" PrivateAssets="All" />
</ItemGroup>
<Target Name="ILRepack" AfterTargets="Build" Condition="$(TargetFramework) == 'netstandard2.0'">
<PropertyGroup>
<WorkingDirectory>$(MSBuildThisFileDirectory)bin\$(Configuration)\$(TargetFramework)</WorkingDirectory>
</PropertyGroup>
<ItemGroup>
<InputAssemblies Include="Mono.Cecil.dll" />
</ItemGroup>
<ILRepack OutputType="$(OutputType)" MainAssembly="$(AssemblyName).dll" OutputAssembly="$(AssemblyName).dll" InputAssemblies="@(InputAssemblies)" WorkingDirectory="$(WorkingDirectory)" />
<ItemGroup>
<DeleteNonNeededResults Include="$(WorkingDirectory)\*.dll" />
<DeleteNonNeededResults Remove="$(WorkingDirectory)\Avalonia.Build.Tasks.dll" />
</ItemGroup>
<Delete Files="@(DeleteNonNeededResults)" />
</Target>
</Project>

2
src/Avalonia.Build.Tasks/XamlCompilerTaskExecutor.Helpers.cs

@ -5,7 +5,7 @@ using Avalonia.Utilities;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using XamlIl.TypeSystem;
using XamlX.TypeSystem;
namespace Avalonia.Build.Tasks
{

60
src/Avalonia.Build.Tasks/XamlCompilerTaskExecutor.cs

@ -7,17 +7,18 @@ using System.Text;
using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions;
using Microsoft.Build.Framework;
using Mono.Cecil;
using XamlIl.TypeSystem;
using Avalonia.Utilities;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using XamlIl;
using XamlIl.Ast;
using XamlIl.Parsers;
using XamlIl.Transform;
using XamlX;
using XamlX.Ast;
using XamlX.Parsers;
using XamlX.Transform;
using XamlX.TypeSystem;
using FieldAttributes = Mono.Cecil.FieldAttributes;
using MethodAttributes = Mono.Cecil.MethodAttributes;
using TypeAttributes = Mono.Cecil.TypeAttributes;
using XamlX.IL;
namespace Avalonia.Build.Tasks
{
@ -50,23 +51,32 @@ namespace Avalonia.Build.Tasks
if (avares.Resources.Count(CheckXamlName) == 0 && emres.Resources.Count(CheckXamlName) == 0)
// Nothing to do
return new CompileResult(true);
var xamlLanguage = AvaloniaXamlIlLanguage.Configure(typeSystem);
var compilerConfig = new XamlIlTransformerConfiguration(typeSystem,
var clrPropertiesDef = new TypeDefinition("CompiledAvaloniaXaml", "XamlIlHelpers",
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
asm.MainModule.Types.Add(clrPropertiesDef);
var indexerAccessorClosure = new TypeDefinition("CompiledAvaloniaXaml", "!IndexerAccessorFactoryClosure",
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
asm.MainModule.Types.Add(indexerAccessorClosure);
var (xamlLanguage , emitConfig) = AvaloniaXamlIlLanguage.Configure(typeSystem);
var compilerConfig = new AvaloniaXamlIlCompilerConfiguration(typeSystem,
typeSystem.TargetAssembly,
xamlLanguage,
XamlIlXmlnsMappings.Resolve(typeSystem, xamlLanguage),
AvaloniaXamlIlLanguage.CustomValueConverter);
XamlXmlnsMappings.Resolve(typeSystem, xamlLanguage),
AvaloniaXamlIlLanguage.CustomValueConverter,
new XamlIlClrPropertyInfoEmitter(typeSystem.CreateTypeBuilder(clrPropertiesDef)),
new XamlIlPropertyInfoAccessorFactoryEmitter(typeSystem.CreateTypeBuilder(indexerAccessorClosure)));
var contextDef = new TypeDefinition("CompiledAvaloniaXaml", "XamlIlContext",
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
asm.MainModule.Types.Add(contextDef);
var contextClass = XamlIlContextDefinition.GenerateContextClass(typeSystem.CreateTypeBuilder(contextDef), typeSystem,
xamlLanguage);
var contextClass = XamlILContextDefinition.GenerateContextClass(typeSystem.CreateTypeBuilder(contextDef), typeSystem,
xamlLanguage, emitConfig);
var compiler = new AvaloniaXamlIlCompiler(compilerConfig, contextClass) { EnableIlVerification = verifyIl };
var compiler = new AvaloniaXamlIlCompiler(compilerConfig, emitConfig, contextClass) { EnableIlVerification = verifyIl };
var editorBrowsableAttribute = typeSystem
.GetTypeReference(typeSystem.FindType("System.ComponentModel.EditorBrowsableAttribute"))
@ -126,35 +136,35 @@ namespace Avalonia.Build.Tasks
// StreamReader is needed here to handle BOM
var xaml = new StreamReader(new MemoryStream(res.FileContents)).ReadToEnd();
var parsed = XDocumentXamlIlParser.Parse(xaml);
var parsed = XDocumentXamlParser.Parse(xaml);
var initialRoot = (XamlIlAstObjectNode)parsed.Root;
var initialRoot = (XamlAstObjectNode)parsed.Root;
var precompileDirective = initialRoot.Children.OfType<XamlIlAstXmlDirective>()
var precompileDirective = initialRoot.Children.OfType<XamlAstXmlDirective>()
.FirstOrDefault(d => d.Namespace == XamlNamespaces.Xaml2006 && d.Name == "Precompile");
if (precompileDirective != null)
{
var precompileText = (precompileDirective.Values[0] as XamlIlAstTextNode)?.Text.Trim()
var precompileText = (precompileDirective.Values[0] as XamlAstTextNode)?.Text.Trim()
.ToLowerInvariant();
if (precompileText == "false")
continue;
if (precompileText != "true")
throw new XamlIlParseException("Invalid value for x:Precompile", precompileDirective);
throw new XamlParseException("Invalid value for x:Precompile", precompileDirective);
}
var classDirective = initialRoot.Children.OfType<XamlIlAstXmlDirective>()
var classDirective = initialRoot.Children.OfType<XamlAstXmlDirective>()
.FirstOrDefault(d => d.Namespace == XamlNamespaces.Xaml2006 && d.Name == "Class");
IXamlIlType classType = null;
IXamlType classType = null;
if (classDirective != null)
{
if (classDirective.Values.Count != 1 || !(classDirective.Values[0] is XamlIlAstTextNode tn))
throw new XamlIlParseException("x:Class should have a string value", classDirective);
if (classDirective.Values.Count != 1 || !(classDirective.Values[0] is XamlAstTextNode tn))
throw new XamlParseException("x:Class should have a string value", classDirective);
classType = typeSystem.TargetAssembly.FindType(tn.Text);
if (classType == null)
throw new XamlIlParseException($"Unable to find type `{tn.Text}`", classDirective);
throw new XamlParseException($"Unable to find type `{tn.Text}`", classDirective);
compiler.OverrideRootType(parsed,
new XamlIlAstClrTypeReference(classDirective, classType, false));
new XamlAstClrTypeReference(classDirective, classType, false));
initialRoot.Children.Remove(classDirective);
}
@ -323,7 +333,7 @@ namespace Avalonia.Build.Tasks
catch (Exception e)
{
int lineNumber = 0, linePosition = 0;
if (e is XamlIlParseException xe)
if (e is XamlParseException xe)
{
lineNumber = xe.LineNumber;
linePosition = xe.LinePosition;

2
src/Avalonia.Controls.DataGrid/DataGrid.cs

@ -3920,6 +3920,8 @@ namespace Avalonia.Controls
dataGridColumn: CurrentColumn,
dataGridRow: EditingRow,
dataGridCell: editingCell);
EditingRow.InvalidateDesiredHeight();
}
// We're done, so raise the CellEditEnded event

5
src/Avalonia.Controls.DataGrid/DataGridRow.cs

@ -767,6 +767,11 @@ namespace Avalonia.Controls
}
}
internal void InvalidateDesiredHeight()
{
_cellsElement?.InvalidateDesiredHeight();
}
internal void ResetGridLine()
{
_bottomGridLine = null;

5
src/Avalonia.Controls.DataGrid/Primitives/DataGridCellsPresenter.cs

@ -299,6 +299,11 @@ namespace Avalonia.Controls.Primitives
DesiredHeight = 0;
}
internal void InvalidateDesiredHeight()
{
DesiredHeight = 0;
}
private bool ShouldDisplayCell(DataGridColumn column, double frozenLeftEdge, double scrollingLeftEdge)
{
if (!column.IsVisible)

2
src/Avalonia.Controls.DataGrid/Themes/Default.xaml

@ -188,7 +188,7 @@
</Style>
<Style Selector="DataGrid">
<Setter Property="RowBackground" Value="{DynamicResource ThemeAccentBrush4}" />
<Setter Property="RowBackground" Value="{DynamicResource SystemAccentColorDark2}" />
<Setter Property="AlternatingRowBackground" Value="#00FFFFFF" />
<Setter Property="Background" Value="{DynamicResource ThemeBackgroundBrush}" />
<Setter Property="HeadersVisibility" Value="Column" />

23
src/Avalonia.Controls/AcrylicPlatformCompensationLevels.cs

@ -0,0 +1,23 @@
namespace Avalonia.Controls
{
/// <summary>
/// Defines compensation levels for the platform depending on the transparency level.
/// It controls the base opacity level of the 'tracing paper' layer that compensates
/// for low blur radius.
/// </summary>
public struct AcrylicPlatformCompensationLevels
{
public AcrylicPlatformCompensationLevels(double transparent, double blurred, double acrylic)
{
TransparentLevel = transparent;
BlurLevel = blurred;
AcrylicBlurLevel = acrylic;
}
public double TransparentLevel { get; }
public double BlurLevel { get; }
public double AcrylicBlurLevel { get; }
}
}

86
src/Avalonia.Controls/Chrome/CaptionButtons.cs

@ -0,0 +1,86 @@
using System;
using System.Reactive.Disposables;
using Avalonia.Controls.Primitives;
#nullable enable
namespace Avalonia.Controls.Chrome
{
/// <summary>
/// Draws window minimize / maximize / close buttons in a <see cref="TitleBar"/> when managed client decorations are enabled.
/// </summary>
public class CaptionButtons : TemplatedControl
{
private CompositeDisposable? _disposables;
private Window? _hostWindow;
public void Attach(Window hostWindow)
{
if (_disposables == null)
{
_hostWindow = hostWindow;
_disposables = new CompositeDisposable
{
_hostWindow.GetObservable(Window.WindowStateProperty)
.Subscribe(x =>
{
PseudoClasses.Set(":minimized", x == WindowState.Minimized);
PseudoClasses.Set(":normal", x == WindowState.Normal);
PseudoClasses.Set(":maximized", x == WindowState.Maximized);
PseudoClasses.Set(":fullscreen", x == WindowState.FullScreen);
})
};
}
}
public void Detach()
{
if (_disposables != null)
{
var layer = ChromeOverlayLayer.GetOverlayLayer(_hostWindow);
layer?.Children.Remove(this);
_disposables.Dispose();
_disposables = null;
}
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
var closeButton = e.NameScope.Get<Panel>("PART_CloseButton");
var restoreButton = e.NameScope.Get<Panel>("PART_RestoreButton");
var minimiseButton = e.NameScope.Get<Panel>("PART_MinimiseButton");
var fullScreenButton = e.NameScope.Get<Panel>("PART_FullScreenButton");
closeButton.PointerReleased += (sender, e) => _hostWindow?.Close();
restoreButton.PointerReleased += (sender, e) =>
{
if (_hostWindow != null)
{
_hostWindow.WindowState = _hostWindow.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
}
};
minimiseButton.PointerReleased += (sender, e) =>
{
if (_hostWindow != null)
{
_hostWindow.WindowState = WindowState.Minimized;
}
};
fullScreenButton.PointerReleased += (sender, e) =>
{
if (_hostWindow != null)
{
_hostWindow.WindowState = _hostWindow.WindowState == WindowState.FullScreen ? WindowState.Normal : WindowState.FullScreen;
}
};
}
}
}

117
src/Avalonia.Controls/Chrome/TitleBar.cs

@ -0,0 +1,117 @@
using System;
using System.Reactive.Disposables;
using Avalonia.Controls.Primitives;
#nullable enable
namespace Avalonia.Controls.Chrome
{
/// <summary>
/// Draws a titlebar when managed client decorations are enabled.
/// </summary>
public class TitleBar : TemplatedControl
{
private CompositeDisposable? _disposables;
private readonly Window? _hostWindow;
private CaptionButtons? _captionButtons;
public TitleBar(Window hostWindow)
{
_hostWindow = hostWindow;
}
public TitleBar()
{
}
public void Attach()
{
if (_disposables == null)
{
var layer = ChromeOverlayLayer.GetOverlayLayer(_hostWindow);
layer?.Children.Add(this);
if (_hostWindow != null)
{
_disposables = new CompositeDisposable
{
_hostWindow.GetObservable(Window.WindowDecorationMarginProperty)
.Subscribe(x => UpdateSize()),
_hostWindow.GetObservable(Window.ExtendClientAreaTitleBarHeightHintProperty)
.Subscribe(x => UpdateSize()),
_hostWindow.GetObservable(Window.OffScreenMarginProperty)
.Subscribe(x => UpdateSize()),
_hostWindow.GetObservable(Window.WindowStateProperty)
.Subscribe(x =>
{
PseudoClasses.Set(":minimized", x == WindowState.Minimized);
PseudoClasses.Set(":normal", x == WindowState.Normal);
PseudoClasses.Set(":maximized", x == WindowState.Maximized);
PseudoClasses.Set(":fullscreen", x == WindowState.FullScreen);
})
};
_captionButtons?.Attach(_hostWindow);
}
UpdateSize();
}
}
private void UpdateSize()
{
if (_hostWindow != null)
{
Margin = new Thickness(
_hostWindow.OffScreenMargin.Left,
_hostWindow.OffScreenMargin.Top,
_hostWindow.OffScreenMargin.Right,
_hostWindow.OffScreenMargin.Bottom);
if (_hostWindow.WindowState != WindowState.FullScreen)
{
Height = _hostWindow.WindowDecorationMargin.Top;
if (_captionButtons != null)
{
_captionButtons.Height = Height;
}
}
}
}
public void Detach()
{
if (_disposables != null)
{
var layer = ChromeOverlayLayer.GetOverlayLayer(_hostWindow);
layer?.Children.Remove(this);
_disposables.Dispose();
_disposables = null;
_captionButtons?.Detach();
}
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_captionButtons = e.NameScope.Get<CaptionButtons>("PART_CaptionButtons");
if (_hostWindow != null)
{
_captionButtons.Attach(_hostWindow);
}
UpdateSize();
}
}
}

31
src/Avalonia.Controls/ComboBox.cs

@ -7,6 +7,7 @@ using Avalonia.Controls.Shapes;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.VisualTree;
@ -63,6 +64,18 @@ namespace Avalonia.Controls
public static readonly StyledProperty<IBrush> PlaceholderForegroundProperty =
AvaloniaProperty.Register<ComboBox, IBrush>(nameof(PlaceholderForeground));
/// <summary>
/// Defines the <see cref="HorizontalContentAlignment"/> property.
/// </summary>
public static readonly StyledProperty<HorizontalAlignment> HorizontalContentAlignmentProperty =
ContentControl.HorizontalContentAlignmentProperty.AddOwner<ComboBox>();
/// <summary>
/// Defines the <see cref="VerticalContentAlignment"/> property.
/// </summary>
public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty =
ContentControl.VerticalContentAlignmentProperty.AddOwner<ComboBox>();
private bool _isDropDownOpen;
private Popup _popup;
private object _selectionBoxItem;
@ -133,6 +146,24 @@ namespace Avalonia.Controls
set { SetValue(VirtualizationModeProperty, value); }
}
/// <summary>
/// Gets or sets the horizontal alignment of the content within the control.
/// </summary>
public HorizontalAlignment HorizontalContentAlignment
{
get { return GetValue(HorizontalContentAlignmentProperty); }
set { SetValue(HorizontalContentAlignmentProperty, value); }
}
/// <summary>
/// Gets or sets the vertical alignment of the content within the control.
/// </summary>
public VerticalAlignment VerticalContentAlignment
{
get { return GetValue(VerticalContentAlignmentProperty); }
set { SetValue(VerticalContentAlignmentProperty, value); }
}
/// <inheritdoc/>
protected override IItemContainerGenerator CreateItemContainerGenerator()
{

3
src/Avalonia.Controls/Embedding/Offscreen/OffscreenTopLevelImpl.cs

@ -52,6 +52,9 @@ namespace Avalonia.Controls.Embedding.Offscreen
public Action<WindowTransparencyLevel> TransparencyLevelChanged { get; set; }
/// <inheritdoc/>
public AcrylicPlatformCompensationLevels AcrylicCompensationLevels { get; } = new AcrylicPlatformCompensationLevels(1, 1, 1);
public void SetInputRoot(IInputRoot inputRoot) => InputRoot = inputRoot;
public virtual Point PointToClient(PixelPoint point) => point.ToPoint(1);

117
src/Avalonia.Controls/ExperimentalAcrylicBorder.cs

@ -0,0 +1,117 @@
using Avalonia.Controls.Utils;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Platform;
using System;
namespace Avalonia.Controls
{
public class ExperimentalAcrylicBorder : Decorator
{
public static readonly StyledProperty<CornerRadius> CornerRadiusProperty =
Border.CornerRadiusProperty.AddOwner<ExperimentalAcrylicBorder>();
public static readonly StyledProperty<ExperimentalAcrylicMaterial> MaterialProperty =
AvaloniaProperty.Register<ExperimentalAcrylicBorder, ExperimentalAcrylicMaterial>(nameof(Material));
private readonly BorderRenderHelper _borderRenderHelper = new BorderRenderHelper();
private IDisposable _subscription;
static ExperimentalAcrylicBorder()
{
AffectsRender<ExperimentalAcrylicBorder>(
MaterialProperty,
CornerRadiusProperty);
}
/// <summary>
/// Gets or sets the radius of the border rounded corners.
/// </summary>
public CornerRadius CornerRadius
{
get { return GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
public ExperimentalAcrylicMaterial Material
{
get => GetValue(MaterialProperty);
set => SetValue(MaterialProperty, value);
}
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
var tl = (e.Root as TopLevel);
_subscription = tl.GetObservable(TopLevel.ActualTransparencyLevelProperty)
.Subscribe(x =>
{
switch (x)
{
case WindowTransparencyLevel.Transparent:
case WindowTransparencyLevel.None:
Material.PlatformTransparencyCompensationLevel = tl.PlatformImpl.AcrylicCompensationLevels.TransparentLevel;
break;
case WindowTransparencyLevel.Blur:
Material.PlatformTransparencyCompensationLevel = tl.PlatformImpl.AcrylicCompensationLevels.BlurLevel;
break;
case WindowTransparencyLevel.AcrylicBlur:
Material.PlatformTransparencyCompensationLevel = tl.PlatformImpl.AcrylicCompensationLevels.AcrylicBlurLevel;
break;
}
});
}
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTree(e);
_subscription?.Dispose();
}
public override void Render(DrawingContext context)
{
if (context.PlatformImpl is IDrawingContextWithAcrylicLikeSupport idc)
{
var cornerRadius = CornerRadius;
idc.DrawRectangle(
Material,
new RoundedRect(
new Rect(Bounds.Size),
cornerRadius.TopLeft, cornerRadius.TopRight,
cornerRadius.BottomRight, cornerRadius.BottomLeft));
}
else
{
_borderRenderHelper.Render(context, Bounds.Size, new Thickness(), CornerRadius, new SolidColorBrush(Material.FallbackColor), null, default);
}
}
/// <summary>
/// Measures the control.
/// </summary>
/// <param name="availableSize">The available size.</param>
/// <returns>The desired size of the control.</returns>
protected override Size MeasureOverride(Size availableSize)
{
return LayoutHelper.MeasureChild(Child, availableSize, Padding);
}
/// <summary>
/// Arranges the control's child.
/// </summary>
/// <param name="finalSize">The size allocated to the control.</param>
/// <returns>The space taken.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
return LayoutHelper.ArrangeChild(Child, finalSize, Padding);
}
}
}

38
src/Avalonia.Controls/Platform/ExtendClientAreaChromeHints.cs

@ -0,0 +1,38 @@
using System;
namespace Avalonia.Platform
{
/// <summary>
/// Hint for Window Chrome when ClientArea is Extended.
/// </summary>
[Flags]
public enum ExtendClientAreaChromeHints
{
/// <summary>
/// The will be no chrome at all.
/// </summary>
NoChrome,
/// <summary>
/// The default for the platform.
/// </summary>
Default = SystemChrome,
/// <summary>
/// Use SystemChrome
/// </summary>
SystemChrome = 0x01,
/// <summary>
/// Use system chrome where possible. OSX system chrome is used, Windows managed chrome is used.
/// This is because Windows Chrome can not be shown ontop of user content.
/// </summary>
PreferSystemChrome = 0x02,
/// <summary>
/// On OSX the titlebar is the thicker toolbar kind. Causes traffic lights to be positioned
/// slightly lower than normal.
/// </summary>
OSXThickTitleBar = 0x08,
}
}

5
src/Avalonia.Controls/Platform/ITopLevelImpl.cs

@ -127,5 +127,10 @@ namespace Avalonia.Platform
/// Gets the current <see cref="WindowTransparencyLevel"/> of the TopLevel.
/// </summary>
WindowTransparencyLevel TransparencyLevel { get; }
/// <summary>
/// Gets the <see cref="AcrylicPlatformCompensationLevels"/> for the platform.
/// </summary>
AcrylicPlatformCompensationLevels AcrylicCompensationLevels { get; }
}
}

46
src/Avalonia.Controls/Platform/IWindowImpl.cs

@ -68,6 +68,34 @@ namespace Avalonia.Platform
/// </summary>
Func<bool> Closing { get; set; }
/// <summary>
/// Gets a value to indicate if the platform was able to extend client area to non-client area.
/// </summary>
bool IsClientAreaExtendedToDecorations { get; }
/// <summary>
/// Gets or Sets an action that is called whenever one of the extend client area properties changed.
/// </summary>
Action<bool> ExtendClientAreaToDecorationsChanged { get; set; }
/// <summary>
/// Gets a flag that indicates if Managed decorations i.e. caption buttons are required.
/// This property is used when <see cref="IsClientAreaExtendedToDecorations"/> is set.
/// </summary>
bool NeedsManagedDecorations { get; }
/// <summary>
/// Gets a thickness that describes the amount each side of the non-client area extends into the client area.
/// It includes the titlebar.
/// </summary>
Thickness ExtendedMargins { get; }
/// <summary>
/// Gets a thickness that describes the margin around the window that is offscreen.
/// This may happen when a window is maximized and <see cref="IsClientAreaExtendedToDecorations"/> is set.
/// </summary>
Thickness OffScreenMargin { get; }
/// <summary>
/// Starts moving a window with left button being held. Should be called from left mouse button press event handler.
/// </summary>
@ -94,5 +122,23 @@ namespace Avalonia.Platform
/// </summary>
///
void SetMinMaxSize(Size minSize, Size maxSize);
/// <summary>
/// Sets if the ClientArea is extended into the non-client area.
/// </summary>
/// <param name="extendIntoClientAreaHint">true to enable, false to disable</param>
void SetExtendClientAreaToDecorationsHint(bool extendIntoClientAreaHint);
/// <summary>
/// Sets hints that configure how the client area extends.
/// </summary>
/// <param name="hints"></param>
void SetExtendClientAreaChromeHints(ExtendClientAreaChromeHints hints);
/// <summary>
/// Sets how big the non-client titlebar area should be.
/// </summary>
/// <param name="titleBarHeight">-1 for platform default, otherwise the height in DIPs.</param>
void SetExtendClientAreaTitleBarHeightHint(double titleBarHeight);
}
}

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

@ -95,6 +95,7 @@ namespace Avalonia.Controls.Presenters
static ContentPresenter()
{
AffectsRender<ContentPresenter>(BackgroundProperty, BorderBrushProperty, BorderThicknessProperty, CornerRadiusProperty);
AffectsArrange<ContentPresenter>(HorizontalContentAlignmentProperty, VerticalContentAlignmentProperty);
AffectsMeasure<ContentPresenter>(BorderThicknessProperty, PaddingProperty);
ContentProperty.Changed.AddClassHandler<ContentPresenter>((x, e) => x.ContentChanged(e));
ContentTemplateProperty.Changed.AddClassHandler<ContentPresenter>((x, e) => x.ContentChanged(e));

4
src/Avalonia.Controls/Presenters/TextPresenter.cs

@ -273,7 +273,7 @@ namespace Avalonia.Controls.Presenters
return new FormattedText
{
Constraint = constraint,
Typeface = FontManager.Current?.GetOrAddTypeface(FontFamily, FontWeight, FontStyle),
Typeface = FontManager.Current?.GetOrAddTypeface(FontFamily, FontStyle, FontWeight),
FontSize = FontSize,
Text = text ?? string.Empty,
TextAlignment = TextAlignment,
@ -490,7 +490,7 @@ namespace Avalonia.Controls.Presenters
return new FormattedText
{
Text = "X",
Typeface = FontManager.Current?.GetOrAddTypeface(FontFamily, FontWeight, FontStyle),
Typeface = FontManager.Current?.GetOrAddTypeface(FontFamily, FontStyle, FontWeight),
FontSize = FontSize,
TextAlignment = TextAlignment,
Constraint = availableSize,

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

@ -97,9 +97,7 @@ namespace Avalonia.Controls.Primitives
{
var lastLine = TextLayout.TextLines[TextLayout.TextLines.Count - 1];
var offsetX = lastLine.LineMetrics.BaselineOrigin.X;
var lineX = offsetX + lastLine.LineMetrics.Size.Width;
var lineX = lastLine.LineMetrics.Size.Width;
var lineY = Bounds.Height - lastLine.LineMetrics.Size.Height;
@ -110,32 +108,33 @@ namespace Avalonia.Controls.Primitives
foreach (var textLine in TextLayout.TextLines)
{
if (textLine.Text.End < textPosition)
if (textLine.TextRange.End < textPosition)
{
currentY += textLine.LineMetrics.Size.Height;
continue;
}
var currentX = textLine.LineMetrics.BaselineOrigin.X;
var currentX = 0.0;
foreach (var textRun in textLine.TextRuns)
{
if (!(textRun is ShapedTextRun shapedRun))
if (!(textRun is ShapedTextCharacters shapedTextCharacters))
{
continue;
}
if (shapedRun.GlyphRun.Characters.End < textPosition)
if (shapedTextCharacters.GlyphRun.Characters.End < textPosition)
{
currentX += shapedRun.GlyphRun.Bounds.Width;
currentX += shapedTextCharacters.GlyphRun.Bounds.Width;
continue;
}
var characterHit = shapedRun.GlyphRun.FindNearestCharacterHit(textPosition, out var width);
var characterHit =
shapedTextCharacters.GlyphRun.FindNearestCharacterHit(textPosition, out var width);
var distance = shapedRun.GlyphRun.GetDistanceFromCharacterHit(characterHit);
var distance = shapedTextCharacters.GlyphRun.GetDistanceFromCharacterHit(characterHit);
currentX += distance - width;
@ -144,7 +143,7 @@ namespace Avalonia.Controls.Primitives
width = 0.0;
}
return new Rect(currentX, currentY, width, shapedRun.GlyphRun.Bounds.Height);
return new Rect(currentX, currentY, width, shapedTextCharacters.GlyphRun.Bounds.Height);
}
}

29
src/Avalonia.Controls/Primitives/ChromeOverlayLayer.cs

@ -0,0 +1,29 @@
using System.Linq;
using Avalonia.Rendering;
using Avalonia.VisualTree;
#nullable enable
namespace Avalonia.Controls.Primitives
{
public class ChromeOverlayLayer : Panel, ICustomSimpleHitTest
{
public static ChromeOverlayLayer? GetOverlayLayer(IVisual visual)
{
foreach (var v in visual.GetVisualAncestors())
if (v is VisualLayerManager vlm)
if (vlm.OverlayLayer != null)
return vlm.ChromeOverlayLayer;
if (visual is TopLevel tl)
{
var layers = tl.GetVisualDescendants().OfType<VisualLayerManager>().FirstOrDefault();
return layers?.ChromeOverlayLayer;
}
return null;
}
public bool HitTest(Point point) => Children.HitTestCustom(point);
}
}

9
src/Avalonia.Controls/Primitives/Track.cs

@ -353,6 +353,15 @@ namespace Avalonia.Controls.Primitives
var trackLength = isVertical ? arrangeSize.Height : arrangeSize.Width;
double thumbMinLength = 10;
StyledProperty<double> minLengthProperty = isVertical ? MinHeightProperty : MinWidthProperty;
var thumb = Thumb;
if (thumb != null && thumb.IsSet(minLengthProperty))
{
thumbMinLength = thumb.GetValue(minLengthProperty);
}
thumbLength = trackLength * viewportSize / extent;
CoerceLength(ref thumbLength, trackLength);
thumbLength = Math.Max(thumbMinLength, thumbLength);

15
src/Avalonia.Controls/Primitives/VisualLayerManager.cs

@ -6,7 +6,9 @@ namespace Avalonia.Controls.Primitives
public class VisualLayerManager : Decorator
{
private const int AdornerZIndex = int.MaxValue - 100;
private const int OverlayZIndex = int.MaxValue - 99;
private const int ChromeZIndex = int.MaxValue - 99;
private const int OverlayZIndex = int.MaxValue - 98;
private ILogicalRoot _logicalRoot;
private readonly List<Control> _layers = new List<Control>();
@ -24,6 +26,17 @@ namespace Avalonia.Controls.Primitives
}
}
public ChromeOverlayLayer ChromeOverlayLayer
{
get
{
var rv = FindLayer<ChromeOverlayLayer>();
if (rv == null)
AddLayer(rv = new ChromeOverlayLayer(), ChromeZIndex);
return rv;
}
}
public OverlayLayer OverlayLayer
{
get

1
src/Avalonia.Controls/Properties/AssemblyInfo.cs

@ -13,3 +13,4 @@ using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui", "Avalonia.Controls.Shapes")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui", "Avalonia.Controls.Templates")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui", "Avalonia.Controls.Notifications")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui", "Avalonia.Controls.Chrome")]

546
src/Avalonia.Controls/RelativePanel.AttachedProperties.cs

@ -0,0 +1,546 @@
using Avalonia.Layout;
#nullable enable
namespace Avalonia.Controls
{
public partial class RelativePanel
{
private static void OnAlignPropertiesChanged(AvaloniaObject d, AvaloniaPropertyChangedEventArgs e)
{
if (d is Layoutable layoutable && layoutable.Parent is Layoutable layoutableParent)
{
layoutableParent.InvalidateArrange();
}
}
static RelativePanel()
{
ClipToBoundsProperty.OverrideDefaultValue<RelativePanel>(true);
AboveProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
AlignBottomWithPanelProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
AlignBottomWithProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
AlignHorizontalCenterWithPanelProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
AlignHorizontalCenterWithProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
AlignLeftWithPanelProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
AlignLeftWithProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
AlignRightWithPanelProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
AlignRightWithProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
AlignTopWithPanelProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
AlignTopWithProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
AlignVerticalCenterWithPanelProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
AlignVerticalCenterWithProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
BelowProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
LeftOfProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
LeftOfProperty.Changed.AddClassHandler<Layoutable>(OnAlignPropertiesChanged);
}
/// <summary>
/// Gets the value of the RelativePanel.Above XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.Above XAML attached property value of the specified object.
/// (The element to position this element above.)
/// </returns>
[ResolveByName]
public static object GetAbove(AvaloniaObject obj)
{
return (object)obj.GetValue(AboveProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.Above XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">The value to set. (The element to position this element above.)</param>
public static void SetAbove(AvaloniaObject obj, object value)
{
obj.SetValue(AboveProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.AboveProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<object> AboveProperty =
AvaloniaProperty.RegisterAttached<Layoutable, object>("Above", typeof(RelativePanel));
/// <summary>
/// Gets the value of the RelativePanel.AlignBottomWithPanel XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.AlignBottomWithPanel XAML attached property value of the specified
/// object. (true to align this element's bottom edge with the panel's bottom edge;
/// otherwise, false.)
/// </returns>
public static bool GetAlignBottomWithPanel(AvaloniaObject obj)
{
return (bool)obj.GetValue(AlignBottomWithPanelProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.Above XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">
/// The value to set. (true to align this element's bottom edge with the panel's
/// bottom edge; otherwise, false.)
/// </param>
public static void SetAlignBottomWithPanel(AvaloniaObject obj, bool value)
{
obj.SetValue(AlignBottomWithPanelProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.AlignBottomWithPanelProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<bool> AlignBottomWithPanelProperty =
AvaloniaProperty.RegisterAttached<Layoutable, bool>("AlignBottomWithPanel", typeof(RelativePanel));
/// <summary>
/// Gets the value of the RelativePanel.AlignBottomWith XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.AlignBottomWith XAML attached property value of the specified object.
/// (The element to align this element's bottom edge with.)
/// </returns>
[ResolveByName]
public static object GetAlignBottomWith(AvaloniaObject obj)
{
return (object)obj.GetValue(AlignBottomWithProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.Above XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">The value to set. (The element to align this element's bottom edge with.)</param>
public static void SetAlignBottomWith(AvaloniaObject obj, object value)
{
obj.SetValue(AlignBottomWithProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.AlignBottomWithProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<object> AlignBottomWithProperty =
AvaloniaProperty.RegisterAttached<Layoutable, object>("AlignBottomWith", typeof(RelativePanel));
/// <summary>
/// Gets the value of the RelativePanel.AlignHorizontalCenterWithPanel XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.AlignHorizontalCenterWithPanel XAML attached property value
/// of the specified object. (true to horizontally center this element in the panel;
/// otherwise, false.)
/// </returns>
public static bool GetAlignHorizontalCenterWithPanel(AvaloniaObject obj)
{
return (bool)obj.GetValue(AlignHorizontalCenterWithPanelProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.Above XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">
/// The value to set. (true to horizontally center this element in the panel; otherwise,
/// false.)
/// </param>
public static void SetAlignHorizontalCenterWithPanel(AvaloniaObject obj, bool value)
{
obj.SetValue(AlignHorizontalCenterWithPanelProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.AlignHorizontalCenterWithPanelProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<bool> AlignHorizontalCenterWithPanelProperty =
AvaloniaProperty.RegisterAttached<Layoutable, bool>("AlignHorizontalCenterWithPanel", typeof(RelativePanel), false);
/// <summary>
/// Gets the value of the RelativePanel.AlignHorizontalCenterWith XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.AlignHorizontalCenterWith XAML attached property value of the
/// specified object. (The element to align this element's horizontal center with.)
/// </returns>
[ResolveByName]
public static object GetAlignHorizontalCenterWith(AvaloniaObject obj)
{
return (object)obj.GetValue(AlignHorizontalCenterWithProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.Above XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">The value to set. (The element to align this element's horizontal center with.)</param>
public static void SetAlignHorizontalCenterWith(AvaloniaObject obj, object value)
{
obj.SetValue(AlignHorizontalCenterWithProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.AlignHorizontalCenterWithProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<object> AlignHorizontalCenterWithProperty =
AvaloniaProperty.RegisterAttached<Layoutable, object>("AlignHorizontalCenterWith", typeof(object), typeof(RelativePanel));
/// <summary>
/// Gets the value of the RelativePanel.AlignLeftWithPanel XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.AlignLeftWithPanel XAML attached property value of the specified
/// object. (true to align this element's left edge with the panel's left edge; otherwise,
/// false.)
/// </returns>
public static bool GetAlignLeftWithPanel(AvaloniaObject obj)
{
return (bool)obj.GetValue(AlignLeftWithPanelProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.Above XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">
/// The value to set. (true to align this element's left edge with the panel's left
/// edge; otherwise, false.)
/// </param>
public static void SetAlignLeftWithPanel(AvaloniaObject obj, bool value)
{
obj.SetValue(AlignLeftWithPanelProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.AlignLeftWithPanelProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<bool> AlignLeftWithPanelProperty =
AvaloniaProperty.RegisterAttached<Layoutable, bool>("AlignLeftWithPanel", typeof(RelativePanel), false);
/// <summary>
/// Gets the value of the RelativePanel.AlignLeftWith XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.AlignLeftWith XAML attached property value of the specified
/// object. (The element to align this element's left edge with.)
/// </returns>
[ResolveByName]
public static object GetAlignLeftWith(AvaloniaObject obj)
{
return (object)obj.GetValue(AlignLeftWithProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.Above XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">The value to set. (The element to align this element's left edge with.)</param>
public static void SetAlignLeftWith(AvaloniaObject obj, object value)
{
obj.SetValue(AlignLeftWithProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.AlignLeftWithProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<object> AlignLeftWithProperty =
AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("AlignLeftWith");
/// <summary>
/// Gets the value of the RelativePanel.AlignRightWithPanel XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.AlignRightWithPanel XAML attached property value of the specified
/// object. (true to align this element's right edge with the panel's right edge;
/// otherwise, false.)
/// </returns>
public static bool GetAlignRightWithPanel(AvaloniaObject obj)
{
return (bool)obj.GetValue(AlignRightWithPanelProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.Above XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">
/// The value to set. (true to align this element's right edge with the panel's right
/// edge; otherwise, false.)
/// </param>
public static void SetAlignRightWithPanel(AvaloniaObject obj, bool value)
{
obj.SetValue(AlignRightWithPanelProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.AlignRightWithPanelProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<bool> AlignRightWithPanelProperty =
AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, bool>("AlignRightWithPanel", false);
/// <summary>
/// Gets the value of the RelativePanel.AlignRightWith XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.AlignRightWith XAML attached property value of the specified
/// object. (The element to align this element's right edge with.)
/// </returns>
[ResolveByName]
public static object GetAlignRightWith(AvaloniaObject obj)
{
return (object)obj.GetValue(AlignRightWithProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.AlignRightWith XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">The value to set. (The element to align this element's right edge with.)</param>
public static void SetAlignRightWith(AvaloniaObject obj, object value)
{
obj.SetValue(AlignRightWithProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.AlignRightWithProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<object> AlignRightWithProperty =
AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("AlignRightWith");
/// <summary>
/// Gets the value of the RelativePanel.AlignTopWithPanel XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.AlignTopWithPanel XAML attached property value of the specified
/// object. (true to align this element's top edge with the panel's top edge; otherwise,
/// false.)
/// </returns>
public static bool GetAlignTopWithPanel(AvaloniaObject obj)
{
return (bool)obj.GetValue(AlignTopWithPanelProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.AlignTopWithPanel XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">
/// The value to set. (true to align this element's top edge with the panel's top
/// edge; otherwise, false.)
/// </param>
public static void SetAlignTopWithPanel(AvaloniaObject obj, bool value)
{
obj.SetValue(AlignTopWithPanelProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.AlignTopWithPanelProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<bool> AlignTopWithPanelProperty =
AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, bool>("AlignTopWithPanel", false);
/// <summary>
/// Gets the value of the RelativePanel.AlignTopWith XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>The value to set. (The element to align this element's top edge with.)</returns>
[ResolveByName]
public static object GetAlignTopWith(AvaloniaObject obj)
{
return (object)obj.GetValue(AlignTopWithProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.AlignTopWith XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">The value to set. (The element to align this element's top edge with.)</param>
public static void SetAlignTopWith(AvaloniaObject obj, object value)
{
obj.SetValue(AlignTopWithProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.AlignTopWithProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<object> AlignTopWithProperty =
AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("AlignTopWith");
/// <summary>
/// Gets the value of the RelativePanel.AlignVerticalCenterWithPanel XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.AlignVerticalCenterWithPanel XAML attached property value of
/// the specified object. (true to vertically center this element in the panel; otherwise,
/// false.)
/// </returns>
public static bool GetAlignVerticalCenterWithPanel(AvaloniaObject obj)
{
return (bool)obj.GetValue(AlignVerticalCenterWithPanelProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.AlignVerticalCenterWithPanel XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">
/// The value to set. (true to vertically center this element in the panel; otherwise,
/// false.)
/// </param>
public static void SetAlignVerticalCenterWithPanel(AvaloniaObject obj, bool value)
{
obj.SetValue(AlignVerticalCenterWithPanelProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.AlignVerticalCenterWithPanelProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<bool> AlignVerticalCenterWithPanelProperty =
AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, bool>("AlignVerticalCenterWithPanel", false);
/// <summary>
/// Gets the value of the RelativePanel.AlignVerticalCenterWith XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>The value to set. (The element to align this element's vertical center with.)</returns>
[ResolveByName]
public static object GetAlignVerticalCenterWith(AvaloniaObject obj)
{
return (object)obj.GetValue(AlignVerticalCenterWithProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.AlignVerticalCenterWith XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">The value to set. (The element to align this element's horizontal center with.)</param>
public static void SetAlignVerticalCenterWith(AvaloniaObject obj, object value)
{
obj.SetValue(AlignVerticalCenterWithProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.AlignVerticalCenterWithProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<object> AlignVerticalCenterWithProperty =
AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("AlignVerticalCenterWith");
/// <summary>
/// Gets the value of the RelativePanel.Below XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.Below XAML attached property value of the specified object.
/// (The element to position this element below.)
/// </returns>
[ResolveByName]
public static object GetBelow(AvaloniaObject obj)
{
return (object)obj.GetValue(BelowProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.Above XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">The value to set. (The element to position this element below.)</param>
public static void SetBelow(AvaloniaObject obj, object value)
{
obj.SetValue(BelowProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.BelowProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<object> BelowProperty =
AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("Below");
/// <summary>
/// Gets the value of the RelativePanel.LeftOf XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.LeftOf XAML attached property value of the specified object.
/// (The element to position this element to the left of.)
/// </returns>
[ResolveByName]
public static object GetLeftOf(AvaloniaObject obj)
{
return (object)obj.GetValue(LeftOfProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.LeftOf XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">The value to set. (The element to position this element to the left of.)</param>
public static void SetLeftOf(AvaloniaObject obj, object value)
{
obj.SetValue(LeftOfProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.LeftOfProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<object> LeftOfProperty =
AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("LeftOf");
/// <summary>
/// Gets the value of the RelativePanel.RightOf XAML attached property for the target element.
/// </summary>
/// <param name="obj">The object from which the property value is read.</param>
/// <returns>
/// The RelativePanel.RightOf XAML attached property value of the specified object.
/// (The element to position this element to the right of.)
/// </returns>
[ResolveByName]
public static object GetRightOf(AvaloniaObject obj)
{
return (object)obj.GetValue(RightOfProperty);
}
/// <summary>
/// Sets the value of the RelativePanel.RightOf XAML attached property for a target element.
/// </summary>
/// <param name="obj">The object to which the property value is written.</param>
/// <param name="value">The value to set. (The element to position this element to the right of.)</param>
public static void SetRightOf(AvaloniaObject obj, object value)
{
obj.SetValue(RightOfProperty, value);
}
/// <summary>
/// Identifies the <see cref="RelativePanel.RightOfProperty"/> XAML attached property.
/// </summary>
public static readonly AttachedProperty<object> RightOfProperty =
AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("RightOf");
}
}

353
src/Avalonia.Controls/RelativePanel.cs

@ -0,0 +1,353 @@
/// Ported from https://github.com/HandyOrg/HandyControl/blob/master/src/Shared/HandyControl_Shared/Controls/Panel/RelativePanel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Layout;
#nullable enable
namespace Avalonia.Controls
{
public partial class RelativePanel : Panel
{
private readonly Graph _childGraph;
public RelativePanel() => _childGraph = new Graph();
protected override Size MeasureOverride(Size availableSize)
{
foreach (var child in Children)
{
child?.Measure(availableSize);
}
return availableSize;
}
protected override Size ArrangeOverride(Size arrangeSize)
{
_childGraph.Reset(arrangeSize);
foreach (var child in Children.OfType<Layoutable>())
{
if (child == null)
continue;
var node = _childGraph.AddNode(child);
node.AlignLeftWithNode = _childGraph.AddLink(node, GetDependencyElement(AlignLeftWithProperty, child));
node.AlignTopWithNode = _childGraph.AddLink(node, GetDependencyElement(AlignTopWithProperty, child));
node.AlignRightWithNode = _childGraph.AddLink(node, GetDependencyElement(AlignRightWithProperty, child));
node.AlignBottomWithNode = _childGraph.AddLink(node, GetDependencyElement(AlignBottomWithProperty, child));
node.LeftOfNode = _childGraph.AddLink(node, GetDependencyElement(LeftOfProperty, child));
node.AboveNode = _childGraph.AddLink(node, GetDependencyElement(AboveProperty, child));
node.RightOfNode = _childGraph.AddLink(node, GetDependencyElement(RightOfProperty, child));
node.BelowNode = _childGraph.AddLink(node, GetDependencyElement(BelowProperty, child));
node.AlignHorizontalCenterWith = _childGraph.AddLink(node, GetDependencyElement(AlignHorizontalCenterWithProperty, child));
node.AlignVerticalCenterWith = _childGraph.AddLink(node, GetDependencyElement(AlignVerticalCenterWithProperty, child));
}
if (_childGraph.CheckCyclic())
{
throw new Exception("RelativePanel error: Circular dependency detected. Layout could not complete.");
}
var size = new Size();
foreach (var child in Children)
{
if (child.Bounds.Bottom > size.Height)
{
size = size.WithHeight(child.Bounds.Bottom);
}
if (child.Bounds.Right > size.Width)
{
size = size.WithWidth(child.Bounds.Right);
}
}
if (VerticalAlignment == VerticalAlignment.Stretch)
{
size = size.WithHeight(arrangeSize.Height);
}
if (HorizontalAlignment == HorizontalAlignment.Stretch)
{
size = size.WithWidth(arrangeSize.Width);
}
return size;
}
private Layoutable? GetDependencyElement(AvaloniaProperty property, AvaloniaObject child)
{
var dependency = child.GetValue(property);
if (dependency is Layoutable layoutable)
{
if (Children.Contains((ILayoutable)layoutable))
return layoutable;
throw new ArgumentException($"RelativePanel error: Element does not exist in the current context: {property.Name}");
}
return null;
}
private class GraphNode
{
public Point Position { get; set; }
public bool Arranged { get; set; }
public Layoutable Element { get; }
public HashSet<GraphNode> OutgoingNodes { get; }
public GraphNode? AlignLeftWithNode { get; set; }
public GraphNode? AlignTopWithNode { get; set; }
public GraphNode? AlignRightWithNode { get; set; }
public GraphNode? AlignBottomWithNode { get; set; }
public GraphNode? LeftOfNode { get; set; }
public GraphNode? AboveNode { get; set; }
public GraphNode? RightOfNode { get; set; }
public GraphNode? BelowNode { get; set; }
public GraphNode? AlignHorizontalCenterWith { get; set; }
public GraphNode? AlignVerticalCenterWith { get; set; }
public GraphNode(Layoutable element)
{
OutgoingNodes = new HashSet<GraphNode>();
Element = element;
}
}
private class Graph
{
private readonly Dictionary<AvaloniaObject, GraphNode> _nodeDic;
private Size _arrangeSize;
public Graph()
{
_nodeDic = new Dictionary<AvaloniaObject, GraphNode>();
}
public GraphNode? AddLink(GraphNode from, Layoutable? to)
{
if (to == null)
return null;
GraphNode nodeTo;
if (_nodeDic.ContainsKey(to))
{
nodeTo = _nodeDic[to];
}
else
{
nodeTo = new GraphNode(to);
_nodeDic[to] = nodeTo;
}
from.OutgoingNodes.Add(nodeTo);
return nodeTo;
}
public GraphNode AddNode(Layoutable value)
{
if (!_nodeDic.ContainsKey(value))
{
var node = new GraphNode(value);
_nodeDic.Add(value, node);
return node;
}
return _nodeDic[value];
}
public void Reset(Size arrangeSize)
{
_arrangeSize = arrangeSize;
_nodeDic.Clear();
}
public bool CheckCyclic() => CheckCyclic(_nodeDic.Values, null);
private bool CheckCyclic(IEnumerable<GraphNode> nodes, HashSet<Layoutable>? set)
{
set ??= new HashSet<Layoutable>();
foreach (var node in nodes)
{
if (!node.Arranged && node.OutgoingNodes.Count == 0)
{
ArrangeChild(node, true);
continue;
}
if (node.OutgoingNodes.All(item => item.Arranged))
{
ArrangeChild(node);
continue;
}
if (!set.Add(node.Element))
return true;
return CheckCyclic(node.OutgoingNodes, set);
}
return false;
}
private void ArrangeChild(GraphNode node, bool ignoneSibling = false)
{
var child = node.Element;
var childSize = child.DesiredSize;
var childPos = new Point();
if (GetAlignHorizontalCenterWithPanel(child))
{
childPos = childPos.WithX((_arrangeSize.Width - childSize.Width) / 2);
}
if (GetAlignVerticalCenterWithPanel(child))
{
childPos = childPos.WithY((_arrangeSize.Height - childSize.Height) / 2);
}
var alignLeftWithPanel = GetAlignLeftWithPanel(child);
var alignTopWithPanel = GetAlignTopWithPanel(child);
var alignRightWithPanel = GetAlignRightWithPanel(child);
var alignBottomWithPanel = GetAlignBottomWithPanel(child);
if (!ignoneSibling)
{
if (node.LeftOfNode != null)
{
childPos = childPos.WithX(node.LeftOfNode.Position.X - childSize.Width);
}
if (node.AboveNode != null)
{
childPos = childPos.WithY(node.AboveNode.Position.Y - childSize.Height);
}
if (node.RightOfNode != null)
{
childPos = childPos.WithX(node.RightOfNode.Position.X + node.RightOfNode.Element.DesiredSize.Width);
}
if (node.BelowNode != null)
{
childPos = childPos.WithY(node.BelowNode.Position.Y + node.BelowNode.Element.DesiredSize.Height);
}
if (node.AlignHorizontalCenterWith != null)
{
childPos = childPos.WithX(node.AlignHorizontalCenterWith.Position.X +
(node.AlignHorizontalCenterWith.Element.DesiredSize.Width - childSize.Width) / 2);
}
if (node.AlignVerticalCenterWith != null)
{
childPos = childPos.WithY(node.AlignVerticalCenterWith.Position.Y +
(node.AlignVerticalCenterWith.Element.DesiredSize.Height - childSize.Height) / 2);
}
if (node.AlignLeftWithNode != null)
{
childPos = childPos.WithX(node.AlignLeftWithNode.Position.X);
}
if (node.AlignTopWithNode != null)
{
childPos = childPos.WithY(node.AlignTopWithNode.Position.Y);
}
if (node.AlignRightWithNode != null)
{
childPos = childPos.WithX(node.AlignRightWithNode.Element.DesiredSize.Width + node.AlignRightWithNode.Position.X - childSize.Width);
}
if (node.AlignBottomWithNode != null)
{
childPos = childPos.WithY(node.AlignBottomWithNode.Element.DesiredSize.Height + node.AlignBottomWithNode.Position.Y - childSize.Height);
}
}
if (alignLeftWithPanel)
{
if (node.AlignRightWithNode != null)
{
childPos = childPos.WithX((node.AlignRightWithNode.Element.DesiredSize.Width + node.AlignRightWithNode.Position.X - childSize.Width) / 2);
}
else
{
childPos = childPos.WithX(0);
}
}
if (alignTopWithPanel)
{
if (node.AlignBottomWithNode != null)
{
childPos = childPos.WithY((node.AlignBottomWithNode.Element.DesiredSize.Height + node.AlignBottomWithNode.Position.Y - childSize.Height) / 2);
}
else
{
childPos = childPos.WithY(0);
}
}
if (alignRightWithPanel)
{
if (alignLeftWithPanel)
{
childPos = childPos.WithX((_arrangeSize.Width - childSize.Width) / 2);
}
else if (node.AlignLeftWithNode == null)
{
childPos = childPos.WithX(_arrangeSize.Width - childSize.Width);
}
else
{
childPos = childPos.WithX((_arrangeSize.Width + node.AlignLeftWithNode.Position.X - childSize.Width) / 2);
}
}
if (alignBottomWithPanel)
{
if (alignTopWithPanel)
{
childPos = childPos.WithY((_arrangeSize.Height - childSize.Height) / 2);
}
else if (node.AlignTopWithNode == null)
{
childPos = childPos.WithY(_arrangeSize.Height - childSize.Height);
}
else
{
childPos = childPos.WithY((_arrangeSize.Height + node.AlignTopWithNode.Position.Y - childSize.Height) / 2);
}
}
child.Arrange(new Rect(childPos.X, childPos.Y, childSize.Width, childSize.Height));
node.Position = childPos;
node.Arranged = true;
}
}
}
}

9
src/Avalonia.Controls/ResolveByNameAttribute.cs

@ -0,0 +1,9 @@
using System;
namespace Avalonia.Controls
{
public class ResolveByNameAttribute : Attribute
{
}
}

66
src/Avalonia.Controls/Slider.cs

@ -1,4 +1,5 @@
using System;
using Avalonia.Collections;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
@ -64,6 +65,12 @@ namespace Avalonia.Controls
public static readonly StyledProperty<TickPlacement> TickPlacementProperty =
AvaloniaProperty.Register<TickBar, TickPlacement>(nameof(TickPlacement), 0d);
/// <summary>
/// Defines the <see cref="TicksProperty"/> property.
/// </summary>
public static readonly StyledProperty<AvaloniaList<double>> TicksProperty =
TickBar.TicksProperty.AddOwner<Slider>();
// Slider required parts
private bool _isDragging = false;
private Track _track;
@ -83,7 +90,8 @@ namespace Avalonia.Controls
PressedMixin.Attach<Slider>();
OrientationProperty.OverrideDefaultValue(typeof(Slider), Orientation.Horizontal);
Thumb.DragStartedEvent.AddClassHandler<Slider>((x, e) => x.OnThumbDragStarted(e), RoutingStrategies.Bubble);
Thumb.DragCompletedEvent.AddClassHandler<Slider>((x, e) => x.OnThumbDragCompleted(e), RoutingStrategies.Bubble);
Thumb.DragCompletedEvent.AddClassHandler<Slider>((x, e) => x.OnThumbDragCompleted(e),
RoutingStrategies.Bubble);
}
/// <summary>
@ -94,6 +102,15 @@ namespace Avalonia.Controls
UpdatePseudoClasses(Orientation);
}
/// <summary>
/// Defines the ticks to be drawn on the tick bar.
/// </summary>
public AvaloniaList<double> Ticks
{
get => GetValue(TicksProperty);
set => SetValue(TicksProperty, value);
}
/// <summary>
/// Gets or sets the orientation of a <see cref="Slider"/>.
/// </summary>
@ -240,19 +257,50 @@ namespace Avalonia.Controls
/// <param name="value">Value that want to snap to closest Tick.</param>
private double SnapToTick(double value)
{
var previous = Minimum;
var next = Maximum;
if (TickFrequency > 0.0)
if (IsSnapToTickEnabled)
{
previous = Minimum + (Math.Round((value - Minimum) / TickFrequency) * TickFrequency);
next = Math.Min(Maximum, previous + TickFrequency);
double previous = Minimum;
double next = Maximum;
// This property is rarely set so let's try to avoid the GetValue
var ticks = Ticks;
// If ticks collection is available, use it.
// Note that ticks may be unsorted.
if ((ticks != null) && (ticks.Count > 0))
{
for (int i = 0; i < ticks.Count; i++)
{
double tick = ticks[i];
if (MathUtilities.AreClose(tick, value))
{
return value;
}
if (MathUtilities.LessThan(tick, value) && MathUtilities.GreaterThan(tick, previous))
{
previous = tick;
}
else if (MathUtilities.GreaterThan(tick, value) && MathUtilities.LessThan(tick, next))
{
next = tick;
}
}
}
else if (MathUtilities.GreaterThan(TickFrequency, 0.0))
{
previous = Minimum + (Math.Round(((value - Minimum) / TickFrequency)) * TickFrequency);
next = Math.Min(Maximum, previous + TickFrequency);
}
// Choose the closest value between previous and next. If tie, snap to 'next'.
value = MathUtilities.GreaterThanOrClose(value, (previous + next) * 0.5) ? next : previous;
}
// Choose the closest value between previous and next. If tie, snap to 'next'.
return MathUtilities.GreaterThanOrClose(value, (previous + next) * 0.5) ? next : previous;
return value;
}
private void UpdatePseudoClasses(Orientation o)
{
PseudoClasses.Set(":vertical", o == Orientation.Vertical);

64
src/Avalonia.Controls/TextBlock.cs

@ -70,6 +70,15 @@ namespace Avalonia.Controls
Brushes.Black,
inherits: true);
/// <summary>
/// Defines the <see cref="LineHeight"/> property.
/// </summary>
public static readonly StyledProperty<double> LineHeightProperty =
AvaloniaProperty.Register<TextBlock, double>(
nameof(LineHeight),
double.NaN,
validate: IsValidLineHeight);
/// <summary>
/// Defines the <see cref="MaxLines"/> property.
/// </summary>
@ -122,19 +131,19 @@ namespace Avalonia.Controls
{
ClipToBoundsProperty.OverrideDefaultValue<TextBlock>(true);
AffectsRender<TextBlock>(BackgroundProperty, ForegroundProperty,
AffectsRender<TextBlock>(BackgroundProperty, ForegroundProperty,
TextAlignmentProperty, TextDecorationsProperty);
AffectsMeasure<TextBlock>(FontSizeProperty, FontWeightProperty,
FontStyleProperty, TextWrappingProperty, FontFamilyProperty,
TextTrimmingProperty, TextProperty, PaddingProperty);
AffectsMeasure<TextBlock>(FontSizeProperty, FontWeightProperty,
FontStyleProperty, TextWrappingProperty, FontFamilyProperty,
TextTrimmingProperty, TextProperty, PaddingProperty, LineHeightProperty, MaxLinesProperty);
Observable.Merge(TextProperty.Changed, ForegroundProperty.Changed,
TextAlignmentProperty.Changed, TextWrappingProperty.Changed,
TextTrimmingProperty.Changed, FontSizeProperty.Changed,
FontStyleProperty.Changed, FontWeightProperty.Changed,
FontFamilyProperty.Changed, TextDecorationsProperty.Changed,
PaddingProperty.Changed
PaddingProperty.Changed, MaxLinesProperty.Changed, LineHeightProperty.Changed
).AddClassHandler<TextBlock>((x, _) => x.InvalidateTextLayout());
}
@ -230,6 +239,15 @@ namespace Avalonia.Controls
set { SetValue(ForegroundProperty, value); }
}
/// <summary>
/// Gets or sets the height of each line of content.
/// </summary>
public double LineHeight
{
get => GetValue(LineHeightProperty);
set => SetValue(LineHeightProperty, value);
}
/// <summary>
/// Gets or sets the maximum number of text lines.
/// </summary>
@ -393,9 +411,30 @@ namespace Avalonia.Controls
context.FillRectangle(background, new Rect(Bounds.Size));
}
if (TextLayout is null)
{
return;
}
var textAlignment = TextAlignment;
var width = Bounds.Size.Width;
var offsetX = 0.0;
switch (textAlignment)
{
case TextAlignment.Center:
offsetX = (width - TextLayout.Size.Width) / 2;
break;
case TextAlignment.Right:
offsetX = width - TextLayout.Size.Width;
break;
}
var padding = Padding;
TextLayout?.Draw(context.PlatformImpl, new Point(padding.Left, padding.Top));
TextLayout.Draw(context, new Point(padding.Left + offsetX, padding.Top));
}
/// <summary>
@ -413,7 +452,7 @@ namespace Avalonia.Controls
return new TextLayout(
text ?? string.Empty,
FontManager.Current?.GetOrAddTypeface(FontFamily, FontWeight, FontStyle),
FontManager.Current?.GetOrAddTypeface(FontFamily, FontStyle, FontWeight),
FontSize,
Foreground,
TextAlignment,
@ -422,7 +461,8 @@ namespace Avalonia.Controls
TextDecorations,
constraint.Width,
constraint.Height,
MaxLines);
maxLines: MaxLines,
lineHeight: LineHeight);
}
/// <summary>
@ -451,12 +491,12 @@ namespace Avalonia.Controls
if (_constraint != availableSize)
{
_constraint = availableSize;
InvalidateTextLayout();
}
_constraint = availableSize;
var measuredSize = TextLayout?.Bounds.Size ?? Size.Empty;
var measuredSize = TextLayout?.Size ?? Size.Empty;
return measuredSize.Inflate(padding);
}
@ -471,5 +511,7 @@ namespace Avalonia.Controls
}
private static bool IsValidMaxLines(int maxLines) => maxLines >= 0;
private static bool IsValidLineHeight(double lineHeight) => double.IsNaN(lineHeight) || lineHeight > 0;
}
}

12
src/Avalonia.Controls/TickBar.cs

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Data.Converters;
using Avalonia.Collections;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Utilities;
@ -135,15 +131,15 @@ namespace Avalonia.Controls
/// <summary>
/// Defines the <see cref="Ticks"/> property.
/// </summary>
public static readonly StyledProperty<List<double>> TicksProperty =
AvaloniaProperty.Register<TickBar, List<double>>(nameof(Ticks));
public static readonly StyledProperty<AvaloniaList<double>> TicksProperty =
AvaloniaProperty.Register<TickBar, AvaloniaList<double>>(nameof(Ticks));
/// <summary>
/// The Ticks property contains collection of value of type Double which
/// are the logical positions use to draw the ticks.
/// The property value is a <see cref="DoubleCollection" />.
/// </summary>
public List<double> Ticks
public AvaloniaList<double> Ticks
{
get { return GetValue(TicksProperty); }
set { SetValue(TicksProperty, value); }

118
src/Avalonia.Controls/ToggleSwitch.cs

@ -10,10 +10,32 @@ namespace Avalonia.Controls
/// </summary>
public class ToggleSwitch : ToggleButton
{
private Panel _knobsPanel;
private Panel _switchKnob;
private bool _knobsPanelPressed = false;
private Point _switchStartPoint = new Point();
private double _initLeft = -1;
private bool _isDragging = false;
static ToggleSwitch()
{
OffContentProperty.Changed.AddClassHandler<ToggleSwitch>((x, e) => x.OffContentChanged(e));
OnContentProperty.Changed.AddClassHandler<ToggleSwitch>((x, e) => x.OnContentChanged(e));
IsCheckedProperty.Changed.AddClassHandler<ToggleSwitch>((x, e) =>
{
if ((e.NewValue != null) && (e.NewValue is bool val))
{
x.UpdateKnobPos(val);
}
});
BoundsProperty.Changed.AddClassHandler<ToggleSwitch>((x, e) =>
{
if (x.IsChecked != null)
{
x.UpdateKnobPos(x.IsChecked.Value);
}
});
}
/// <summary>
@ -131,6 +153,102 @@ namespace Avalonia.Controls
return result;
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_switchKnob = e.NameScope.Find<Panel>("SwitchKnob");
_knobsPanel = e.NameScope.Find<Panel>("MovingKnobs");
_knobsPanel.PointerPressed += KnobsPanel_PointerPressed;
_knobsPanel.PointerReleased += KnobsPanel_PointerReleased;
_knobsPanel.PointerMoved += KnobsPanel_PointerMoved;
if (IsChecked.HasValue)
{
UpdateKnobPos(IsChecked.Value);
}
}
private void KnobsPanel_PointerPressed(object sender, Input.PointerPressedEventArgs e)
{
_switchStartPoint = e.GetPosition(_switchKnob);
_initLeft = Canvas.GetLeft(_knobsPanel);
_isDragging = false;
_knobsPanelPressed = true;
}
private void KnobsPanel_PointerReleased(object sender, Input.PointerReleasedEventArgs e)
{
if (_isDragging)
{
bool shouldBecomeChecked = Canvas.GetLeft(_knobsPanel) >= (_switchKnob.Bounds.Width / 2);
_knobsPanel.ClearValue(Canvas.LeftProperty);
PseudoClasses.Set(":dragging", false);
if (shouldBecomeChecked == IsChecked)
{
UpdateKnobPos(shouldBecomeChecked);
}
else
{
IsChecked = shouldBecomeChecked;
}
}
else
{
base.Toggle();
}
_isDragging = false;
_knobsPanelPressed = false;
}
private void KnobsPanel_PointerMoved(object sender, Input.PointerEventArgs e)
{
if (_knobsPanelPressed)
{
var difference = e.GetPosition(_switchKnob) - _switchStartPoint;
if ((!_isDragging) && (System.Math.Abs(difference.X) > 3))
{
_isDragging = true;
PseudoClasses.Set(":dragging", true);
}
if (_isDragging)
{
Canvas.SetLeft(_knobsPanel, System.Math.Min(_switchKnob.Bounds.Width, System.Math.Max(0, (_initLeft + difference.X))));
}
}
}
protected override void Toggle()
{
if ((_switchKnob != null) && (!_switchKnob.IsPointerOver))
{
base.Toggle();
}
}
protected void UpdateKnobPos(bool value)
{
if ((_switchKnob != null) && (_knobsPanel != null))
{
if (value)
{
Canvas.SetLeft(_knobsPanel, _switchKnob.Bounds.Width);
}
else
{
Canvas.SetLeft(_knobsPanel, 0);
}
}
}
}
}

2
src/Avalonia.Controls/TopLevel.cs

@ -405,7 +405,7 @@ namespace Avalonia.Controls
}
else
{
_transparencyFallbackBorder.Background = Brushes.Transparent;
_transparencyFallbackBorder.Background = null;
}
}

135
src/Avalonia.Controls/Window.cs

@ -4,6 +4,7 @@ using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Avalonia.Controls.Chrome;
using Avalonia.Controls.Platform;
using Avalonia.Data;
using Avalonia.Input;
@ -69,7 +70,11 @@ namespace Avalonia.Controls
/// </summary>
public class Window : WindowBase, IStyleable, IFocusScope, ILayoutRoot
{
private readonly List<(Window child, bool isDialog)> _children = new List<(Window, bool)>();
private readonly List<(Window child, bool isDialog)> _children = new List<(Window, bool)>();
private TitleBar _managedTitleBar;
private bool _isExtendedIntoWindowDecorations;
private Thickness _windowDecorationMargin;
private Thickness _offScreenMargin;
/// <summary>
/// Defines the <see cref="SizeToContent"/> property.
@ -87,6 +92,37 @@ namespace Avalonia.Controls
o => o.HasSystemDecorations,
(o, v) => o.HasSystemDecorations = v);
/// <summary>
/// Defines the <see cref="ExtendClientAreaToDecorationsHint"/> property.
/// </summary>
public static readonly StyledProperty<bool> ExtendClientAreaToDecorationsHintProperty =
AvaloniaProperty.Register<Window, bool>(nameof(ExtendClientAreaToDecorationsHint), false);
public static readonly StyledProperty<ExtendClientAreaChromeHints> ExtendClientAreaChromeHintsProperty =
AvaloniaProperty.Register<Window, ExtendClientAreaChromeHints>(nameof(ExtendClientAreaChromeHints), ExtendClientAreaChromeHints.Default);
public static readonly StyledProperty<double> ExtendClientAreaTitleBarHeightHintProperty =
AvaloniaProperty.Register<Window, double>(nameof(ExtendClientAreaTitleBarHeightHint), -1);
/// <summary>
/// Defines the <see cref="IsExtendedIntoWindowDecorations"/> property.
/// </summary>
public static readonly DirectProperty<Window, bool> IsExtendedIntoWindowDecorationsProperty =
AvaloniaProperty.RegisterDirect<Window, bool>(nameof(IsExtendedIntoWindowDecorations),
o => o.IsExtendedIntoWindowDecorations,
unsetValue: false);
/// <summary>
/// Defines the <see cref="WindowDecorationMargin"/> property.
/// </summary>
public static readonly DirectProperty<Window, Thickness> WindowDecorationMarginProperty =
AvaloniaProperty.RegisterDirect<Window, Thickness>(nameof(WindowDecorationMargin),
o => o.WindowDecorationMargin);
public static readonly DirectProperty<Window, Thickness> OffScreenMarginProperty =
AvaloniaProperty.RegisterDirect<Window, Thickness>(nameof(OffScreenMargin),
o => o.OffScreenMargin);
/// <summary>
/// Defines the <see cref="SystemDecorations"/> property.
/// </summary>
@ -164,6 +200,21 @@ namespace Avalonia.Controls
WindowStateProperty.Changed.AddClassHandler<Window>(
(w, e) => { if (w.PlatformImpl != null) w.PlatformImpl.WindowState = (WindowState)e.NewValue; });
ExtendClientAreaToDecorationsHintProperty.Changed.AddClassHandler<Window>(
(w, e) => { if (w.PlatformImpl != null) w.PlatformImpl.SetExtendClientAreaToDecorationsHint((bool)e.NewValue); });
ExtendClientAreaChromeHintsProperty.Changed.AddClassHandler<Window>(
(w, e) =>
{
if (w.PlatformImpl != null)
{
w.PlatformImpl.SetExtendClientAreaChromeHints((ExtendClientAreaChromeHints)e.NewValue);
}
});
ExtendClientAreaTitleBarHeightHintProperty.Changed.AddClassHandler<Window>(
(w, e) => { if (w.PlatformImpl != null) w.PlatformImpl.SetExtendClientAreaTitleBarHeightHint((double)e.NewValue); });
MinWidthProperty.Changed.AddClassHandler<Window>((w, e) => w.PlatformImpl?.SetMinMaxSize(new Size((double)e.NewValue, w.MinHeight), new Size(w.MaxWidth, w.MaxHeight)));
MinHeightProperty.Changed.AddClassHandler<Window>((w, e) => w.PlatformImpl?.SetMinMaxSize(new Size(w.MinWidth, (double)e.NewValue), new Size(w.MaxWidth, w.MaxHeight)));
MaxWidthProperty.Changed.AddClassHandler<Window>((w, e) => w.PlatformImpl?.SetMinMaxSize(new Size(w.MinWidth, w.MinHeight), new Size((double)e.NewValue, w.MaxHeight)));
@ -189,6 +240,7 @@ namespace Avalonia.Controls
impl.GotInputWhenDisabled = OnGotInputWhenDisabled;
impl.WindowStateChanged = HandleWindowStateChanged;
_maxPlatformClientSize = PlatformImpl?.MaxAutoSizeHint ?? default(Size);
impl.ExtendClientAreaToDecorationsChanged = ExtendClientAreaToDecorationsChanged;
this.GetObservable(ClientSizeProperty).Skip(1).Subscribe(x => PlatformImpl?.Resize(x));
PlatformImpl?.ShowTaskbarIcon(ShowInTaskbar);
@ -237,6 +289,66 @@ namespace Avalonia.Controls
}
}
/// <summary>
/// Gets or sets if the ClientArea is Extended into the Window Decorations (chrome or border).
/// </summary>
public bool ExtendClientAreaToDecorationsHint
{
get { return GetValue(ExtendClientAreaToDecorationsHintProperty); }
set { SetValue(ExtendClientAreaToDecorationsHintProperty, value); }
}
/// <summary>
/// Gets or Sets the <see cref="Avalonia.Platform.ExtendClientAreaChromeHints"/> that control
/// how the chrome looks when the client area is extended.
/// </summary>
public ExtendClientAreaChromeHints ExtendClientAreaChromeHints
{
get => GetValue(ExtendClientAreaChromeHintsProperty);
set => SetValue(ExtendClientAreaChromeHintsProperty, value);
}
/// <summary>
/// Gets or Sets the TitlebarHeightHint for when the client area is extended.
/// A value of -1 will cause the titlebar to be auto sized to the OS default.
/// Any other positive value will cause the titlebar to assume that height.
/// </summary>
public double ExtendClientAreaTitleBarHeightHint
{
get => GetValue(ExtendClientAreaTitleBarHeightHintProperty);
set => SetValue(ExtendClientAreaTitleBarHeightHintProperty, value);
}
/// <summary>
/// Gets if the ClientArea is Extended into the Window Decorations.
/// </summary>
public bool IsExtendedIntoWindowDecorations
{
get => _isExtendedIntoWindowDecorations;
private set => SetAndRaise(IsExtendedIntoWindowDecorationsProperty, ref _isExtendedIntoWindowDecorations, value);
}
/// <summary>
/// Gets the WindowDecorationMargin.
/// This tells you the thickness around the window that is used by borders and the titlebar.
/// </summary>
public Thickness WindowDecorationMargin
{
get => _windowDecorationMargin;
private set => SetAndRaise(WindowDecorationMarginProperty, ref _windowDecorationMargin, value);
}
/// <summary>
/// Gets the window margin that is hidden off the screen area.
/// This is generally only the case on Windows when in Maximized where the window border
/// is hidden off the screen. This Margin may be used to ensure user content doesnt overlap this space.
/// </summary>
public Thickness OffScreenMargin
{
get => _offScreenMargin;
private set => SetAndRaise(OffScreenMarginProperty, ref _offScreenMargin, value);
}
/// <summary>
/// Sets the system decorations (title bar, border, etc)
/// </summary>
@ -435,6 +547,27 @@ namespace Avalonia.Controls
}
}
protected virtual void ExtendClientAreaToDecorationsChanged(bool isExtended)
{
IsExtendedIntoWindowDecorations = isExtended;
WindowDecorationMargin = PlatformImpl.ExtendedMargins;
OffScreenMargin = PlatformImpl.OffScreenMargin;
if (PlatformImpl.NeedsManagedDecorations)
{
if (_managedTitleBar == null)
{
_managedTitleBar = new TitleBar(this);
_managedTitleBar.Attach();
}
}
else
{
_managedTitleBar?.Detach();
_managedTitleBar = null;
}
}
/// <summary>
/// Hides the window but does not close it.
/// </summary>

24
src/Avalonia.DesignerSupport/Remote/PreviewerWindowImpl.cs

@ -78,7 +78,17 @@ namespace Avalonia.DesignerSupport.Remote
}
public IScreenImpl Screen { get; } = new ScreenStub();
public Action GotInputWhenDisabled { get; set; }
public Action GotInputWhenDisabled { get; set; }
public Action<bool> ExtendClientAreaToDecorationsChanged { get; set; }
public Thickness ExtendedMargins { get; } = new Thickness();
public bool IsClientAreaExtendedToDecorations { get; }
public Thickness OffScreenMargin { get; } = new Thickness();
public bool NeedsManagedDecorations => false;
public void Activate()
{
@ -119,5 +129,17 @@ namespace Avalonia.DesignerSupport.Remote
public void SetEnabled(bool enable)
{
}
public void SetExtendClientAreaToDecorationsHint(bool extendIntoClientAreaHint)
{
}
public void SetExtendClientAreaChromeHints(ExtendClientAreaChromeHints hints)
{
}
public void SetExtendClientAreaTitleBarHeightHint(double titleBarHeight)
{
}
}
}

26
src/Avalonia.DesignerSupport/Remote/Stubs.cs

@ -38,7 +38,13 @@ namespace Avalonia.DesignerSupport.Remote
public WindowState WindowState { get; set; }
public Action<WindowState> WindowStateChanged { get; set; }
public Action<WindowTransparencyLevel> TransparencyLevelChanged { get; set; }
public Action<WindowTransparencyLevel> TransparencyLevelChanged { get; set; }
public Action<bool> ExtendClientAreaToDecorationsChanged { get; set; }
public Thickness ExtendedMargins { get; } = new Thickness();
public Thickness OffScreenMargin { get; } = new Thickness();
public WindowStub(IWindowImpl parent = null)
{
@ -141,6 +147,18 @@ namespace Avalonia.DesignerSupport.Remote
{
}
public void SetExtendClientAreaToDecorationsHint(bool extendIntoClientAreaHint)
{
}
public void SetExtendClientAreaChromeHints(ExtendClientAreaChromeHints hints)
{
}
public void SetExtendClientAreaTitleBarHeightHint(double titleBarHeight)
{
}
public IPopupPositioner PopupPositioner { get; }
public Action GotInputWhenDisabled { get; set; }
@ -152,6 +170,12 @@ namespace Avalonia.DesignerSupport.Remote
}
public WindowTransparencyLevel TransparencyLevel { get; private set; }
public bool IsClientAreaExtendedToDecorations { get; }
public bool NeedsManagedDecorations => false;
public AcrylicPlatformCompensationLevels AcrylicCompensationLevels { get; } = new AcrylicPlatformCompensationLevels(1, 1, 1);
}
class ClipboardStub : IClipboard

4
src/Avalonia.Desktop/AppBuilderDesktopExtensions.cs

@ -46,10 +46,6 @@ namespace Avalonia
where TAppBuilder : AppBuilderBase<TAppBuilder>, new()
=> builder.UseX11();
static void LoadDirect2D1<TAppBuilder>(TAppBuilder builder)
where TAppBuilder : AppBuilderBase<TAppBuilder>, new()
=> builder.UseDirect2D1();
static void LoadSkia<TAppBuilder>(TAppBuilder builder)
where TAppBuilder : AppBuilderBase<TAppBuilder>, new()
=> builder.UseSkia();

3
src/Avalonia.Desktop/Avalonia.Desktop.csproj

@ -5,8 +5,7 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../src/Windows/Avalonia.Win32/Avalonia.Win32.csproj" />
<ProjectReference Include="../../src/Windows/Avalonia.Direct2D1/Avalonia.Direct2D1.csproj" />
<ProjectReference Include="../../src/Windows/Avalonia.Win32/Avalonia.Win32.csproj" />
<ProjectReference Include="../../src/Skia/Avalonia.Skia/Avalonia.Skia.csproj" />
<ProjectReference Include="../../src/Avalonia.Native/Avalonia.Native.csproj" />
<ProjectReference Include="../../packages/Avalonia/Avalonia.csproj" />

12
src/Avalonia.Headless.Vnc/Avalonia.Headless.Vnc.csproj

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Avalonia.Headless\Avalonia.Headless.csproj" />
<PackageReference Include="Quamotion.RemoteViewing" Version="1.1.21" />
</ItemGroup>
</Project>

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save