1
0
Эх сурвалжийг харах

Merge branch 'master' into BrushRelativeTransform

Max Katz 3 жил өмнө
parent
commit
012cee5510
100 өөрчлөгдсөн 3669 нэмэгдсэн , 2808 устгасан
  1. 1 1
      Avalonia.sln
  2. 2 0
      build/ApiCompatAttributeExcludeList.txt
  3. 0 2
      build/CoreLibraries.props
  4. 3 3
      build/HarfBuzzSharp.props
  5. 1 1
      build/ImageSharp.props
  6. 3 3
      build/SkiaSharp.props
  7. 5 0
      native/Avalonia.Native/inc/rendertarget.h
  8. 17 0
      native/Avalonia.Native/src/OSX/AutoFitContentView.h
  9. 106 0
      native/Avalonia.Native/src/OSX/AutoFitContentView.mm
  10. 72 6
      native/Avalonia.Native/src/OSX/Avalonia.Native.OSX.xcodeproj/project.pbxproj
  11. 5 1
      native/Avalonia.Native/src/OSX/Avalonia.Native.OSX.xcodeproj/xcshareddata/xcschemes/Avalonia.Native.OSX.xcscheme
  12. 11 0
      native/Avalonia.Native/src/OSX/AvnPanelWindow.mm
  13. 27 0
      native/Avalonia.Native/src/OSX/AvnView.h
  14. 712 0
      native/Avalonia.Native/src/OSX/AvnView.mm
  15. 466 0
      native/Avalonia.Native/src/OSX/AvnWindow.mm
  16. 17 0
      native/Avalonia.Native/src/OSX/INSWindowHolder.h
  17. 18 0
      native/Avalonia.Native/src/OSX/IWindowStateChanged.h
  18. 9 0
      native/Avalonia.Native/src/OSX/PopupImpl.h
  19. 61 0
      native/Avalonia.Native/src/OSX/PopupImpl.mm
  20. 24 0
      native/Avalonia.Native/src/OSX/ResizeScope.h
  21. 18 0
      native/Avalonia.Native/src/OSX/ResizeScope.mm
  22. 1 1
      native/Avalonia.Native/src/OSX/SystemDialogs.mm
  23. 136 0
      native/Avalonia.Native/src/OSX/WindowBaseImpl.h
  24. 615 0
      native/Avalonia.Native/src/OSX/WindowBaseImpl.mm
  25. 101 0
      native/Avalonia.Native/src/OSX/WindowImpl.h
  26. 554 0
      native/Avalonia.Native/src/OSX/WindowImpl.mm
  27. 17 0
      native/Avalonia.Native/src/OSX/WindowInterfaces.h
  28. 27 0
      native/Avalonia.Native/src/OSX/WindowProtocol.h
  29. 0 12
      native/Avalonia.Native/src/OSX/app.mm
  30. 2 2
      native/Avalonia.Native/src/OSX/automation.h
  31. 2 1
      native/Avalonia.Native/src/OSX/automation.mm
  32. 1 2
      native/Avalonia.Native/src/OSX/common.h
  33. 0 1
      native/Avalonia.Native/src/OSX/cursor.mm
  34. 1 6
      native/Avalonia.Native/src/OSX/main.mm
  35. 0 1
      native/Avalonia.Native/src/OSX/menu.h
  36. 2 4
      native/Avalonia.Native/src/OSX/menu.mm
  37. 0 4
      native/Avalonia.Native/src/OSX/rendertarget.mm
  38. 0 77
      native/Avalonia.Native/src/OSX/window.h
  39. 0 2590
      native/Avalonia.Native/src/OSX/window.mm
  40. 1 0
      samples/BindingDemo/BindingDemo.csproj
  41. 0 1
      samples/ControlCatalog.NetCore/Program.cs
  42. 2 2
      samples/ControlCatalog/App.xaml.cs
  43. 4 1
      samples/ControlCatalog/ControlCatalog.csproj
  44. 1 2
      samples/ControlCatalog/Pages/CalendarDatePickerPage.xaml
  45. 1 0
      samples/ControlCatalog/Pages/CarouselPage.xaml
  46. 3 0
      samples/ControlCatalog/Pages/CarouselPage.xaml.cs
  47. 68 18
      samples/ControlCatalog/Pages/ColorPickerPage.xaml
  48. 10 0
      samples/ControlCatalog/Pages/ComboBoxPage.xaml
  49. 1 2
      samples/ControlCatalog/Pages/DialogsPage.xaml.cs
  50. 6 0
      samples/ControlCatalog/Pages/TextBoxPage.xaml
  51. 1 1
      samples/ControlCatalog/ViewModels/MainWindowViewModel.cs
  52. 2 1
      samples/IntegrationTestApp/IntegrationTestApp.csproj
  53. 1 0
      samples/PlatformSanityChecks/PlatformSanityChecks.csproj
  54. 3 0
      samples/Previewer/Previewer.csproj
  55. 3 0
      samples/RenderDemo/MainWindow.xaml
  56. 210 0
      samples/RenderDemo/Pages/Transform3DPage.axaml
  57. 21 0
      samples/RenderDemo/Pages/Transform3DPage.axaml.cs
  58. 1 0
      samples/RenderDemo/RenderDemo.csproj
  59. 55 0
      samples/RenderDemo/ViewModels/Transform3DPageViewModel.cs
  60. 1 0
      samples/Sandbox/Sandbox.csproj
  61. 1 0
      samples/VirtualizationDemo/VirtualizationDemo.csproj
  62. 1 0
      samples/interop/Direct3DInteropSample/Direct3DInteropSample.csproj
  63. 1 0
      samples/interop/NativeEmbedSample/NativeEmbedSample.csproj
  64. 1 1
      src/Android/Avalonia.Android/Platform/SkiaPlatform/TopLevelImpl.cs
  65. 1 0
      src/Avalonia.Base/Animation/Animators/TransformAnimator.cs
  66. 2 0
      src/Avalonia.Base/Animation/IAnimation.cs
  67. 3 0
      src/Avalonia.Base/Animation/IAnimationSetter.cs
  68. 2 0
      src/Avalonia.Base/Animation/IAnimator.cs
  69. 2 2
      src/Avalonia.Base/Animation/IClock.cs
  70. 2 3
      src/Avalonia.Base/Animation/IGlobalClock.cs
  71. 2 0
      src/Avalonia.Base/Animation/ITransition.cs
  72. 3 3
      src/Avalonia.Base/Animation/PageSlide.cs
  73. 121 0
      src/Avalonia.Base/Animation/Transitions/Rotate3DTransition.cs
  74. 1 1
      src/Avalonia.Base/AvaloniaPropertyChangedEventArgs.cs
  75. 6 0
      src/Avalonia.Base/Collections/AvaloniaList.cs
  76. 2 2
      src/Avalonia.Base/Controls/INameScope.cs
  77. 2 0
      src/Avalonia.Base/Controls/IPseudoClasses.cs
  78. 2 2
      src/Avalonia.Base/Controls/IResourceHost.cs
  79. 2 2
      src/Avalonia.Base/Controls/IResourceNode.cs
  80. 2 1
      src/Avalonia.Base/Controls/ISetInheritanceParent.cs
  81. 2 2
      src/Avalonia.Base/Controls/ISetLogicalParent.cs
  82. 4 7
      src/Avalonia.Base/Controls/ResourceNodeExtensions.cs
  83. 23 23
      src/Avalonia.Base/Data/Core/ExpressionNode.cs
  84. 2 0
      src/Avalonia.Base/Data/Core/IPropertyInfo.cs
  85. 12 7
      src/Avalonia.Base/Data/Core/Plugins/InpcPropertyAccessorPlugin.cs
  86. 3 0
      src/Avalonia.Base/Data/IBinding.cs
  87. 2 3
      src/Avalonia.Base/DirectPropertyBase.cs
  88. 2 0
      src/Avalonia.Base/IAvaloniaObject.cs
  89. 2 1
      src/Avalonia.Base/IDataContextProvider.cs
  90. 1 0
      src/Avalonia.Base/IDirectPropertyAccessor.cs
  91. 3 0
      src/Avalonia.Base/IDirectPropertyMetadata.cs
  92. 2 2
      src/Avalonia.Base/IStyledElement.cs
  93. 3 0
      src/Avalonia.Base/IStyledPropertyMetadata.cs
  94. 3 0
      src/Avalonia.Base/Input/IAccessKeyHandler.cs
  95. 3 0
      src/Avalonia.Base/Input/IFocusManager.cs
  96. 2 0
      src/Avalonia.Base/Input/IInputDevice.cs
  97. 2 0
      src/Avalonia.Base/Input/IInputElement.cs
  98. 2 0
      src/Avalonia.Base/Input/IInputManager.cs
  99. 3 0
      src/Avalonia.Base/Input/IInputRoot.cs
  100. 2 0
      src/Avalonia.Base/Input/IKeyboardDevice.cs

+ 1 - 1
Avalonia.sln

@@ -99,7 +99,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Props", "Props", "{F3AC8BC1
 		build\HarfBuzzSharp.props = build\HarfBuzzSharp.props
 		build\JetBrains.Annotations.props = build\JetBrains.Annotations.props
 		build\JetBrains.dotMemoryUnit.props = build\JetBrains.dotMemoryUnit.props
-		build\Magick.NET-Q16-AnyCPU.props = build\Magick.NET-Q16-AnyCPU.props
 		build\Microsoft.CSharp.props = build\Microsoft.CSharp.props
 		build\Microsoft.Reactive.Testing.props = build\Microsoft.Reactive.Testing.props
 		build\Moq.props = build\Moq.props
@@ -118,6 +117,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Props", "Props", "{F3AC8BC1
 		build\System.Memory.props = build\System.Memory.props
 		build\UnitTests.NetFX.props = build\UnitTests.NetFX.props
 		build\XUnit.props = build\XUnit.props
+		build\ImageSharp.props = build\ImageSharp.props
 	EndProjectSection
 EndProject
 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Targets", "Targets", "{4D6FAF79-58B4-482F-9122-0668C346364C}"

+ 2 - 0
build/ApiCompatAttributeExcludeList.txt

@@ -0,0 +1,2 @@
+T:Avalonia.Metadata.NotClientImplementableAttribute
+T:Avalonia.Metadata.UnstableAttribute

+ 0 - 2
build/CoreLibraries.props

@@ -3,8 +3,6 @@
       <ProjectReference Include="$(MSBuildThisFileDirectory)/../src/Avalonia.Base/Avalonia.Base.csproj" />
       <ProjectReference Include="$(MSBuildThisFileDirectory)/../src/Avalonia.Controls/Avalonia.Controls.csproj" />
       <ProjectReference Include="$(MSBuildThisFileDirectory)/../src/Avalonia.DesignerSupport/Avalonia.DesignerSupport.csproj" />
-      <ProjectReference Include="$(MSBuildThisFileDirectory)/../src/Avalonia.Themes.Default/Avalonia.Themes.Default.csproj" />
-      <ProjectReference Include="$(MSBuildThisFileDirectory)/../src/Avalonia.Themes.Fluent/Avalonia.Themes.Fluent.csproj" />
       <ProjectReference Include="$(MSBuildThisFileDirectory)/../src/Avalonia.OpenGL/Avalonia.OpenGL.csproj" />
       <ProjectReference Include="$(MSBuildThisFileDirectory)/../src/Avalonia.Dialogs/Avalonia.Dialogs.csproj" />
       <ProjectReference Include="$(MSBuildThisFileDirectory)/../src/Markup/Avalonia.Markup/Avalonia.Markup.csproj" />

+ 3 - 3
build/HarfBuzzSharp.props

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

+ 1 - 1
build/Magick.NET-Q16-AnyCPU.props → build/ImageSharp.props

@@ -1,5 +1,5 @@
 <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
   <ItemGroup>
-    <PackageReference Include="Magick.NET-Q16-AnyCPU" Version="7.9.0.2" />
+    <PackageReference Include="SixLabors.ImageSharp" Version="2.1.1" />
   </ItemGroup>
 </Project>

+ 3 - 3
build/SkiaSharp.props

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

+ 5 - 0
native/Avalonia.Native/inc/rendertarget.h

@@ -1,3 +1,8 @@
+#pragma once
+
+#include "com.h"
+#include "comimpl.h"
+#include "avalonia-native.h"
 
 @protocol IRenderTarget
 -(void) setNewLayer: (CALayer*) layer;

+ 17 - 0
native/Avalonia.Native/src/OSX/AutoFitContentView.h

@@ -0,0 +1,17 @@
+//
+// Created by Dan Walmsley on 05/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#pragma once
+
+#import <Foundation/Foundation.h>
+#include "avalonia-native.h"
+
+@interface AutoFitContentView : NSView
+-(AutoFitContentView* _Nonnull) initWithContent: (NSView* _Nonnull) content;
+-(void) ShowTitleBar: (bool) show;
+-(void) SetTitleBarHeightHint: (double) height;
+
+-(void) ShowBlur: (bool) show;
+@end

+ 106 - 0
native/Avalonia.Native/src/OSX/AutoFitContentView.mm

@@ -0,0 +1,106 @@
+//
+// Created by Dan Walmsley on 05/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#include "AvnView.h"
+#include "AutoFitContentView.h"
+#include "WindowInterfaces.h"
+#include "WindowProtocol.h"
+
+@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;
+
+    [_blurBehind setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
+    [_content setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
+
+    [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
+{
+    if(_settingSize)
+    {
+        return;
+    }
+
+    _settingSize = true;
+    [super setFrameSize:newSize];
+
+    auto window = (id <AvnWindowProtocol>) [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;
+}
+@end

+ 72 - 6
native/Avalonia.Native/src/OSX/Avalonia.Native.OSX.xcodeproj/project.pbxproj

@@ -7,6 +7,24 @@
 	objects = {
 
 /* Begin PBXBuildFile section */
+		18391068E48EF96E3DB5FDAB /* ResizeScope.mm in Sources */ = {isa = PBXBuildFile; fileRef = 18391E45702740FE9DD69695 /* ResizeScope.mm */; };
+		1839125F057B0A4EB1760058 /* WindowImpl.mm in Sources */ = {isa = PBXBuildFile; fileRef = 183919BF108EB72A029F7671 /* WindowImpl.mm */; };
+		183914E50CF6D2EFC1667F7C /* WindowInterfaces.h in Headers */ = {isa = PBXBuildFile; fileRef = 18391DB45C7D892E61BF388C /* WindowInterfaces.h */; };
+		1839151F32D1BB1AB51A7BB6 /* AvnPanelWindow.mm in Sources */ = {isa = PBXBuildFile; fileRef = 18391884C7476DA4E53A492D /* AvnPanelWindow.mm */; };
+		183916173528EC2737DBE5E1 /* WindowBaseImpl.h in Headers */ = {isa = PBXBuildFile; fileRef = 183915BFF0E234CD3604A7CD /* WindowBaseImpl.h */; };
+		1839171DCC651B0638603AC4 /* INSWindowHolder.h in Headers */ = {isa = PBXBuildFile; fileRef = 18391BBB7782C296D424071F /* INSWindowHolder.h */; };
+		1839179A55FC1421BEE83330 /* WindowBaseImpl.mm in Sources */ = {isa = PBXBuildFile; fileRef = 18391676ECF0E983F4964357 /* WindowBaseImpl.mm */; };
+		183919D91DB9AAB5D700C2EA /* WindowImpl.h in Headers */ = {isa = PBXBuildFile; fileRef = 18391CD090AA776E7E841AC9 /* WindowImpl.h */; };
+		18391AA7E0BBA74D184C5734 /* AutoFitContentView.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1839166350F32661F3ABD70F /* AutoFitContentView.mm */; };
+		18391AC16726CBC45856233B /* AvnWindow.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1839155B28B20FFB672D29C6 /* AvnWindow.mm */; };
+		18391AC65ADD7DDD33FBE737 /* PopupImpl.h in Headers */ = {isa = PBXBuildFile; fileRef = 183910513F396141938832B5 /* PopupImpl.h */; };
+		18391C28BF1823B5464FDD36 /* ResizeScope.h in Headers */ = {isa = PBXBuildFile; fileRef = 1839171D898F9BFC1373631A /* ResizeScope.h */; };
+		18391CF07316F819E76B617C /* IWindowStateChanged.h in Headers */ = {isa = PBXBuildFile; fileRef = 183913C6BFD6856BD42D19FD /* IWindowStateChanged.h */; };
+		18391D4EB311BC7EF8B8C0A6 /* AvnView.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1839132D0E2454D911F1D1F9 /* AvnView.mm */; };
+		18391D8CD1756DC858DC1A09 /* PopupImpl.mm in Sources */ = {isa = PBXBuildFile; fileRef = 18391BB698579F40F1783F31 /* PopupImpl.mm */; };
+		18391E1381E2D5BFD60265A9 /* AutoFitContentView.h in Headers */ = {isa = PBXBuildFile; fileRef = 18391654EF0E7AB3D3AB4071 /* AutoFitContentView.h */; };
+		18391ED5F611FF62C45F196D /* AvnView.h in Headers */ = {isa = PBXBuildFile; fileRef = 18391D1669284AD2EC9E866A /* AvnView.h */; };
+		18391F1E2411C79405A9943A /* WindowProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 1839122E037567BDD1D09DEB /* WindowProtocol.h */; };
 		1A002B9E232135EE00021753 /* app.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1A002B9D232135EE00021753 /* app.mm */; };
 		1A1852DC23E05814008F0DED /* deadlock.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1A1852DB23E05814008F0DED /* deadlock.mm */; };
 		1A3E5EA823E9E83B00EDE661 /* rendertarget.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1A3E5EA723E9E83B00EDE661 /* rendertarget.mm */; };
@@ -28,13 +46,30 @@
 		AB00E4F72147CA920032A60A /* main.mm in Sources */ = {isa = PBXBuildFile; fileRef = AB00E4F62147CA920032A60A /* main.mm */; };
 		AB1E522C217613570091CD71 /* OpenGL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AB1E522B217613570091CD71 /* OpenGL.framework */; };
 		AB661C1E2148230F00291242 /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AB661C1D2148230F00291242 /* AppKit.framework */; };
-		AB661C202148286E00291242 /* window.mm in Sources */ = {isa = PBXBuildFile; fileRef = AB661C1F2148286E00291242 /* window.mm */; };
 		AB8F7D6B21482D7F0057DBA5 /* platformthreading.mm in Sources */ = {isa = PBXBuildFile; fileRef = AB8F7D6A21482D7F0057DBA5 /* platformthreading.mm */; };
 		BC11A5BE2608D58F0017BAD0 /* automation.h in Headers */ = {isa = PBXBuildFile; fileRef = BC11A5BC2608D58F0017BAD0 /* automation.h */; };
 		BC11A5BF2608D58F0017BAD0 /* automation.mm in Sources */ = {isa = PBXBuildFile; fileRef = BC11A5BD2608D58F0017BAD0 /* automation.mm */; };
 /* End PBXBuildFile section */
 
 /* Begin PBXFileReference section */
+		183910513F396141938832B5 /* PopupImpl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PopupImpl.h; sourceTree = "<group>"; };
+		1839122E037567BDD1D09DEB /* WindowProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WindowProtocol.h; sourceTree = "<group>"; };
+		1839132D0E2454D911F1D1F9 /* AvnView.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = AvnView.mm; sourceTree = "<group>"; };
+		183913C6BFD6856BD42D19FD /* IWindowStateChanged.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IWindowStateChanged.h; sourceTree = "<group>"; };
+		1839155B28B20FFB672D29C6 /* AvnWindow.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = AvnWindow.mm; sourceTree = "<group>"; };
+		183915BFF0E234CD3604A7CD /* WindowBaseImpl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WindowBaseImpl.h; sourceTree = "<group>"; };
+		18391654EF0E7AB3D3AB4071 /* AutoFitContentView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AutoFitContentView.h; sourceTree = "<group>"; };
+		1839166350F32661F3ABD70F /* AutoFitContentView.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = AutoFitContentView.mm; sourceTree = "<group>"; };
+		18391676ECF0E983F4964357 /* WindowBaseImpl.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WindowBaseImpl.mm; sourceTree = "<group>"; };
+		1839171D898F9BFC1373631A /* ResizeScope.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ResizeScope.h; sourceTree = "<group>"; };
+		18391884C7476DA4E53A492D /* AvnPanelWindow.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = AvnPanelWindow.mm; sourceTree = "<group>"; };
+		183919BF108EB72A029F7671 /* WindowImpl.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WindowImpl.mm; sourceTree = "<group>"; };
+		18391BB698579F40F1783F31 /* PopupImpl.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = PopupImpl.mm; sourceTree = "<group>"; };
+		18391BBB7782C296D424071F /* INSWindowHolder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = INSWindowHolder.h; sourceTree = "<group>"; };
+		18391CD090AA776E7E841AC9 /* WindowImpl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WindowImpl.h; sourceTree = "<group>"; };
+		18391D1669284AD2EC9E866A /* AvnView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AvnView.h; sourceTree = "<group>"; };
+		18391DB45C7D892E61BF388C /* WindowInterfaces.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WindowInterfaces.h; sourceTree = "<group>"; };
+		18391E45702740FE9DD69695 /* ResizeScope.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = ResizeScope.mm; sourceTree = "<group>"; };
 		1A002B9D232135EE00021753 /* app.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = app.mm; sourceTree = "<group>"; };
 		1A1852DB23E05814008F0DED /* deadlock.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = deadlock.mm; sourceTree = "<group>"; };
 		1A3E5EA723E9E83B00EDE661 /* rendertarget.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = rendertarget.mm; sourceTree = "<group>"; };
@@ -48,7 +83,6 @@
 		37A4E71A2178846A00EACBCD /* headers */ = {isa = PBXFileReference; lastKnownFileType = folder; name = headers; path = ../../inc; sourceTree = "<group>"; };
 		37A517B22159597E00FBA241 /* Screens.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = Screens.mm; sourceTree = "<group>"; };
 		37C09D8721580FE4006A6758 /* SystemDialogs.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = SystemDialogs.mm; sourceTree = "<group>"; };
-		37C09D8A21581EF2006A6758 /* window.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = window.h; sourceTree = "<group>"; };
 		37DDA9AF219330F8002E132B /* AvnString.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = AvnString.mm; sourceTree = "<group>"; };
 		37DDA9B121933371002E132B /* AvnString.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AvnString.h; sourceTree = "<group>"; };
 		37E2330E21583241000CB7E2 /* KeyTransform.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = KeyTransform.mm; sourceTree = "<group>"; };
@@ -62,7 +96,6 @@
 		AB00E4F62147CA920032A60A /* main.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = main.mm; sourceTree = "<group>"; };
 		AB1E522B217613570091CD71 /* OpenGL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGL.framework; path = System/Library/Frameworks/OpenGL.framework; sourceTree = SDKROOT; };
 		AB661C1D2148230F00291242 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = System/Library/Frameworks/AppKit.framework; sourceTree = SDKROOT; };
-		AB661C1F2148286E00291242 /* window.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = window.mm; sourceTree = "<group>"; };
 		AB661C212148288600291242 /* common.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = common.h; sourceTree = "<group>"; };
 		AB7A61EF2147C815003C5833 /* libAvalonia.Native.OSX.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = libAvalonia.Native.OSX.dylib; sourceTree = BUILT_PRODUCTS_DIR; };
 		AB8F7D6A21482D7F0057DBA5 /* platformthreading.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = platformthreading.mm; sourceTree = "<group>"; };
@@ -118,8 +151,6 @@
 				AB661C212148288600291242 /* common.h */,
 				379860FE214DA0C000CD0246 /* KeyTransform.h */,
 				37E2330E21583241000CB7E2 /* KeyTransform.mm */,
-				AB661C1F2148286E00291242 /* window.mm */,
-				37C09D8A21581EF2006A6758 /* window.h */,
 				AB00E4F62147CA920032A60A /* main.mm */,
 				37155CE3233C00EB0034DCE9 /* menu.h */,
 				520624B222973F4100C4DCEF /* menu.mm */,
@@ -130,6 +161,24 @@
 				37C09D8721580FE4006A6758 /* SystemDialogs.mm */,
 				AB7A61F02147C815003C5833 /* Products */,
 				AB661C1C2148230E00291242 /* Frameworks */,
+				18391676ECF0E983F4964357 /* WindowBaseImpl.mm */,
+				183915BFF0E234CD3604A7CD /* WindowBaseImpl.h */,
+				18391BBB7782C296D424071F /* INSWindowHolder.h */,
+				183919BF108EB72A029F7671 /* WindowImpl.mm */,
+				18391CD090AA776E7E841AC9 /* WindowImpl.h */,
+				183913C6BFD6856BD42D19FD /* IWindowStateChanged.h */,
+				18391E45702740FE9DD69695 /* ResizeScope.mm */,
+				1839171D898F9BFC1373631A /* ResizeScope.h */,
+				1839132D0E2454D911F1D1F9 /* AvnView.mm */,
+				18391D1669284AD2EC9E866A /* AvnView.h */,
+				1839166350F32661F3ABD70F /* AutoFitContentView.mm */,
+				18391654EF0E7AB3D3AB4071 /* AutoFitContentView.h */,
+				18391884C7476DA4E53A492D /* AvnPanelWindow.mm */,
+				1839122E037567BDD1D09DEB /* WindowProtocol.h */,
+				1839155B28B20FFB672D29C6 /* AvnWindow.mm */,
+				18391DB45C7D892E61BF388C /* WindowInterfaces.h */,
+				18391BB698579F40F1783F31 /* PopupImpl.mm */,
+				183910513F396141938832B5 /* PopupImpl.h */,
 			);
 			sourceTree = "<group>";
 		};
@@ -150,6 +199,16 @@
 			files = (
 				37155CE4233C00EB0034DCE9 /* menu.h in Headers */,
 				BC11A5BE2608D58F0017BAD0 /* automation.h in Headers */,
+				183916173528EC2737DBE5E1 /* WindowBaseImpl.h in Headers */,
+				1839171DCC651B0638603AC4 /* INSWindowHolder.h in Headers */,
+				183919D91DB9AAB5D700C2EA /* WindowImpl.h in Headers */,
+				18391CF07316F819E76B617C /* IWindowStateChanged.h in Headers */,
+				18391C28BF1823B5464FDD36 /* ResizeScope.h in Headers */,
+				18391ED5F611FF62C45F196D /* AvnView.h in Headers */,
+				18391E1381E2D5BFD60265A9 /* AutoFitContentView.h in Headers */,
+				18391F1E2411C79405A9943A /* WindowProtocol.h in Headers */,
+				183914E50CF6D2EFC1667F7C /* WindowInterfaces.h in Headers */,
+				18391AC65ADD7DDD33FBE737 /* PopupImpl.h in Headers */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
@@ -228,7 +287,14 @@
 				1A465D10246AB61600C5858B /* dnd.mm in Sources */,
 				AB00E4F72147CA920032A60A /* main.mm in Sources */,
 				37C09D8821580FE4006A6758 /* SystemDialogs.mm in Sources */,
-				AB661C202148286E00291242 /* window.mm in Sources */,
+				1839179A55FC1421BEE83330 /* WindowBaseImpl.mm in Sources */,
+				1839125F057B0A4EB1760058 /* WindowImpl.mm in Sources */,
+				18391068E48EF96E3DB5FDAB /* ResizeScope.mm in Sources */,
+				18391D4EB311BC7EF8B8C0A6 /* AvnView.mm in Sources */,
+				18391AA7E0BBA74D184C5734 /* AutoFitContentView.mm in Sources */,
+				1839151F32D1BB1AB51A7BB6 /* AvnPanelWindow.mm in Sources */,
+				18391AC16726CBC45856233B /* AvnWindow.mm in Sources */,
+				18391D8CD1756DC858DC1A09 /* PopupImpl.mm in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};

+ 5 - 1
native/Avalonia.Native/src/OSX/Avalonia.Native.OSX.xcodeproj/xcshareddata/xcschemes/Avalonia.Native.OSX.xcscheme

@@ -56,10 +56,14 @@
       </MacroExpansion>
       <CommandLineArguments>
          <CommandLineArgument
-            argument = "bin/Debug/netcoreapp3.1/ControlCatalog.NetCore.dll"
+            argument = "bin/Debug/net6.0/ControlCatalog.NetCore.dll"
             isEnabled = "YES">
          </CommandLineArgument>
       </CommandLineArguments>
+      <LocationScenarioReference
+         identifier = "com.apple.dt.IDEFoundation.CurrentLocationScenarioIdentifier"
+         referenceType = "1">
+      </LocationScenarioReference>
    </LaunchAction>
    <ProfileAction
       buildConfiguration = "Release"

+ 11 - 0
native/Avalonia.Native/src/OSX/AvnPanelWindow.mm

@@ -0,0 +1,11 @@
+//
+// Created by Dan Walmsley on 06/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#pragma once
+
+#define IS_NSPANEL
+
+#include "AvnWindow.mm"
+

+ 27 - 0
native/Avalonia.Native/src/OSX/AvnView.h

@@ -0,0 +1,27 @@
+//
+// Created by Dan Walmsley on 05/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+#pragma once
+#import <Foundation/Foundation.h>
+
+
+#import <Foundation/Foundation.h>
+#import <AppKit/AppKit.h>
+#include "common.h"
+#include "WindowImpl.h"
+#include "KeyTransform.h"
+
+@class AvnAccessibilityElement;
+
+@interface AvnView : NSView<NSTextInputClient, NSDraggingDestination>
+-(AvnView* _Nonnull) initWithParent: (WindowBaseImpl* _Nonnull) parent;
+-(NSEvent* _Nonnull) lastMouseDownEvent;
+-(AvnPoint) translateLocalPoint:(AvnPoint)pt;
+-(void) setSwRenderedFrame: (AvnFramebuffer* _Nonnull) fb dispose: (IUnknown* _Nonnull) dispose;
+-(void) onClosed;
+
+-(AvnPlatformResizeReason) getResizeReason;
+-(void) setResizeReason:(AvnPlatformResizeReason)reason;
++ (AvnPoint)toAvnPoint:(CGPoint)p;
+@end

+ 712 - 0
native/Avalonia.Native/src/OSX/AvnView.mm

@@ -0,0 +1,712 @@
+//
+// Created by Dan Walmsley on 05/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#import <AppKit/AppKit.h>
+#include "AvnView.h"
+#include "automation.h"
+#import "WindowInterfaces.h"
+
+@implementation AvnView
+{
+    ComPtr<WindowBaseImpl> _parent;
+    NSTrackingArea* _area;
+    bool _isLeftPressed, _isMiddlePressed, _isRightPressed, _isXButton1Pressed, _isXButton2Pressed;
+    AvnInputModifiers _modifierState;
+    NSEvent* _lastMouseDownEvent;
+    bool _lastKeyHandled;
+    AvnPixelSize _lastPixelSize;
+    NSObject<IRenderTarget>* _renderTarget;
+    AvnPlatformResizeReason _resizeReason;
+    AvnAccessibilityElement* _accessibilityChild;
+}
+
+- (void)onClosed
+{
+    @synchronized (self)
+    {
+        _parent = nullptr;
+    }
+}
+
+- (NSEvent*) lastMouseDownEvent
+{
+    return _lastMouseDownEvent;
+}
+
+- (void) updateRenderTarget
+{
+    [_renderTarget resize:_lastPixelSize withScale:static_cast<float>([[self window] backingScaleFactor])];
+    [self setNeedsDisplayInRect:[self frame]];
+}
+
+-(AvnView*)  initWithParent: (WindowBaseImpl*) parent
+{
+    self = [super init];
+    _renderTarget = parent->renderTarget;
+    [self setWantsLayer:YES];
+    [self setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize];
+
+    _parent = parent;
+    _area = nullptr;
+    _lastPixelSize.Height = 100;
+    _lastPixelSize.Width = 100;
+    [self registerForDraggedTypes: @[@"public.data", GetAvnCustomDataType()]];
+
+    _modifierState = AvnInputModifiersNone;
+    return self;
+}
+
+- (BOOL)isFlipped
+{
+    return YES;
+}
+
+- (BOOL)wantsUpdateLayer
+{
+    return YES;
+}
+
+- (void)setLayer:(CALayer *)layer
+{
+    [_renderTarget setNewLayer: layer];
+    [super setLayer: layer];
+}
+
+- (BOOL)isOpaque
+{
+    return YES;
+}
+
+- (BOOL)acceptsFirstResponder
+{
+    return true;
+}
+
+- (BOOL)acceptsFirstMouse:(NSEvent *)event
+{
+    return true;
+}
+
+- (BOOL)canBecomeKeyView
+{
+    return true;
+}
+
+-(void)setFrameSize:(NSSize)newSize
+{
+    [super setFrameSize:newSize];
+
+    if(_area != nullptr)
+    {
+        [self removeTrackingArea:_area];
+        _area = nullptr;
+    }
+
+    if (_parent == nullptr)
+    {
+        return;
+    }
+
+    NSRect rect = NSZeroRect;
+    rect.size = newSize;
+
+    NSTrackingAreaOptions options = NSTrackingActiveAlways | NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingEnabledDuringMouseDrag;
+    _area = [[NSTrackingArea alloc] initWithRect:rect options:options owner:self userInfo:nullptr];
+    [self addTrackingArea:_area];
+
+    _parent->UpdateCursor();
+
+    auto fsize = [self convertSizeToBacking: [self frame].size];
+
+    if(_lastPixelSize.Width != (int)fsize.width || _lastPixelSize.Height != (int)fsize.height)
+    {
+        _lastPixelSize.Width = (int)fsize.width;
+        _lastPixelSize.Height = (int)fsize.height;
+        [self updateRenderTarget];
+
+        auto reason = [self inLiveResize] ? ResizeUser : _resizeReason;
+        _parent->BaseEvents->Resized(AvnSize{newSize.width, newSize.height}, reason);
+    }
+}
+
+- (void)updateLayer
+{
+    AvnInsidePotentialDeadlock deadlock;
+    if (_parent == nullptr)
+    {
+        return;
+    }
+
+    _parent->BaseEvents->RunRenderPriorityJobs();
+
+    if (_parent == nullptr)
+    {
+        return;
+    }
+
+    _parent->BaseEvents->Paint();
+}
+
+- (void)drawRect:(NSRect)dirtyRect
+{
+    return;
+}
+
+-(void) setSwRenderedFrame: (AvnFramebuffer*) fb dispose: (IUnknown*) dispose
+{
+    @autoreleasepool {
+        [_renderTarget setSwFrame:fb];
+        dispose->Release();
+    }
+}
+
+- (AvnPoint) translateLocalPoint:(AvnPoint)pt
+{
+    pt.Y = [self bounds].size.height - pt.Y;
+    return pt;
+}
+
++ (AvnPoint)toAvnPoint:(CGPoint)p
+{
+    AvnPoint result;
+
+    result.X = p.x;
+    result.Y = p.y;
+
+    return result;
+}
+
+- (void) viewDidChangeBackingProperties
+{
+    auto fsize = [self convertSizeToBacking: [self frame].size];
+    _lastPixelSize.Width = (int)fsize.width;
+    _lastPixelSize.Height = (int)fsize.height;
+    [self updateRenderTarget];
+
+    if(_parent != nullptr)
+    {
+        _parent->BaseEvents->ScalingChanged([_parent->Window backingScaleFactor]);
+    }
+
+    [super viewDidChangeBackingProperties];
+}
+
+- (bool) ignoreUserInput:(bool)trigerInputWhenDisabled
+{
+    if(_parent == nullptr)
+    {
+        return TRUE;
+    }
+
+    auto parentWindow = _parent->GetWindowProtocol();
+
+    if(parentWindow == nil || ![parentWindow shouldTryToHandleEvents])
+    {
+        if(trigerInputWhenDisabled)
+        {
+            auto window = dynamic_cast<WindowImpl*>(_parent.getRaw());
+
+            if(window != nullptr)
+            {
+                window->WindowEvents->GotInputWhenDisabled();
+            }
+        }
+
+        return TRUE;
+    }
+
+    return FALSE;
+}
+
+- (void)mouseEvent:(NSEvent *)event withType:(AvnRawMouseEventType) type
+{
+    bool triggerInputWhenDisabled = type != Move;
+
+    if([self ignoreUserInput: triggerInputWhenDisabled])
+    {
+        return;
+    }
+
+    auto localPoint = [self convertPoint:[event locationInWindow] toView:self];
+    auto avnPoint = [AvnView toAvnPoint:localPoint];
+    auto point = [self translateLocalPoint:avnPoint];
+    AvnVector delta = { 0, 0};
+
+    if(type == Wheel)
+    {
+        auto speed = 5;
+
+        if([event hasPreciseScrollingDeltas])
+        {
+            speed = 50;
+        }
+
+        delta.X = [event scrollingDeltaX] / speed;
+        delta.Y = [event scrollingDeltaY] / speed;
+
+        if(delta.X == 0 && delta.Y == 0)
+        {
+            return;
+        }
+    }
+    else if (type == Magnify)
+    {
+        delta.X = delta.Y = [event magnification];
+    }
+    else if (type == Rotate)
+    {
+        delta.X = delta.Y = [event rotation];
+    }
+    else if (type == Swipe)
+    {
+        delta.X = [event deltaX];
+        delta.Y = [event deltaY];
+    }
+
+    uint32 timestamp = static_cast<uint32>([event timestamp] * 1000);
+    auto modifiers = [self getModifiers:[event modifierFlags]];
+
+    if(type != Move ||
+            (
+                    [self window] != nil &&
+                            (
+                                    [[self window] firstResponder] == nil
+                                            || ![[[self window] firstResponder] isKindOfClass: [NSView class]]
+                            )
+            )
+            )
+        [self becomeFirstResponder];
+
+    if(_parent != nullptr)
+    {
+        _parent->BaseEvents->RawMouseEvent(type, timestamp, modifiers, point, delta);
+    }
+
+    [super mouseMoved:event];
+}
+
+- (BOOL) resignFirstResponder
+{
+    _parent->BaseEvents->LostFocus();
+    return YES;
+}
+
+- (void)mouseMoved:(NSEvent *)event
+{
+    [self mouseEvent:event withType:Move];
+}
+
+- (void)mouseDown:(NSEvent *)event
+{
+    _isLeftPressed = true;
+    _lastMouseDownEvent = event;
+    [self mouseEvent:event withType:LeftButtonDown];
+}
+
+- (void)otherMouseDown:(NSEvent *)event
+{
+    _lastMouseDownEvent = event;
+
+    switch(event.buttonNumber)
+    {
+        case 2:
+        case 3:
+            _isMiddlePressed = true;
+            [self mouseEvent:event withType:MiddleButtonDown];
+            break;
+        case 4:
+            _isXButton1Pressed = true;
+            [self mouseEvent:event withType:XButton1Down];
+            break;
+        case 5:
+            _isXButton2Pressed = true;
+            [self mouseEvent:event withType:XButton2Down];
+            break;
+
+        default:
+            break;
+    }
+}
+
+- (void)rightMouseDown:(NSEvent *)event
+{
+    _isRightPressed = true;
+    _lastMouseDownEvent = event;
+    [self mouseEvent:event withType:RightButtonDown];
+}
+
+- (void)mouseUp:(NSEvent *)event
+{
+    _isLeftPressed = false;
+    [self mouseEvent:event withType:LeftButtonUp];
+}
+
+- (void)otherMouseUp:(NSEvent *)event
+{
+    switch(event.buttonNumber)
+    {
+        case 2:
+        case 3:
+            _isMiddlePressed = false;
+            [self mouseEvent:event withType:MiddleButtonUp];
+            break;
+        case 4:
+            _isXButton1Pressed = false;
+            [self mouseEvent:event withType:XButton1Up];
+            break;
+        case 5:
+            _isXButton2Pressed = false;
+            [self mouseEvent:event withType:XButton2Up];
+            break;
+
+        default:
+            break;
+    }
+}
+
+- (void)rightMouseUp:(NSEvent *)event
+{
+    _isRightPressed = false;
+    [self mouseEvent:event withType:RightButtonUp];
+}
+
+- (void)mouseDragged:(NSEvent *)event
+{
+    [self mouseEvent:event withType:Move];
+    [super mouseDragged:event];
+}
+
+- (void)otherMouseDragged:(NSEvent *)event
+{
+    [self mouseEvent:event withType:Move];
+    [super otherMouseDragged:event];
+}
+
+- (void)rightMouseDragged:(NSEvent *)event
+{
+    [self mouseEvent:event withType:Move];
+    [super rightMouseDragged:event];
+}
+
+- (void)scrollWheel:(NSEvent *)event
+{
+    [self mouseEvent:event withType:Wheel];
+    [super scrollWheel:event];
+}
+
+- (void)magnifyWithEvent:(NSEvent *)event
+{
+    [self mouseEvent:event withType:Magnify];
+    [super magnifyWithEvent:event];
+}
+
+- (void)rotateWithEvent:(NSEvent *)event
+{
+    [self mouseEvent:event withType:Rotate];
+    [super rotateWithEvent:event];
+}
+
+- (void)swipeWithEvent:(NSEvent *)event
+{
+    [self mouseEvent:event withType:Swipe];
+    [super swipeWithEvent:event];
+}
+
+- (void)mouseEntered:(NSEvent *)event
+{
+    [super mouseEntered:event];
+}
+
+- (void)mouseExited:(NSEvent *)event
+{
+    [self mouseEvent:event withType:LeaveWindow];
+    [super mouseExited:event];
+}
+
+- (void) keyboardEvent: (NSEvent *) event withType: (AvnRawKeyEventType)type
+{
+    if([self ignoreUserInput: false])
+    {
+        return;
+    }
+
+    auto key = s_KeyMap[[event keyCode]];
+
+    uint32_t timestamp = static_cast<uint32_t>([event timestamp] * 1000);
+    auto modifiers = [self getModifiers:[event modifierFlags]];
+
+    if(_parent != nullptr)
+    {
+        _lastKeyHandled = _parent->BaseEvents->RawKeyEvent(type, timestamp, modifiers, key);
+    }
+}
+
+- (BOOL)performKeyEquivalent:(NSEvent *)event
+{
+    bool result = _lastKeyHandled;
+
+    _lastKeyHandled = false;
+
+    return result;
+}
+
+- (void)flagsChanged:(NSEvent *)event
+{
+    auto newModifierState = [self getModifiers:[event modifierFlags]];
+
+    bool isAltCurrentlyPressed = (_modifierState & Alt) == Alt;
+    bool isControlCurrentlyPressed = (_modifierState & Control) == Control;
+    bool isShiftCurrentlyPressed = (_modifierState & Shift) == Shift;
+    bool isCommandCurrentlyPressed = (_modifierState & Windows) == Windows;
+
+    bool isAltPressed = (newModifierState & Alt) == Alt;
+    bool isControlPressed = (newModifierState & Control) == Control;
+    bool isShiftPressed = (newModifierState & Shift) == Shift;
+    bool isCommandPressed = (newModifierState & Windows) == Windows;
+
+
+    if (isAltPressed && !isAltCurrentlyPressed)
+    {
+        [self keyboardEvent:event withType:KeyDown];
+    }
+    else if (isAltCurrentlyPressed && !isAltPressed)
+    {
+        [self keyboardEvent:event withType:KeyUp];
+    }
+
+    if (isControlPressed && !isControlCurrentlyPressed)
+    {
+        [self keyboardEvent:event withType:KeyDown];
+    }
+    else if (isControlCurrentlyPressed && !isControlPressed)
+    {
+        [self keyboardEvent:event withType:KeyUp];
+    }
+
+    if (isShiftPressed && !isShiftCurrentlyPressed)
+    {
+        [self keyboardEvent:event withType:KeyDown];
+    }
+    else if(isShiftCurrentlyPressed && !isShiftPressed)
+    {
+        [self keyboardEvent:event withType:KeyUp];
+    }
+
+    if(isCommandPressed && !isCommandCurrentlyPressed)
+    {
+        [self keyboardEvent:event withType:KeyDown];
+    }
+    else if(isCommandCurrentlyPressed && ! isCommandPressed)
+    {
+        [self keyboardEvent:event withType:KeyUp];
+    }
+
+    _modifierState = newModifierState;
+
+    [[self inputContext] handleEvent:event];
+    [super flagsChanged:event];
+}
+
+- (void)keyDown:(NSEvent *)event
+{
+    [self keyboardEvent:event withType:KeyDown];
+    [[self inputContext] handleEvent:event];
+    [super keyDown:event];
+}
+
+- (void)keyUp:(NSEvent *)event
+{
+    [self keyboardEvent:event withType:KeyUp];
+    [super keyUp:event];
+}
+
+- (AvnInputModifiers)getModifiers:(NSEventModifierFlags)mod
+{
+    unsigned int rv = 0;
+
+    if (mod & NSEventModifierFlagControl)
+        rv |= Control;
+    if (mod & NSEventModifierFlagShift)
+        rv |= Shift;
+    if (mod & NSEventModifierFlagOption)
+        rv |= Alt;
+    if (mod & NSEventModifierFlagCommand)
+        rv |= Windows;
+
+    if (_isLeftPressed)
+        rv |= LeftMouseButton;
+    if (_isMiddlePressed)
+        rv |= MiddleMouseButton;
+    if (_isRightPressed)
+        rv |= RightMouseButton;
+    if (_isXButton1Pressed)
+        rv |= XButton1MouseButton;
+    if (_isXButton2Pressed)
+        rv |= XButton2MouseButton;
+
+    return (AvnInputModifiers)rv;
+}
+
+- (BOOL)hasMarkedText
+{
+    return _lastKeyHandled;
+}
+
+- (NSRange)markedRange
+{
+    return NSMakeRange(NSNotFound, 0);
+}
+
+- (NSRange)selectedRange
+{
+    return NSMakeRange(NSNotFound, 0);
+}
+
+- (void)setMarkedText:(id)string selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
+{
+
+}
+
+- (void)unmarkText
+{
+
+}
+
+- (NSArray<NSString *> *)validAttributesForMarkedText
+{
+    return [NSArray new];
+}
+
+- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)range actualRange:(NSRangePointer)actualRange
+{
+    return [NSAttributedString new];
+}
+
+- (void)insertText:(id)string replacementRange:(NSRange)replacementRange
+{
+    if(!_lastKeyHandled)
+    {
+        if(_parent != nullptr)
+        {
+            _lastKeyHandled = _parent->BaseEvents->RawTextInputEvent(0, [string UTF8String]);
+        }
+    }
+}
+
+- (NSUInteger)characterIndexForPoint:(NSPoint)point
+{
+    return 0;
+}
+
+- (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(NSRangePointer)actualRange
+{
+    CGRect result = { 0 };
+
+    return result;
+}
+
+- (NSDragOperation)triggerAvnDragEvent: (AvnDragEventType) type info: (id <NSDraggingInfo>)info
+{
+    auto localPoint = [self convertPoint:[info draggingLocation] toView:self];
+    auto avnPoint = [AvnView toAvnPoint:localPoint];
+    auto point = [self translateLocalPoint:avnPoint];
+    auto modifiers = [self getModifiers:[[NSApp currentEvent] modifierFlags]];
+    NSDragOperation nsop = [info draggingSourceOperationMask];
+
+    auto effects = ConvertDragDropEffects(nsop);
+    int reffects = (int)_parent->BaseEvents
+            ->DragEvent(type, point, modifiers, effects,
+                    CreateClipboard([info draggingPasteboard], nil),
+                    GetAvnDataObjectHandleFromDraggingInfo(info));
+
+    NSDragOperation ret = static_cast<NSDragOperation>(0);
+
+    // Ensure that the managed part didn't add any new effects
+    reffects = (int)effects & reffects;
+
+    // OSX requires exactly one operation
+    if((reffects & (int)AvnDragDropEffects::Copy) != 0)
+        ret = NSDragOperationCopy;
+    else if((reffects & (int)AvnDragDropEffects::Move) != 0)
+        ret = NSDragOperationMove;
+    else if((reffects & (int)AvnDragDropEffects::Link) != 0)
+        ret = NSDragOperationLink;
+    if(ret == 0)
+        ret = NSDragOperationNone;
+    return ret;
+}
+
+- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
+{
+    return [self triggerAvnDragEvent: AvnDragEventType::Enter info:sender];
+}
+
+- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
+{
+    return [self triggerAvnDragEvent: AvnDragEventType::Over info:sender];
+}
+
+- (void)draggingExited:(id <NSDraggingInfo>)sender
+{
+    [self triggerAvnDragEvent: AvnDragEventType::Leave info:sender];
+}
+
+- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
+{
+    return [self triggerAvnDragEvent: AvnDragEventType::Over info:sender] != NSDragOperationNone;
+}
+
+- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
+{
+    return [self triggerAvnDragEvent: AvnDragEventType::Drop info:sender] != NSDragOperationNone;
+}
+
+- (void)concludeDragOperation:(nullable id <NSDraggingInfo>)sender
+{
+
+}
+
+- (AvnPlatformResizeReason)getResizeReason
+{
+    return _resizeReason;
+}
+
+- (void)setResizeReason:(AvnPlatformResizeReason)reason
+{
+    _resizeReason = reason;
+}
+
+- (AvnAccessibilityElement *) accessibilityChild
+{
+    if (_accessibilityChild == nil)
+    {
+        auto peer = _parent->BaseEvents->GetAutomationPeer();
+
+        if (peer == nil)
+            return nil;
+
+        _accessibilityChild = [AvnAccessibilityElement acquire:peer];
+    }
+
+    return _accessibilityChild;
+}
+
+- (NSArray *)accessibilityChildren
+{
+    auto child = [self accessibilityChild];
+    return NSAccessibilityUnignoredChildrenForOnlyChild(child);
+}
+
+- (id)accessibilityHitTest:(NSPoint)point
+{
+    return [[self accessibilityChild] accessibilityHitTest:point];
+}
+
+- (id)accessibilityFocusedUIElement
+{
+    return [[self accessibilityChild] accessibilityFocusedUIElement];
+}
+
+@end

+ 466 - 0
native/Avalonia.Native/src/OSX/AvnWindow.mm

@@ -0,0 +1,466 @@
+//
+// Created by Dan Walmsley on 06/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+
+#import <AppKit/AppKit.h>
+#import "WindowProtocol.h"
+#import "WindowBaseImpl.h"
+
+#ifdef IS_NSPANEL
+#define BASE_CLASS NSPanel
+#define CLASS_NAME AvnPanel
+#else
+#define BASE_CLASS NSWindow
+#define CLASS_NAME AvnWindow
+#endif
+
+#import <AppKit/AppKit.h>
+#include "common.h"
+#include "menu.h"
+#include "automation.h"
+#include "WindowBaseImpl.h"
+#include "WindowImpl.h"
+#include "AvnView.h"
+#include "WindowInterfaces.h"
+#include "PopupImpl.h"
+
+@implementation CLASS_NAME
+{
+    ComPtr<WindowBaseImpl> _parent;
+    bool _closed;
+    bool _isEnabled;
+    bool _canBecomeKeyWindow;
+    bool _isExtended;
+    AvnMenu* _menu;
+}
+
+-(void) setIsExtended:(bool)value;
+{
+    _isExtended = value;
+}
+
+-(bool) isDialog
+{
+    return _parent->IsDialog();
+}
+
+-(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)performClose:(id)sender
+{
+    if([[self delegate] respondsToSelector:@selector(windowShouldClose:)])
+    {
+        if(![[self delegate] windowShouldClose:self]) return;
+    }
+    else if([self respondsToSelector:@selector(windowShouldClose:)])
+    {
+        if(![self windowShouldClose:self]) return;
+    }
+
+    [self close];
+}
+
+- (void)pollModalSession:(nonnull NSModalSession)session
+{
+    auto response = [NSApp runModalSession:session];
+
+    if(response == NSModalResponseContinue)
+    {
+        dispatch_async(dispatch_get_main_queue(), ^{
+            [self pollModalSession:session];
+        });
+    }
+    else if (!_closed)
+    {
+        [self orderOut:self];
+        [NSApp endModalSession:session];
+    }
+}
+
+-(void) showWindowMenuWithAppMenu
+{
+    if(_menu != nullptr)
+    {
+        auto appMenuItem = ::GetAppMenuItem();
+
+        if(appMenuItem != nullptr)
+        {
+            auto appMenu = [appMenuItem menu];
+
+            [appMenu removeItem:appMenuItem];
+
+            [_menu insertItem:appMenuItem atIndex:0];
+
+            [_menu setHasGlobalMenuItem:true];
+        }
+
+        [NSApp setMenu:_menu];
+    }
+    else
+    {
+        [self showAppMenuOnly];
+    }
+}
+
+-(void) showAppMenuOnly
+{
+    auto appMenuItem = ::GetAppMenuItem();
+
+    if(appMenuItem != nullptr)
+    {
+        auto appMenu = ::GetAppMenu();
+
+        auto nativeAppMenu = dynamic_cast<AvnAppMenu*>(appMenu);
+
+        [[appMenuItem menu] removeItem:appMenuItem];
+
+        if(_menu != nullptr)
+        {
+            [_menu setHasGlobalMenuItem:false];
+        }
+
+        [nativeAppMenu->GetNative() addItem:appMenuItem];
+
+        [NSApp setMenu:nativeAppMenu->GetNative()];
+    }
+}
+
+-(void) applyMenu:(AvnMenu *)menu
+{
+    if(menu == nullptr)
+    {
+        menu = [AvnMenu new];
+    }
+
+    _menu = menu;
+}
+
+-(CLASS_NAME*)  initWithParent: (WindowBaseImpl*) parent contentRect: (NSRect)contentRect styleMask: (NSWindowStyleMask)styleMask;
+{
+    // https://jameshfisher.com/2020/07/10/why-is-the-contentrect-of-my-nswindow-ignored/
+    // create nswindow with specific contentRect, otherwise we wont be able to resize the window
+    // until several ms after the window is physically on the screen.
+    self = [super initWithContentRect:contentRect styleMask: styleMask backing:NSBackingStoreBuffered defer:false];
+
+    [self setReleasedWhenClosed:false];
+    _parent = parent;
+    [self setDelegate:self];
+    _closed = false;
+    _isEnabled = true;
+
+    [self backingScaleFactor];
+    [self setOpaque:NO];
+    [self setBackgroundColor: [NSColor clearColor]];
+
+    _isExtended = false;
+
+#ifdef IS_NSPANEL
+    [self setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces|NSWindowCollectionBehaviorFullScreenAuxiliary];
+#endif
+
+    return self;
+}
+
+- (BOOL)windowShouldClose:(NSWindow *)sender
+{
+    auto window = dynamic_cast<WindowImpl*>(_parent.getRaw());
+
+    if(window != nullptr)
+    {
+        return !window->WindowEvents->Closing();
+    }
+
+    return true;
+}
+
+- (void)windowDidChangeBackingProperties:(NSNotification *)notification
+{
+    [self backingScaleFactor];
+}
+
+
+
+- (void)windowWillClose:(NSNotification *)notification
+{
+    _closed = true;
+    if(_parent)
+    {
+        ComPtr<WindowBaseImpl> parent = _parent;
+        _parent = NULL;
+        [self restoreParentWindow];
+        parent->BaseEvents->Closed();
+        [parent->View onClosed];
+    }
+}
+
+-(BOOL)canBecomeKeyWindow
+{
+    if(_canBecomeKeyWindow)
+    {
+        // If the window has a child window being shown as a dialog then don't allow it to become the key window.
+        for(NSWindow* uch in [self childWindows])
+        {
+            if (![uch conformsToProtocol:@protocol(AvnWindowProtocol)])
+            {
+                continue;
+            }
+
+            id <AvnWindowProtocol> ch = (id <AvnWindowProtocol>) uch;
+
+            if(ch.isDialog)
+                return false;
+        }
+
+        return true;
+    }
+    
+    return false;
+}
+
+#ifndef IS_NSPANEL
+-(BOOL)canBecomeMainWindow
+{
+    return true;
+}
+#endif
+
+-(void)setCanBecomeKeyWindow:(bool)value
+{
+    _canBecomeKeyWindow = value;
+}
+
+-(bool)shouldTryToHandleEvents
+{
+    return _isEnabled;
+}
+
+-(void) setEnabled:(bool)enable
+{
+    _isEnabled = enable;
+}
+
+-(void)becomeKeyWindow
+{
+    [self showWindowMenuWithAppMenu];
+
+    if(_parent != nullptr)
+    {
+        _parent->BaseEvents->Activated();
+    }
+
+    [super becomeKeyWindow];
+}
+
+-(void) restoreParentWindow;
+{
+    auto parent = [self parentWindow];
+
+    if(parent != nil)
+    {
+        [parent removeChildWindow:self];
+    }
+}
+
+- (void)windowDidMiniaturize:(NSNotification *)notification
+{
+    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
+
+    if(parent != nullptr)
+    {
+        parent->WindowStateChanged();
+    }
+}
+
+- (void)windowDidDeminiaturize:(NSNotification *)notification
+{
+    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
+
+    if(parent != nullptr)
+    {
+        parent->WindowStateChanged();
+    }
+}
+
+- (void)windowDidResize:(NSNotification *)notification
+{
+    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
+
+    if(parent != nullptr)
+    {
+        parent->WindowStateChanged();
+    }
+}
+
+- (void)windowWillExitFullScreen:(NSNotification *)notification
+{
+    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
+
+    if(parent != nullptr)
+    {
+        parent->StartStateTransition();
+    }
+}
+
+- (void)windowDidExitFullScreen:(NSNotification *)notification
+{
+    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
+
+    if(parent != nullptr)
+    {
+        parent->EndStateTransition();
+
+        if(parent->Decorations() != SystemDecorationsFull && parent->WindowState() == Maximized)
+        {
+            NSRect screenRect = [[self screen] visibleFrame];
+            [self setFrame:screenRect display:YES];
+        }
+
+        if(parent->WindowState() == Minimized)
+        {
+            [self miniaturize:nullptr];
+        }
+
+        parent->WindowStateChanged();
+    }
+}
+
+- (void)windowWillEnterFullScreen:(NSNotification *)notification
+{
+    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
+
+    if(parent != nullptr)
+    {
+        parent->StartStateTransition();
+    }
+}
+
+- (void)windowDidEnterFullScreen:(NSNotification *)notification
+{
+    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
+
+    if(parent != nullptr)
+    {
+        parent->EndStateTransition();
+        parent->WindowStateChanged();
+    }
+}
+
+- (BOOL)windowShouldZoom:(NSWindow *)window toFrame:(NSRect)newFrame
+{
+    return true;
+}
+
+-(void)resignKeyWindow
+{
+    if(_parent)
+        _parent->BaseEvents->Deactivated();
+
+    [self showAppMenuOnly];
+
+    [super resignKeyWindow];
+}
+
+- (void)windowDidMove:(NSNotification *)notification
+{
+    AvnPoint position;
+
+    if(_parent != nullptr)
+    {
+        auto cparent = dynamic_cast<WindowImpl*>(_parent.getRaw());
+
+        if(cparent != nullptr)
+        {
+            if(!cparent->IsShown())
+            {
+                return;
+            }
+
+            if(cparent->WindowState() == Maximized)
+            {
+                cparent->SetWindowState(Normal);
+            }
+        }
+
+        _parent->GetPosition(&position);
+        _parent->BaseEvents->PositionChanged(position);
+    }
+}
+
+- (AvnPoint) translateLocalPoint:(AvnPoint)pt
+{
+    pt.Y = [self frame].size.height - pt.Y;
+    return pt;
+}
+
+- (void)sendEvent:(NSEvent *)event
+{
+    [super sendEvent:event];
+
+    /// This is to detect non-client clicks. This can only be done on Windows... not popups, hence the dynamic_cast.
+    if(_parent != nullptr && dynamic_cast<WindowImpl*>(_parent.getRaw()) != nullptr)
+    {
+        switch(event.type)
+        {
+            case NSEventTypeLeftMouseDown:
+            {
+                AvnView* view = _parent->View;
+                NSPoint windowPoint = [event locationInWindow];
+                NSPoint viewPoint = [view convertPoint:windowPoint fromView:nil];
+
+                if (!NSPointInRect(viewPoint, view.bounds))
+                {
+                    auto avnPoint = [AvnView toAvnPoint:windowPoint];
+                    auto point = [self translateLocalPoint:avnPoint];
+                    AvnVector delta = { 0, 0 };
+
+                    _parent->BaseEvents->RawMouseEvent(NonClientLeftButtonDown, static_cast<uint32>([event timestamp] * 1000), AvnInputModifiersNone, point, delta);
+                }
+            }
+                break;
+
+            case NSEventTypeMouseEntered:
+            {
+                _parent->UpdateCursor();
+            }
+                break;
+
+            case NSEventTypeMouseExited:
+            {
+                [[NSCursor arrowCursor] set];
+            }
+                break;
+
+            default:
+                break;
+        }
+    }
+}
+
+- (void)disconnectParent {
+    _parent = nullptr;
+}
+
+@end
+

+ 17 - 0
native/Avalonia.Native/src/OSX/INSWindowHolder.h

@@ -0,0 +1,17 @@
+//
+// Created by Dan Walmsley on 04/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#ifndef AVALONIA_NATIVE_OSX_INSWINDOWHOLDER_H
+#define AVALONIA_NATIVE_OSX_INSWINDOWHOLDER_H
+
+@class AvnView;
+
+struct INSWindowHolder
+{
+    virtual NSWindow* _Nonnull GetNSWindow () = 0;
+    virtual NSView* _Nonnull GetNSView () = 0;
+};
+
+#endif //AVALONIA_NATIVE_OSX_INSWINDOWHOLDER_H

+ 18 - 0
native/Avalonia.Native/src/OSX/IWindowStateChanged.h

@@ -0,0 +1,18 @@
+//
+// Created by Dan Walmsley on 04/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#ifndef AVALONIA_NATIVE_OSX_IWINDOWSTATECHANGED_H
+#define AVALONIA_NATIVE_OSX_IWINDOWSTATECHANGED_H
+
+struct IWindowStateChanged
+{
+    virtual void WindowStateChanged () = 0;
+    virtual void StartStateTransition () = 0;
+    virtual void EndStateTransition () = 0;
+    virtual SystemDecorations Decorations () = 0;
+    virtual AvnWindowState WindowState () = 0;
+};
+
+#endif //AVALONIA_NATIVE_OSX_IWINDOWSTATECHANGED_H

+ 9 - 0
native/Avalonia.Native/src/OSX/PopupImpl.h

@@ -0,0 +1,9 @@
+//
+// Created by Dan Walmsley on 06/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#ifndef AVALONIA_NATIVE_OSX_POPUPIMPL_H
+#define AVALONIA_NATIVE_OSX_POPUPIMPL_H
+
+#endif //AVALONIA_NATIVE_OSX_POPUPIMPL_H

+ 61 - 0
native/Avalonia.Native/src/OSX/PopupImpl.mm

@@ -0,0 +1,61 @@
+//
+// Created by Dan Walmsley on 06/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#include "WindowInterfaces.h"
+#include "AvnView.h"
+#include "WindowImpl.h"
+#include "automation.h"
+#include "menu.h"
+#include "common.h"
+#import "WindowBaseImpl.h"
+#import "WindowProtocol.h"
+#import <AppKit/AppKit.h>
+#include "PopupImpl.h"
+
+class PopupImpl : public virtual WindowBaseImpl, public IAvnPopup
+{
+private:
+    BEGIN_INTERFACE_MAP()
+    INHERIT_INTERFACE_MAP(WindowBaseImpl)
+    INTERFACE_MAP_ENTRY(IAvnPopup, IID_IAvnPopup)
+    END_INTERFACE_MAP()
+    virtual ~PopupImpl(){}
+    ComPtr<IAvnWindowEvents> WindowEvents;
+    PopupImpl(IAvnWindowEvents* events, IAvnGlContext* gl) : WindowBaseImpl(events, gl)
+    {
+        WindowEvents = events;
+    }
+protected:
+    virtual NSWindowStyleMask GetStyle() override
+    {
+        return NSWindowStyleMaskBorderless;
+    }
+    
+    virtual void OnInitialiseNSWindow () override
+    {
+        [Window setLevel:NSPopUpMenuWindowLevel];
+    }
+
+public:
+    virtual bool ShouldTakeFocusOnShow() override
+    {
+        return false;
+    }
+
+    virtual HRESULT Show(bool activate, bool isDialog) override
+    {
+        return WindowBaseImpl::Show(activate, true);
+    }
+};
+
+
+extern IAvnPopup* CreateAvnPopup(IAvnWindowEvents*events, IAvnGlContext* gl)
+{
+    @autoreleasepool
+    {
+        IAvnPopup* ptr = dynamic_cast<IAvnPopup*>(new PopupImpl(events, gl));
+        return ptr;
+    }
+}

+ 24 - 0
native/Avalonia.Native/src/OSX/ResizeScope.h

@@ -0,0 +1,24 @@
+//
+// Created by Dan Walmsley on 04/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#ifndef AVALONIA_NATIVE_OSX_RESIZESCOPE_H
+#define AVALONIA_NATIVE_OSX_RESIZESCOPE_H
+
+#include "avalonia-native.h"
+
+@class AvnView;
+
+class ResizeScope
+{
+public:
+    ResizeScope(AvnView* _Nonnull view, AvnPlatformResizeReason reason);
+
+    ~ResizeScope();
+private:
+    AvnView* _Nonnull _view;
+    AvnPlatformResizeReason _restore;
+};
+
+#endif //AVALONIA_NATIVE_OSX_RESIZESCOPE_H

+ 18 - 0
native/Avalonia.Native/src/OSX/ResizeScope.mm

@@ -0,0 +1,18 @@
+//
+// Created by Dan Walmsley on 04/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#import <AppKit/AppKit.h>
+#include "ResizeScope.h"
+#include "AvnView.h"
+
+ResizeScope::ResizeScope(AvnView *view, AvnPlatformResizeReason reason) {
+    _view = view;
+    _restore = [view getResizeReason];
+    [view setResizeReason:reason];
+}
+
+ResizeScope::~ResizeScope() {
+    [_view setResizeReason:_restore];
+}

+ 1 - 1
native/Avalonia.Native/src/OSX/SystemDialogs.mm

@@ -1,5 +1,5 @@
 #include "common.h"
-#include "window.h"
+#include "INSWindowHolder.h"
 
 class SystemDialogs : public ComSingleObject<IAvnSystemDialogs, &IID_IAvnSystemDialogs>
 {

+ 136 - 0
native/Avalonia.Native/src/OSX/WindowBaseImpl.h

@@ -0,0 +1,136 @@
+//
+// Created by Dan Walmsley on 04/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#ifndef AVALONIA_NATIVE_OSX_WINDOWBASEIMPL_H
+#define AVALONIA_NATIVE_OSX_WINDOWBASEIMPL_H
+
+#include "rendertarget.h"
+#include "INSWindowHolder.h"
+
+@class AutoFitContentView;
+@class AvnMenu;
+@protocol AvnWindowProtocol;
+
+class WindowBaseImpl : public virtual ComObject,
+                       public virtual IAvnWindowBase,
+                       public INSWindowHolder {
+
+public:
+    FORWARD_IUNKNOWN()
+
+BEGIN_INTERFACE_MAP()
+        INTERFACE_MAP_ENTRY(IAvnWindowBase, IID_IAvnWindowBase)
+    END_INTERFACE_MAP()
+
+    virtual ~WindowBaseImpl();
+
+    WindowBaseImpl(IAvnWindowBaseEvents *events, IAvnGlContext *gl);
+
+    virtual HRESULT ObtainNSWindowHandle(void **ret) override;
+
+    virtual HRESULT ObtainNSWindowHandleRetained(void **ret) override;
+
+    virtual HRESULT ObtainNSViewHandle(void **ret) override;
+
+    virtual HRESULT ObtainNSViewHandleRetained(void **ret) override;
+
+    virtual NSWindow *GetNSWindow() override;
+
+    virtual NSView *GetNSView() override;
+
+    virtual HRESULT Show(bool activate, bool isDialog) override;
+
+    virtual bool IsShown ();
+
+    virtual bool ShouldTakeFocusOnShow();
+
+    virtual HRESULT Hide() override;
+
+    virtual HRESULT Activate() override;
+
+    virtual HRESULT SetTopMost(bool value) override;
+
+    virtual HRESULT Close() override;
+
+    virtual HRESULT GetClientSize(AvnSize *ret) override;
+
+    virtual HRESULT GetFrameSize(AvnSize *ret) override;
+
+    virtual HRESULT GetScaling(double *ret) override;
+
+    virtual HRESULT SetMinMaxSize(AvnSize minSize, AvnSize maxSize) override;
+
+    virtual HRESULT Resize(double x, double y, AvnPlatformResizeReason reason) override;
+
+    virtual HRESULT Invalidate(__attribute__((unused)) AvnRect rect) override;
+
+    virtual HRESULT SetMainMenu(IAvnMenu *menu) override;
+
+    virtual HRESULT BeginMoveDrag() override;
+
+    virtual HRESULT BeginResizeDrag(__attribute__((unused)) AvnWindowEdge edge) override;
+
+    virtual HRESULT GetPosition(AvnPoint *ret) override;
+
+    virtual HRESULT SetPosition(AvnPoint point) override;
+
+    virtual HRESULT PointToClient(AvnPoint point, AvnPoint *ret) override;
+
+    virtual HRESULT PointToScreen(AvnPoint point, AvnPoint *ret) override;
+
+    virtual HRESULT ThreadSafeSetSwRenderedFrame(AvnFramebuffer *fb, IUnknown *dispose) override;
+
+    virtual HRESULT SetCursor(IAvnCursor *cursor) override;
+
+    virtual void UpdateCursor();
+
+    virtual HRESULT CreateGlRenderTarget(IAvnGlSurfaceRenderTarget **ppv) override;
+
+    virtual HRESULT CreateNativeControlHost(IAvnNativeControlHost **retOut) override;
+
+    virtual HRESULT SetBlurEnabled(bool enable) override;
+
+    virtual HRESULT BeginDragAndDropOperation(AvnDragDropEffects effects, AvnPoint point,
+            IAvnClipboard *clipboard, IAvnDndResultCallback *cb,
+            void *sourceHandle) override;
+
+    virtual bool IsDialog();
+
+    id<AvnWindowProtocol> GetWindowProtocol ();
+
+protected:
+    virtual NSWindowStyleMask GetStyle();
+
+    void UpdateStyle();
+                           
+    virtual void OnInitialiseNSWindow ();
+
+private:
+    void CreateNSWindow (bool isDialog);
+    void CleanNSWindow ();
+    void InitialiseNSWindow ();
+
+    NSCursor *cursor;
+    ComPtr<IAvnGlContext> _glContext;
+    bool hasPosition;
+    NSSize lastSize;
+    NSSize lastMinSize;
+    NSSize lastMaxSize;
+    AvnMenu* lastMenu;
+    bool _inResize;
+
+protected:
+    AvnPoint lastPositionSet;
+    AutoFitContentView *StandardContainer;
+    bool _shown;
+
+public:
+    NSObject <IRenderTarget> *renderTarget;
+    NSWindow * Window;
+    ComPtr<IAvnWindowBaseEvents> BaseEvents;
+    AvnView *View;
+};
+
+#endif //AVALONIA_NATIVE_OSX_WINDOWBASEIMPL_H

+ 615 - 0
native/Avalonia.Native/src/OSX/WindowBaseImpl.mm

@@ -0,0 +1,615 @@
+//
+// Created by Dan Walmsley on 04/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#import <AppKit/AppKit.h>
+#include "common.h"
+#include "AvnView.h"
+#include "menu.h"
+#include "automation.h"
+#include "cursor.h"
+#include "ResizeScope.h"
+#include "AutoFitContentView.h"
+#import "WindowProtocol.h"
+#import "WindowInterfaces.h"
+#include "WindowBaseImpl.h"
+
+
+WindowBaseImpl::~WindowBaseImpl() {
+    View = nullptr;
+    Window = nullptr;
+}
+
+WindowBaseImpl::WindowBaseImpl(IAvnWindowBaseEvents *events, IAvnGlContext *gl) {
+    _shown = false;
+    _inResize = false;
+    BaseEvents = events;
+    _glContext = gl;
+    renderTarget = [[IOSurfaceRenderTarget alloc] initWithOpenGlContext:gl];
+    View = [[AvnView alloc] initWithParent:this];
+    StandardContainer = [[AutoFitContentView new] initWithContent:View];
+
+    lastPositionSet = { 0, 0 };
+    hasPosition = false;
+    lastSize = NSSize { 100, 100 };
+    lastMaxSize = NSSize { CGFLOAT_MAX, CGFLOAT_MAX};
+    lastMinSize = NSSize { 0, 0 };
+
+    Window = nullptr;
+    lastMenu = nullptr;
+}
+
+HRESULT WindowBaseImpl::ObtainNSViewHandle(void **ret) {
+    START_COM_CALL;
+
+    if (ret == nullptr) {
+        return E_POINTER;
+    }
+
+    *ret = (__bridge void *) View;
+
+    return S_OK;
+}
+
+HRESULT WindowBaseImpl::ObtainNSViewHandleRetained(void **ret) {
+    START_COM_CALL;
+
+    if (ret == nullptr) {
+        return E_POINTER;
+    }
+
+    *ret = (__bridge_retained void *) View;
+
+    return S_OK;
+}
+
+NSWindow *WindowBaseImpl::GetNSWindow() {
+    return Window;
+}
+
+NSView *WindowBaseImpl::GetNSView() {
+    return View;
+}
+
+HRESULT WindowBaseImpl::ObtainNSWindowHandleRetained(void **ret) {
+    START_COM_CALL;
+
+    if (ret == nullptr) {
+        return E_POINTER;
+    }
+
+    *ret = (__bridge_retained void *) Window;
+
+    return S_OK;
+}
+
+HRESULT WindowBaseImpl::Show(bool activate, bool isDialog) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        CreateNSWindow(isDialog);
+        InitialiseNSWindow();
+
+        if(hasPosition)
+        {
+            SetPosition(lastPositionSet);
+        } else
+        {
+            [Window center];
+        }
+
+        UpdateStyle();
+
+        if (ShouldTakeFocusOnShow() && activate) {
+            [Window orderFront:Window];
+            [Window makeKeyAndOrderFront:Window];
+            [Window makeFirstResponder:View];
+            [NSApp activateIgnoringOtherApps:YES];
+        } else {
+            [Window orderFront:Window];
+        }
+
+        _shown = true;
+
+        return S_OK;
+    }
+}
+
+bool WindowBaseImpl::IsShown ()
+{
+    return _shown;
+}
+
+bool WindowBaseImpl::ShouldTakeFocusOnShow() {
+    return true;
+}
+
+HRESULT WindowBaseImpl::ObtainNSWindowHandle(void **ret) {
+    START_COM_CALL;
+
+    if (ret == nullptr) {
+        return E_POINTER;
+    }
+
+    *ret = (__bridge void *) Window;
+
+    return S_OK;
+}
+
+HRESULT WindowBaseImpl::Hide() {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        if (Window != nullptr) {
+            [Window orderOut:Window];
+
+            [GetWindowProtocol() restoreParentWindow];
+        }
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::Activate() {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        if (Window != nullptr) {
+            [Window makeKeyAndOrderFront:nil];
+            [NSApp activateIgnoringOtherApps:YES];
+        }
+    }
+
+    return S_OK;
+}
+
+HRESULT WindowBaseImpl::SetTopMost(bool value) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        [Window setLevel:value ? NSFloatingWindowLevel : NSNormalWindowLevel];
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::Close() {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        if (Window != nullptr) {
+            auto window = Window;
+            Window = nullptr;
+
+            try {
+                // Seems to throw sometimes on application exit.
+                [window close];
+            }
+            catch (NSException *) {}
+        }
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::GetClientSize(AvnSize *ret) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        if (ret == nullptr)
+            return E_POINTER;
+
+        ret->Width = lastSize.width;
+        ret->Height = lastSize.height;
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::GetFrameSize(AvnSize *ret) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        if (ret == nullptr)
+            return E_POINTER;
+
+        if(Window != nullptr){
+            auto frame = [Window frame];
+            ret->Width = frame.size.width;
+            ret->Height = frame.size.height;
+        }
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::GetScaling(double *ret) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        if (ret == nullptr)
+            return E_POINTER;
+
+        if (Window == nullptr) {
+            *ret = 1;
+            return S_OK;
+        }
+
+        *ret = [Window backingScaleFactor];
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::SetMinMaxSize(AvnSize minSize, AvnSize maxSize) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        lastMinSize = ToNSSize(minSize);
+        lastMaxSize = ToNSSize(maxSize);
+
+        if(Window != nullptr) {
+            [Window setContentMinSize:lastMinSize];
+            [Window setContentMaxSize:lastMaxSize];
+        }
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::Resize(double x, double y, AvnPlatformResizeReason reason) {
+    if (_inResize) {
+        return S_OK;
+    }
+
+    _inResize = true;
+
+    START_COM_CALL;
+    auto resizeBlock = ResizeScope(View, reason);
+
+    @autoreleasepool {
+        auto maxSize = lastMaxSize;
+        auto minSize = lastMinSize;
+
+        if (x < minSize.width) {
+            x = minSize.width;
+        }
+
+        if (y < minSize.height) {
+            y = minSize.height;
+        }
+
+        if (x > maxSize.width) {
+            x = maxSize.width;
+        }
+
+        if (y > maxSize.height) {
+            y = maxSize.height;
+        }
+
+        @try {
+            lastSize = NSSize {x, y};
+
+            if (!_shown) {
+                BaseEvents->Resized(AvnSize{x, y}, reason);
+            }
+
+            if(Window != nullptr) {
+                [Window setContentSize:lastSize];
+            }
+        }
+        @finally {
+            _inResize = false;
+        }
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::Invalidate(__attribute__((unused)) AvnRect rect) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        [View setNeedsDisplayInRect:[View frame]];
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::SetMainMenu(IAvnMenu *menu) {
+    START_COM_CALL;
+
+    auto nativeMenu = dynamic_cast<AvnAppMenu *>(menu);
+
+    lastMenu = nativeMenu->GetNative();
+
+    if(Window != nullptr) {
+        [GetWindowProtocol() applyMenu:lastMenu];
+
+        if ([Window isKeyWindow]) {
+            [GetWindowProtocol() showWindowMenuWithAppMenu];
+        }
+    }
+
+    return S_OK;
+}
+
+HRESULT WindowBaseImpl::BeginMoveDrag() {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        auto lastEvent = [View lastMouseDownEvent];
+
+        if (lastEvent == nullptr) {
+            return S_OK;
+        }
+
+        [Window performWindowDragWithEvent:lastEvent];
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::BeginResizeDrag(__attribute__((unused)) AvnWindowEdge edge) {
+    START_COM_CALL;
+
+    return S_OK;
+}
+
+HRESULT WindowBaseImpl::GetPosition(AvnPoint *ret) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        if (ret == nullptr) {
+            return E_POINTER;
+        }
+
+        if(Window != nullptr) {
+            auto frame = [Window frame];
+
+            ret->X = frame.origin.x;
+            ret->Y = frame.origin.y + frame.size.height;
+
+            *ret = ConvertPointY(*ret);
+        } else
+        {
+            *ret = lastPositionSet;
+        }
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::SetPosition(AvnPoint point) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        lastPositionSet = point;
+        hasPosition = true;
+
+        if(Window != nullptr) {
+            [Window setFrameTopLeftPoint:ToNSPoint(ConvertPointY(point))];
+        }
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::PointToClient(AvnPoint point, AvnPoint *ret) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        if (ret == nullptr) {
+            return E_POINTER;
+        }
+
+        point = ConvertPointY(point);
+        NSRect convertRect = [Window convertRectFromScreen:NSMakeRect(point.X, point.Y, 0.0, 0.0)];
+        auto viewPoint = NSMakePoint(convertRect.origin.x, convertRect.origin.y);
+
+        *ret = [View translateLocalPoint:ToAvnPoint(viewPoint)];
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::PointToScreen(AvnPoint point, AvnPoint *ret) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        if (ret == nullptr) {
+            return E_POINTER;
+        }
+
+        auto cocoaViewPoint = ToNSPoint([View translateLocalPoint:point]);
+        NSRect convertRect = [Window convertRectToScreen:NSMakeRect(cocoaViewPoint.x, cocoaViewPoint.y, 0.0, 0.0)];
+        auto cocoaScreenPoint = NSPointFromCGPoint(NSMakePoint(convertRect.origin.x, convertRect.origin.y));
+        *ret = ConvertPointY(ToAvnPoint(cocoaScreenPoint));
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowBaseImpl::ThreadSafeSetSwRenderedFrame(AvnFramebuffer *fb, IUnknown *dispose) {
+    START_COM_CALL;
+
+    [View setSwRenderedFrame:fb dispose:dispose];
+    return S_OK;
+}
+
+HRESULT WindowBaseImpl::SetCursor(IAvnCursor *cursor) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        Cursor *avnCursor = dynamic_cast<Cursor *>(cursor);
+        this->cursor = avnCursor->GetNative();
+        UpdateCursor();
+
+        if (avnCursor->IsHidden()) {
+            [NSCursor hide];
+        } else {
+            [NSCursor unhide];
+        }
+
+        return S_OK;
+    }
+}
+
+void WindowBaseImpl::UpdateCursor() {
+    if (cursor != nil) {
+        [cursor set];
+    }
+}
+
+HRESULT WindowBaseImpl::CreateGlRenderTarget(IAvnGlSurfaceRenderTarget **ppv) {
+    START_COM_CALL;
+
+    if (View == NULL)
+        return E_FAIL;
+    *ppv = [renderTarget createSurfaceRenderTarget];
+    return static_cast<HRESULT>(*ppv == nil ? E_FAIL : S_OK);
+}
+
+HRESULT WindowBaseImpl::CreateNativeControlHost(IAvnNativeControlHost **retOut) {
+    START_COM_CALL;
+
+    if (View == NULL)
+        return E_FAIL;
+    *retOut = ::CreateNativeControlHost(View);
+    return S_OK;
+}
+
+HRESULT WindowBaseImpl::SetBlurEnabled(bool enable) {
+    START_COM_CALL;
+
+    [StandardContainer ShowBlur:enable];
+
+    return S_OK;
+}
+
+HRESULT WindowBaseImpl::BeginDragAndDropOperation(AvnDragDropEffects effects, AvnPoint point, IAvnClipboard *clipboard, IAvnDndResultCallback *cb, void *sourceHandle) {
+    START_COM_CALL;
+
+    auto item = TryGetPasteboardItem(clipboard);
+    [item setString:@"" forType:GetAvnCustomDataType()];
+    if (item == nil)
+        return E_INVALIDARG;
+    if (View == NULL)
+        return E_FAIL;
+
+    auto nsevent = [NSApp currentEvent];
+    auto nseventType = [nsevent type];
+
+    // If current event isn't a mouse one (probably due to malfunctioning user app)
+    // attempt to forge a new one
+    if (!((nseventType >= NSEventTypeLeftMouseDown && nseventType <= NSEventTypeMouseExited)
+            || (nseventType >= NSEventTypeOtherMouseDown && nseventType <= NSEventTypeOtherMouseDragged))) {
+        NSRect convertRect = [Window convertRectToScreen:NSMakeRect(point.X, point.Y, 0.0, 0.0)];
+        auto nspoint = NSMakePoint(convertRect.origin.x, convertRect.origin.y);
+        CGPoint cgpoint = NSPointToCGPoint(nspoint);
+        auto cgevent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, cgpoint, kCGMouseButtonLeft);
+        nsevent = [NSEvent eventWithCGEvent:cgevent];
+        CFRelease(cgevent);
+    }
+
+    auto dragItem = [[NSDraggingItem alloc] initWithPasteboardWriter:item];
+
+    auto dragItemImage = [NSImage imageNamed:NSImageNameMultipleDocuments];
+    NSRect dragItemRect = {(float) point.X, (float) point.Y, [dragItemImage size].width, [dragItemImage size].height};
+    [dragItem setDraggingFrame:dragItemRect contents:dragItemImage];
+
+    int op = 0;
+    int ieffects = (int) effects;
+    if ((ieffects & (int) AvnDragDropEffects::Copy) != 0)
+        op |= NSDragOperationCopy;
+    if ((ieffects & (int) AvnDragDropEffects::Link) != 0)
+        op |= NSDragOperationLink;
+    if ((ieffects & (int) AvnDragDropEffects::Move) != 0)
+        op |= NSDragOperationMove;
+    [View beginDraggingSessionWithItems:@[dragItem] event:nsevent
+                                 source:CreateDraggingSource((NSDragOperation) op, cb, sourceHandle)];
+    return S_OK;
+}
+
+bool WindowBaseImpl::IsDialog() {
+    return false;
+}
+
+NSWindowStyleMask WindowBaseImpl::GetStyle() {
+    return NSWindowStyleMaskBorderless;
+}
+
+void WindowBaseImpl::UpdateStyle() {
+    [Window setStyleMask:GetStyle()];
+}
+
+void WindowBaseImpl::CleanNSWindow() {
+    if(Window != nullptr) {
+        [GetWindowProtocol() disconnectParent];
+        [Window close];
+        Window = nullptr;
+    }
+}
+
+void WindowBaseImpl::CreateNSWindow(bool isDialog) {
+    if (isDialog) {
+        if (![Window isKindOfClass:[AvnPanel class]]) {
+            CleanNSWindow();
+
+            Window = [[AvnPanel alloc] initWithParent:this contentRect:NSRect{0, 0, lastSize} styleMask:GetStyle()];
+        }
+    } else {
+        if (![Window isKindOfClass:[AvnWindow class]]) {
+            CleanNSWindow();
+
+            Window = [[AvnWindow alloc] initWithParent:this contentRect:NSRect{0, 0, lastSize} styleMask:GetStyle()];
+        }
+    }
+}
+
+void WindowBaseImpl::OnInitialiseNSWindow()
+{
+    
+}
+
+void WindowBaseImpl::InitialiseNSWindow() {
+    if(Window != nullptr) {
+        [Window setContentView:StandardContainer];
+        [Window setStyleMask:NSWindowStyleMaskBorderless];
+        [Window setBackingType:NSBackingStoreBuffered];
+
+        [Window setContentSize:lastSize];
+        [Window setContentMinSize:lastMinSize];
+        [Window setContentMaxSize:lastMaxSize];
+
+        [Window setOpaque:false];
+
+        if (lastMenu != nullptr) {
+            [GetWindowProtocol() applyMenu:lastMenu];
+
+            if ([Window isKeyWindow]) {
+                [GetWindowProtocol() showWindowMenuWithAppMenu];
+            }
+        }
+        
+        OnInitialiseNSWindow();
+    }
+}
+
+id <AvnWindowProtocol> WindowBaseImpl::GetWindowProtocol() {
+    if(Window == nullptr)
+    {
+        return nullptr;
+    }
+
+    return (id <AvnWindowProtocol>) Window;
+}
+
+extern IAvnWindow* CreateAvnWindow(IAvnWindowEvents*events, IAvnGlContext* gl)
+{
+    @autoreleasepool
+    {
+        IAvnWindow* ptr = (IAvnWindow*)new WindowImpl(events, gl);
+        return ptr;
+    }
+}

+ 101 - 0
native/Avalonia.Native/src/OSX/WindowImpl.h

@@ -0,0 +1,101 @@
+//
+// Created by Dan Walmsley on 04/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#ifndef AVALONIA_NATIVE_OSX_WINDOWIMPL_H
+#define AVALONIA_NATIVE_OSX_WINDOWIMPL_H
+
+#import "WindowBaseImpl.h"
+#include "IWindowStateChanged.h"
+
+class WindowImpl : public virtual WindowBaseImpl, public virtual IAvnWindow, public IWindowStateChanged
+{
+private:
+    bool _canResize;
+    bool _fullScreenActive;
+    SystemDecorations _decorations;
+    AvnWindowState _lastWindowState;
+    AvnWindowState _actualWindowState;
+    bool _inSetWindowState;
+    NSRect _preZoomSize;
+    bool _transitioningWindowState;
+    bool _isClientAreaExtended;
+    bool _isDialog;
+    AvnExtendClientAreaChromeHints _extendClientHints;
+
+    FORWARD_IUNKNOWN()
+BEGIN_INTERFACE_MAP()
+        INHERIT_INTERFACE_MAP(WindowBaseImpl)
+        INTERFACE_MAP_ENTRY(IAvnWindow, IID_IAvnWindow)
+    END_INTERFACE_MAP()
+    virtual ~WindowImpl()
+    {
+    }
+
+    ComPtr<IAvnWindowEvents> WindowEvents;
+
+    WindowImpl(IAvnWindowEvents* events, IAvnGlContext* gl);
+
+    void HideOrShowTrafficLights ();
+
+    virtual HRESULT Show (bool activate, bool isDialog) override;
+
+    virtual HRESULT SetEnabled (bool enable) override;
+
+    virtual HRESULT SetParent (IAvnWindow* parent) override;
+
+    void StartStateTransition () override ;
+
+    void EndStateTransition () override ;
+
+    SystemDecorations Decorations () override ;
+
+    AvnWindowState WindowState () override ;
+
+    void WindowStateChanged () override ;
+
+    bool UndecoratedIsMaximized ();
+
+    bool IsZoomed ();
+
+    void DoZoom();
+
+    virtual HRESULT SetCanResize(bool value) override;
+
+    virtual HRESULT SetDecorations(SystemDecorations value) override;
+
+    virtual HRESULT SetTitle (char* utf8title) override;
+
+    virtual HRESULT SetTitleBarColor(AvnColor color) override;
+
+    virtual HRESULT GetWindowState (AvnWindowState*ret) override;
+
+    virtual HRESULT TakeFocusFromChildren () override;
+
+    virtual HRESULT SetExtendClientArea (bool enable) override;
+
+    virtual HRESULT SetExtendClientAreaHints (AvnExtendClientAreaChromeHints hints) override;
+
+    virtual HRESULT GetExtendTitleBarHeight (double*ret) override;
+
+    virtual HRESULT SetExtendTitleBarHeight (double value) override;
+
+    void EnterFullScreenMode ();
+
+    void ExitFullScreenMode ();
+
+    virtual HRESULT SetWindowState (AvnWindowState state) override;
+
+    virtual bool IsDialog() override;
+    
+    virtual void OnInitialiseNSWindow() override;
+
+protected:
+    virtual NSWindowStyleMask GetStyle() override;
+
+private:
+    NSString *_lastTitle;
+};
+
+#endif //AVALONIA_NATIVE_OSX_WINDOWIMPL_H

+ 554 - 0
native/Avalonia.Native/src/OSX/WindowImpl.mm

@@ -0,0 +1,554 @@
+//
+// Created by Dan Walmsley on 04/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#import <AppKit/AppKit.h>
+#include "AutoFitContentView.h"
+#include "AvnView.h"
+#include "automation.h"
+#include "WindowProtocol.h"
+
+WindowImpl::WindowImpl(IAvnWindowEvents *events, IAvnGlContext *gl) : WindowBaseImpl(events, gl) {
+    _isClientAreaExtended = false;
+    _extendClientHints = AvnDefaultChrome;
+    _fullScreenActive = false;
+    _canResize = true;
+    _decorations = SystemDecorationsFull;
+    _transitioningWindowState = false;
+    _inSetWindowState = false;
+    _lastWindowState = Normal;
+    _actualWindowState = Normal;
+    _lastTitle = @"";
+    WindowEvents = events;
+}
+
+void WindowImpl::HideOrShowTrafficLights() {
+    if (Window == nil) {
+        return;
+    }
+
+    for (id subview in Window.contentView.superview.subviews) {
+        if ([subview isKindOfClass:NSClassFromString(@"NSTitlebarContainerView")]) {
+            NSView *titlebarView = [subview subviews][0];
+            for (id button in titlebarView.subviews) {
+                if ([button isKindOfClass:[NSButton class]]) {
+                    if (_isClientAreaExtended) {
+                        auto wantsChrome = (_extendClientHints & AvnSystemChrome) || (_extendClientHints & AvnPreferSystemChrome);
+
+                        [button setHidden:!wantsChrome];
+                    } else {
+                        [button setHidden:(_decorations != SystemDecorationsFull)];
+                    }
+
+                    [button setWantsLayer:true];
+                }
+            }
+        }
+    }
+}
+
+void WindowImpl::OnInitialiseNSWindow(){
+    [GetWindowProtocol() setCanBecomeKeyWindow:true];
+    [Window disableCursorRects];
+    [Window setTabbingMode:NSWindowTabbingModeDisallowed];
+    [Window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
+
+    [Window setTitle:_lastTitle];
+    
+    if(_isClientAreaExtended)
+    {
+        [GetWindowProtocol() setIsExtended:true];
+        SetExtendClientArea(true);
+    }
+}
+
+HRESULT WindowImpl::Show(bool activate, bool isDialog) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        _isDialog = isDialog;
+
+        WindowBaseImpl::Show(activate, isDialog);
+
+        HideOrShowTrafficLights();
+
+        return SetWindowState(_lastWindowState);
+    }
+}
+
+HRESULT WindowImpl::SetEnabled(bool enable) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        [GetWindowProtocol() setEnabled:enable];
+        return S_OK;
+    }
+}
+
+HRESULT WindowImpl::SetParent(IAvnWindow *parent) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        if (parent == nullptr)
+            return E_POINTER;
+
+        auto cparent = dynamic_cast<WindowImpl *>(parent);
+        if (cparent == nullptr)
+            return E_INVALIDARG;
+
+        // If one tries to show a child window with a minimized parent window, then the parent window will be
+        // restored but macOS isn't kind enough to *tell* us that, so the window will be left in a non-interactive
+        // state. Detect this and explicitly restore the parent window ourselves to avoid this situation.
+        if (cparent->WindowState() == Minimized)
+            cparent->SetWindowState(Normal);
+
+        [Window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
+        [cparent->Window addChildWindow:Window ordered:NSWindowAbove];
+
+        UpdateStyle();
+
+        return S_OK;
+    }
+}
+
+void WindowImpl::StartStateTransition() {
+    _transitioningWindowState = true;
+}
+
+void WindowImpl::EndStateTransition() {
+    _transitioningWindowState = false;
+}
+
+SystemDecorations WindowImpl::Decorations() {
+    return _decorations;
+}
+
+AvnWindowState WindowImpl::WindowState() {
+    return _lastWindowState;
+}
+
+void WindowImpl::WindowStateChanged() {
+    if (_shown && !_inSetWindowState && !_transitioningWindowState) {
+        AvnWindowState state;
+        GetWindowState(&state);
+
+        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;
+            _actualWindowState = state;
+            WindowEvents->WindowStateChanged(state);
+        }
+    }
+}
+
+bool WindowImpl::UndecoratedIsMaximized() {
+    auto windowSize = [Window frame];
+    auto available = [Window screen].visibleFrame;
+    return CGRectEqualToRect(windowSize, available);
+}
+
+bool WindowImpl::IsZoomed() {
+    return _decorations == SystemDecorationsFull ? [Window isZoomed] : UndecoratedIsMaximized();
+}
+
+void WindowImpl::DoZoom() {
+    switch (_decorations) {
+        case SystemDecorationsNone:
+        case SystemDecorationsBorderOnly:
+            [Window setFrame:[Window screen].visibleFrame display:true];
+            break;
+
+
+        case SystemDecorationsFull:
+            [Window performZoom:Window];
+            break;
+    }
+}
+
+HRESULT WindowImpl::SetCanResize(bool value) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        _canResize = value;
+        UpdateStyle();
+        return S_OK;
+    }
+}
+
+HRESULT WindowImpl::SetDecorations(SystemDecorations value) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        auto currentWindowState = _lastWindowState;
+        _decorations = value;
+
+        if (_fullScreenActive) {
+            return S_OK;
+        }
+
+        UpdateStyle();
+
+        HideOrShowTrafficLights();
+
+        switch (_decorations) {
+            case SystemDecorationsNone:
+                [Window setHasShadow:NO];
+                [Window setTitleVisibility:NSWindowTitleHidden];
+                [Window setTitlebarAppearsTransparent:YES];
+
+                if (currentWindowState == Maximized) {
+                    if (!UndecoratedIsMaximized()) {
+                        DoZoom();
+                    }
+                }
+                break;
+
+            case SystemDecorationsBorderOnly:
+                [Window setHasShadow:YES];
+                [Window setTitleVisibility:NSWindowTitleHidden];
+                [Window setTitlebarAppearsTransparent:YES];
+
+                if (currentWindowState == Maximized) {
+                    if (!UndecoratedIsMaximized()) {
+                        DoZoom();
+                    }
+                }
+                break;
+
+            case SystemDecorationsFull:
+                [Window setHasShadow:YES];
+                [Window setTitleVisibility:NSWindowTitleVisible];
+                [Window setTitlebarAppearsTransparent:NO];
+                [Window setTitle:_lastTitle];
+
+                if (currentWindowState == Maximized) {
+                    auto newFrame = [Window contentRectForFrameRect:[Window frame]].size;
+
+                    [View setFrameSize:newFrame];
+                }
+                break;
+        }
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowImpl::SetTitle(char *utf8title) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        _lastTitle = [NSString stringWithUTF8String:(const char *) utf8title];
+        [Window setTitle:_lastTitle];
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowImpl::SetTitleBarColor(AvnColor color) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        float a = (float) color.Alpha / 255.0f;
+        float r = (float) color.Red / 255.0f;
+        float g = (float) color.Green / 255.0f;
+        float b = (float) color.Blue / 255.0f;
+
+        auto nscolor = [NSColor colorWithSRGBRed:r green:g blue:b alpha:a];
+
+        // Based on the titlebar color we have to choose either light or dark
+        // OSX doesnt let you set a foreground color for titlebar.
+        if ((r * 0.299 + g * 0.587 + b * 0.114) > 186.0f / 255.0f) {
+            [Window setAppearance:[NSAppearance appearanceNamed:NSAppearanceNameVibrantLight]];
+        } else {
+            [Window setAppearance:[NSAppearance appearanceNamed:NSAppearanceNameVibrantDark]];
+        }
+
+        [Window setTitlebarAppearsTransparent:true];
+        [Window setBackgroundColor:nscolor];
+    }
+
+    return S_OK;
+}
+
+HRESULT WindowImpl::GetWindowState(AvnWindowState *ret) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        if (ret == nullptr) {
+            return E_POINTER;
+        }
+
+        if (([Window styleMask] & NSWindowStyleMaskFullScreen) == NSWindowStyleMaskFullScreen) {
+            *ret = FullScreen;
+            return S_OK;
+        }
+
+        if ([Window isMiniaturized]) {
+            *ret = Minimized;
+            return S_OK;
+        }
+
+        if (IsZoomed()) {
+            *ret = Maximized;
+            return S_OK;
+        }
+
+        *ret = Normal;
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowImpl::TakeFocusFromChildren() {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        if (Window == nil)
+            return S_OK;
+        if ([Window isKeyWindow])
+            [Window makeFirstResponder:View];
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowImpl::SetExtendClientArea(bool enable) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        _isClientAreaExtended = enable;
+
+        if(Window != nullptr) {
+            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;
+            }
+
+            [GetWindowProtocol() setIsExtended:enable];
+
+            HideOrShowTrafficLights();
+
+            UpdateStyle();
+        }
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowImpl::SetExtendClientAreaHints(AvnExtendClientAreaChromeHints hints) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        _extendClientHints = hints;
+
+        SetExtendClientArea(_isClientAreaExtended);
+        return S_OK;
+    }
+}
+
+HRESULT WindowImpl::GetExtendTitleBarHeight(double *ret) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        if (ret == nullptr) {
+            return E_POINTER;
+        }
+
+        *ret = [GetWindowProtocol() getExtendedTitleBarHeight];
+
+        return S_OK;
+    }
+}
+
+HRESULT WindowImpl::SetExtendTitleBarHeight(double value) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        [StandardContainer SetTitleBarHeightHint:value];
+        return S_OK;
+    }
+}
+
+void WindowImpl::EnterFullScreenMode() {
+    _fullScreenActive = true;
+
+    [Window setTitle:_lastTitle];
+    [Window toggleFullScreen:nullptr];
+}
+
+void WindowImpl::ExitFullScreenMode() {
+    [Window toggleFullScreen:nullptr];
+
+    _fullScreenActive = false;
+
+    SetDecorations(_decorations);
+}
+
+HRESULT WindowImpl::SetWindowState(AvnWindowState state) {
+    START_COM_CALL;
+
+    @autoreleasepool {
+        auto currentState = _actualWindowState;
+        _lastWindowState = state;
+
+        if (Window == nullptr) {
+            return S_OK;
+        }
+
+        if (_actualWindowState == state) {
+            return S_OK;
+        }
+
+        _inSetWindowState = true;
+
+        if (currentState == Normal) {
+            _preZoomSize = [Window frame];
+        }
+
+        if (_shown) {
+            switch (state) {
+                case Maximized:
+                    if (currentState == FullScreen) {
+                        ExitFullScreenMode();
+                    }
+
+                    lastPositionSet.X = 0;
+                    lastPositionSet.Y = 0;
+
+                    if ([Window isMiniaturized]) {
+                        [Window deminiaturize:Window];
+                    }
+
+                    if (!IsZoomed()) {
+                        DoZoom();
+                    }
+                    break;
+
+                case Minimized:
+                    if (currentState == FullScreen) {
+                        ExitFullScreenMode();
+                    } else {
+                        [Window miniaturize:Window];
+                    }
+                    break;
+
+                case FullScreen:
+                    if ([Window isMiniaturized]) {
+                        [Window deminiaturize:Window];
+                    }
+
+                    EnterFullScreenMode();
+                    break;
+
+                case Normal:
+                    if ([Window isMiniaturized]) {
+                        [Window deminiaturize:Window];
+                    }
+
+                    if (currentState == FullScreen) {
+                        ExitFullScreenMode();
+                    }
+
+                    if (IsZoomed()) {
+                        if (_decorations == SystemDecorationsFull) {
+                            DoZoom();
+                        } else {
+                            [Window setFrame:_preZoomSize display:true];
+                            auto newFrame = [Window contentRectForFrameRect:[Window frame]].size;
+
+                            [View setFrameSize:newFrame];
+                        }
+
+                    }
+                    break;
+            }
+
+            _actualWindowState = _lastWindowState;
+            WindowEvents->WindowStateChanged(_actualWindowState);
+        }
+
+
+        _inSetWindowState = false;
+
+        return S_OK;
+    }
+}
+
+bool WindowImpl::IsDialog() {
+    return _isDialog;
+}
+
+NSWindowStyleMask WindowImpl::GetStyle() {
+    unsigned long s = this->_isDialog ? NSWindowStyleMaskDocModalWindow : NSWindowStyleMaskBorderless;
+
+    switch (_decorations) {
+        case SystemDecorationsNone:
+            s = s | NSWindowStyleMaskFullSizeContentView;
+            break;
+
+        case SystemDecorationsBorderOnly:
+            s = s | NSWindowStyleMaskTitled | NSWindowStyleMaskFullSizeContentView;
+            break;
+
+        case SystemDecorationsFull:
+            s = s | NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskBorderless;
+
+            if (_canResize) {
+                s = s | NSWindowStyleMaskResizable;
+            }
+            break;
+    }
+
+    if ([Window parentWindow] == nullptr) {
+        s |= NSWindowStyleMaskMiniaturizable;
+    }
+
+    if (_isClientAreaExtended) {
+        s |= NSWindowStyleMaskFullSizeContentView | NSWindowStyleMaskTexturedBackground;
+    }
+    return s;
+}

+ 17 - 0
native/Avalonia.Native/src/OSX/WindowInterfaces.h

@@ -0,0 +1,17 @@
+//
+// Created by Dan Walmsley on 06/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+#import <AppKit/AppKit.h>
+#include "WindowProtocol.h"
+#include "WindowBaseImpl.h"
+
+@interface AvnWindow : NSWindow <AvnWindowProtocol, NSWindowDelegate>
+-(AvnWindow* _Nonnull) initWithParent: (WindowBaseImpl* _Nonnull) parent contentRect: (NSRect)contentRect styleMask: (NSWindowStyleMask)styleMask;
+@end
+
+@interface AvnPanel : NSPanel <AvnWindowProtocol, NSWindowDelegate>
+-(AvnPanel* _Nonnull) initWithParent: (WindowBaseImpl* _Nonnull) parent contentRect: (NSRect)contentRect styleMask: (NSWindowStyleMask)styleMask;
+@end

+ 27 - 0
native/Avalonia.Native/src/OSX/WindowProtocol.h

@@ -0,0 +1,27 @@
+//
+// Created by Dan Walmsley on 06/05/2022.
+// Copyright (c) 2022 Avalonia. All rights reserved.
+//
+
+#pragma once
+
+#import <AppKit/AppKit.h>
+
+@class AvnMenu;
+
+@protocol AvnWindowProtocol
+-(void) pollModalSession: (NSModalSession _Nonnull) session;
+-(void) restoreParentWindow;
+-(bool) shouldTryToHandleEvents;
+-(void) setEnabled: (bool) enable;
+-(void) showAppMenuOnly;
+-(void) showWindowMenuWithAppMenu;
+-(void) applyMenu:(AvnMenu* _Nullable)menu;
+
+-(double) getExtendedTitleBarHeight;
+-(void) setIsExtended:(bool)value;
+-(void) disconnectParent;
+-(bool) isDialog;
+
+-(void) setCanBecomeKeyWindow:(bool)value;
+@end

+ 0 - 12
native/Avalonia.Native/src/OSX/app.mm

@@ -82,18 +82,6 @@ ComPtr<IAvnApplicationEvents> _events;
         _isHandlingSendEvent = oldHandling;
     }
 }
-
-// This is needed for certain embedded controls
-- (BOOL) isHandlingSendEvent
-{
-    return _isHandlingSendEvent;
-}
-
-- (void)setHandlingSendEvent:(BOOL)handlingSendEvent
-{
-    _isHandlingSendEvent = handlingSendEvent;
-}
-
 @end
 
 extern void InitializeAvnApp(IAvnApplicationEvents* events)

+ 2 - 2
native/Avalonia.Native/src/OSX/automation.h

@@ -1,6 +1,6 @@
-#import <Cocoa/Cocoa.h>
-#include "window.h"
+#pragma once
 
+#import <Cocoa/Cocoa.h>
 NS_ASSUME_NONNULL_BEGIN
 
 class IAvnAutomationPeer;

+ 2 - 1
native/Avalonia.Native/src/OSX/automation.mm

@@ -1,7 +1,8 @@
 #include "common.h"
 #include "automation.h"
 #include "AvnString.h"
-#include "window.h"
+#include "INSWindowHolder.h"
+#include "AvnView.h"
 
 @interface AvnAccessibilityElement (Events)
 - (void) raiseChildrenChanged;

+ 1 - 2
native/Avalonia.Native/src/OSX/common.h

@@ -27,7 +27,7 @@ extern IAvnMenuItem* CreateAppMenuItem();
 extern IAvnMenuItem* CreateAppMenuItemSeparator();
 extern IAvnApplicationCommands* CreateApplicationCommands();
 extern IAvnNativeControlHost* CreateNativeControlHost(NSView* parent);
-extern void SetAppMenu (NSString* appName, IAvnMenu* appMenu);
+extern void SetAppMenu(IAvnMenu *menu);
 extern void SetServicesMenu (IAvnMenu* menu);
 extern IAvnMenu* GetAppMenu ();
 extern NSMenuItem* GetAppMenuItem ();
@@ -38,7 +38,6 @@ extern NSPoint ToNSPoint (AvnPoint p);
 extern NSRect ToNSRect (AvnRect r);
 extern AvnPoint ToAvnPoint (NSPoint p);
 extern AvnPoint ConvertPointY (AvnPoint p);
-extern CGFloat PrimaryDisplayHeight();
 extern NSSize ToNSSize (AvnSize s);
 #ifdef DEBUG
 #define NSDebugLog(...) NSLog(__VA_ARGS__)

+ 0 - 1
native/Avalonia.Native/src/OSX/cursor.mm

@@ -1,6 +1,5 @@
 #include "common.h"
 #include "cursor.h"
-#include <map>
 
 class CursorFactory : public ComSingleObject<IAvnCursorFactory, &IID_IAvnCursorFactory>
 {

+ 1 - 6
native/Avalonia.Native/src/OSX/main.mm

@@ -1,7 +1,6 @@
 //This file will contain actual IID structures
 #define COM_GUIDS_MATERIALIZE
 #include "common.h"
-#include "window.h"
 
 static NSString* s_appTitle = @"Avalonia";
 
@@ -343,7 +342,7 @@ public:
         
         @autoreleasepool
         {
-            ::SetAppMenu(s_appTitle, appMenu);
+            ::SetAppMenu(appMenu);
             return S_OK;
         }
     }
@@ -428,7 +427,3 @@ AvnPoint ConvertPointY (AvnPoint p)
     return p;
 }
 
-CGFloat PrimaryDisplayHeight()
-{
-  return NSMaxY([[[NSScreen screens] firstObject] frame]);
-}

+ 0 - 1
native/Avalonia.Native/src/OSX/menu.h

@@ -31,7 +31,6 @@ private:
     NSMenuItem* _native; // here we hold a pointer to an AvnMenuItem
     IAvnActionCallback* _callback;
     IAvnPredicateCallback* _predicate;
-    bool _isSeparator;
     bool _isCheckable;
     
 public:

+ 2 - 4
native/Avalonia.Native/src/OSX/menu.mm

@@ -1,7 +1,6 @@
 
 #include "common.h"
 #include "menu.h"
-#include "window.h"
 #include "KeyTransform.h"
 #include <CoreFoundation/CoreFoundation.h>
 #include <Carbon/Carbon.h> /* For kVK_ constants, and TIS functions. */
@@ -74,8 +73,7 @@
 AvnAppMenuItem::AvnAppMenuItem(bool isSeparator)
 {
     _isCheckable = false;
-    _isSeparator = isSeparator;
-    
+
     if(isSeparator)
     {
         _native = [NSMenuItem separatorItem];
@@ -460,7 +458,7 @@ extern IAvnMenuItem* CreateAppMenuItemSeparator()
 static IAvnMenu* s_appMenu = nullptr;
 static NSMenuItem* s_appMenuItem = nullptr;
 
-extern void SetAppMenu (NSString* appName, IAvnMenu* menu)
+extern void SetAppMenu(IAvnMenu *menu)
 {
     s_appMenu = menu;
     

+ 0 - 4
native/Avalonia.Native/src/OSX/rendertarget.mm

@@ -1,14 +1,10 @@
 #include "common.h"
 #include "rendertarget.h"
-#import <IOSurface/IOSurface.h>
 #import <IOSurface/IOSurfaceObjC.h>
 #import <QuartzCore/QuartzCore.h>
 
-#include <OpenGL/CGLIOSurface.h>
-#include <OpenGL/OpenGL.h>
 #include <OpenGL/glext.h>
 #include <OpenGL/gl3.h>
-#include <OpenGL/gl3ext.h>
 
 @interface IOSurfaceHolder : NSObject
 @end

+ 0 - 77
native/Avalonia.Native/src/OSX/window.h

@@ -1,77 +0,0 @@
-#ifndef window_h
-#define window_h
-
-class WindowBaseImpl;
-
-@interface AvnView : NSView<NSTextInputClient, NSDraggingDestination>
--(AvnView* _Nonnull) initWithParent: (WindowBaseImpl* _Nonnull) parent;
--(NSEvent* _Nonnull) lastMouseDownEvent;
--(AvnPoint) translateLocalPoint:(AvnPoint)pt;
--(void) setSwRenderedFrame: (AvnFramebuffer* _Nonnull) fb dispose: (IUnknown* _Nonnull) dispose;
--(void) onClosed;
--(AvnPixelSize) getPixelSize;
--(AvnPlatformResizeReason) getResizeReason;
--(void) setResizeReason:(AvnPlatformResizeReason)reason;
-+ (AvnPoint)toAvnPoint:(CGPoint)p;
-@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;
--(void) setCanBecomeKeyAndMain;
--(void) pollModalSession: (NSModalSession _Nonnull) session;
--(void) restoreParentWindow;
--(bool) shouldTryToHandleEvents;
--(void) setEnabled: (bool) enable;
--(void) showAppMenuOnly;
--(void) showWindowMenuWithAppMenu;
--(void) applyMenu:(NSMenu* _Nullable)menu;
--(double) getScaling;
--(double) getExtendedTitleBarHeight;
--(void) setIsExtended:(bool)value;
--(bool) isDialog;
-@end
-
-struct INSWindowHolder
-{
-    virtual AvnWindow* _Nonnull GetNSWindow () = 0;
-    virtual AvnView* _Nonnull GetNSView () = 0;
-};
-
-struct IWindowStateChanged
-{
-    virtual void WindowStateChanged () = 0;
-    virtual void StartStateTransition () = 0;
-    virtual void EndStateTransition () = 0;
-    virtual SystemDecorations Decorations () = 0;
-    virtual AvnWindowState WindowState () = 0;
-};
-
-class ResizeScope
-{
-public:
-    ResizeScope(AvnView* _Nonnull view, AvnPlatformResizeReason reason)
-    {
-        _view = view;
-        _restore = [view getResizeReason];
-        [view setResizeReason:reason];
-    }
-    
-    ~ResizeScope()
-    {
-        [_view setResizeReason:_restore];
-    }
-private:
-    AvnView* _Nonnull _view;
-    AvnPlatformResizeReason _restore;
-};
-
-#endif /* window_h */

+ 0 - 2590
native/Avalonia.Native/src/OSX/window.mm

@@ -1,2590 +0,0 @@
-#include "common.h"
-#include "window.h"
-#include "KeyTransform.h"
-#include "cursor.h"
-#include "menu.h"
-#include <OpenGL/gl.h>
-#include "rendertarget.h"
-#include "AvnString.h"
-#include "automation.h"
-
-class WindowBaseImpl : public virtual ComObject,
-    public virtual IAvnWindowBase,
-    public INSWindowHolder
-{
-private:
-    NSCursor* cursor;
-
-public:
-    FORWARD_IUNKNOWN()
-    BEGIN_INTERFACE_MAP()
-    INTERFACE_MAP_ENTRY(IAvnWindowBase, IID_IAvnWindowBase)
-    END_INTERFACE_MAP()
-
-    virtual ~WindowBaseImpl()
-    {
-        View = NULL;
-        Window = NULL;
-    }
-    AutoFitContentView* StandardContainer;
-    AvnView* View;
-    AvnWindow* Window;
-    ComPtr<IAvnWindowBaseEvents> BaseEvents;
-    ComPtr<IAvnGlContext> _glContext;
-    NSObject<IRenderTarget>* renderTarget;
-    AvnPoint lastPositionSet;
-    NSString* _lastTitle;
-    IAvnMenu* _mainMenu;
-    
-    bool _shown;
-    bool _inResize;
-    
-    WindowBaseImpl(IAvnWindowBaseEvents* events, IAvnGlContext* gl)
-    {
-        _shown = false;
-        _inResize = false;
-        _mainMenu = nullptr;
-        BaseEvents = events;
-        _glContext = gl;
-        renderTarget = [[IOSurfaceRenderTarget alloc] initWithOpenGlContext: gl];
-        View = [[AvnView alloc] initWithParent:this];
-        StandardContainer = [[AutoFitContentView new] initWithContent:View];
-
-        Window = [[AvnWindow alloc] initWithParent:this];
-        [Window setContentView: StandardContainer];
-        
-        lastPositionSet.X = 100;
-        lastPositionSet.Y = 100;
-        _lastTitle = @"";
-        
-        [Window setStyleMask:NSWindowStyleMaskBorderless];
-        [Window setBackingType:NSBackingStoreBuffered];
-        
-        [Window setOpaque:false];
-    }
-    
-    virtual HRESULT ObtainNSWindowHandle(void** ret) override
-    {
-        START_COM_CALL;
-        
-        if (ret == nullptr)
-        {
-            return E_POINTER;
-        }
-        
-        *ret =  (__bridge void*)Window;
-        
-        return S_OK;
-    }
-    
-    virtual HRESULT ObtainNSWindowHandleRetained(void** ret) override
-    {
-        START_COM_CALL;
-        
-        if (ret == nullptr)
-        {
-            return E_POINTER;
-        }
-        
-        *ret =  (__bridge_retained void*)Window;
-        
-        return S_OK;
-    }
-    
-    virtual HRESULT ObtainNSViewHandle(void** ret) override
-    {
-        START_COM_CALL;
-        
-        if (ret == nullptr)
-        {
-            return E_POINTER;
-        }
-        
-        *ret =  (__bridge void*)View;
-        
-        return S_OK;
-    }
-    
-    virtual HRESULT ObtainNSViewHandleRetained(void** ret) override
-    {
-        START_COM_CALL;
-        
-        if (ret == nullptr)
-        {
-            return E_POINTER;
-        }
-        
-        *ret =  (__bridge_retained void*)View;
-        
-        return S_OK;
-    }
-    
-    virtual AvnWindow* GetNSWindow() override
-    {
-        return Window;
-    }
-
-    virtual AvnView* GetNSView() override
-    {
-        return View;
-    }
-
-    virtual HRESULT Show(bool activate, bool isDialog) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            SetPosition(lastPositionSet);
-            UpdateStyle();
-            
-            [Window setTitle:_lastTitle];
-            
-            if(ShouldTakeFocusOnShow() && activate)
-            {
-                [Window orderFront: Window];
-                [Window makeKeyAndOrderFront:Window];
-                [Window makeFirstResponder:View];
-                [NSApp activateIgnoringOtherApps:YES];
-            }
-            else
-            {
-                [Window orderFront: Window];
-            }
-            
-            _shown = true;
-            
-            return S_OK;
-        }
-    }
-    
-    virtual bool ShouldTakeFocusOnShow()
-    {
-        return true;
-    }
-    
-    virtual HRESULT Hide () override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if(Window != nullptr)
-            {
-                [Window orderOut:Window];
-                [Window restoreParentWindow];
-            }
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT Activate () override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if(Window != nullptr)
-            {
-                [Window makeKeyAndOrderFront:nil];
-                [NSApp activateIgnoringOtherApps:YES];
-            }
-        }
-        
-        return S_OK;
-    }
-    
-    virtual HRESULT SetTopMost (bool value) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            [Window setLevel: value ? NSFloatingWindowLevel : NSNormalWindowLevel];
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT Close() override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if (Window != nullptr)
-            {
-                auto window = Window;
-                Window = nullptr;
-                
-                try{
-                    // Seems to throw sometimes on application exit.
-                    [window close];
-                }
-                catch(NSException*){}
-            }
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT GetClientSize(AvnSize* ret) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if(ret == nullptr)
-                return E_POINTER;
-            
-            auto frame = [View frame];
-            ret->Width = frame.size.width;
-            ret->Height = frame.size.height;
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT GetFrameSize(AvnSize* ret) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if(ret == nullptr)
-                return E_POINTER;
-            
-            auto frame = [Window frame];
-            ret->Width = frame.size.width;
-            ret->Height = frame.size.height;
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT GetScaling (double* ret) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if(ret == nullptr)
-                return E_POINTER;
-            
-            if(Window == nullptr)
-            {
-                *ret = 1;
-                return S_OK;
-            }
-            
-            *ret = [Window backingScaleFactor];
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT SetMinMaxSize (AvnSize minSize, AvnSize maxSize) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            [Window setMinSize: ToNSSize(minSize)];
-            [Window setMaxSize: ToNSSize(maxSize)];
-        
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT Resize(double x, double y, AvnPlatformResizeReason reason) override
-    {
-        if(_inResize)
-        {
-            return S_OK;
-        }
-        
-        _inResize = true;
-        
-        START_COM_CALL;
-        auto resizeBlock = ResizeScope(View, reason);
-        
-        @autoreleasepool
-        {
-            auto maxSize = [Window maxSize];
-            auto minSize = [Window minSize];
-            
-            if (x < minSize.width)
-            {
-                x = minSize.width;
-            }
-            
-            if (y < minSize.height)
-            {
-                y = minSize.height;
-            }
-            
-            if (x > maxSize.width)
-            {
-                x = maxSize.width;
-            }
-            
-            if (y > maxSize.height)
-            {
-                y = maxSize.height;
-            }
-            
-            @try
-            {
-                if(!_shown)
-                {
-                    BaseEvents->Resized(AvnSize{x,y}, reason);
-                }
-                
-                [Window setContentSize:NSSize{x,y}];
-                [Window invalidateShadow];
-            }
-            @finally
-            {
-                _inResize = false;
-            }
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT Invalidate (AvnRect rect) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            [View setNeedsDisplayInRect:[View frame]];
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT SetMainMenu(IAvnMenu* menu) override
-    {
-        START_COM_CALL;
-        
-        _mainMenu = menu;
-        
-        auto nativeMenu = dynamic_cast<AvnAppMenu*>(menu);
-        
-        auto nsmenu = nativeMenu->GetNative();
-        
-        [Window applyMenu:nsmenu];
-        
-        if ([Window isKeyWindow])
-        {
-            [Window showWindowMenuWithAppMenu];
-        }
-        
-        return S_OK;
-    }
-    
-    virtual HRESULT BeginMoveDrag () override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            auto lastEvent = [View lastMouseDownEvent];
-            
-            if(lastEvent == nullptr)
-            {
-                return S_OK;
-            }
-            
-            [Window performWindowDragWithEvent:lastEvent];
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT BeginResizeDrag (AvnWindowEdge edge) override
-    {
-        START_COM_CALL;
-        
-        return S_OK;
-    }
-    
-    virtual HRESULT GetPosition (AvnPoint* ret) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if(ret == nullptr)
-            {
-                return E_POINTER;
-            }
-            
-            auto frame = [Window frame];
-            
-            ret->X = frame.origin.x;
-            ret->Y = frame.origin.y + frame.size.height;
-            
-            *ret = ConvertPointY(*ret);
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT SetPosition (AvnPoint point) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            lastPositionSet = point;
-            [Window setFrameTopLeftPoint:ToNSPoint(ConvertPointY(point))];
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT PointToClient (AvnPoint point, AvnPoint* ret) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if(ret == nullptr)
-            {
-                return E_POINTER;
-            }
-            
-            point = ConvertPointY(point);
-            NSRect convertRect = [Window convertRectFromScreen:NSMakeRect(point.X, point.Y, 0.0, 0.0)];
-            auto viewPoint = NSMakePoint(convertRect.origin.x, convertRect.origin.y);
-            
-            *ret = [View translateLocalPoint:ToAvnPoint(viewPoint)];
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT PointToScreen (AvnPoint point, AvnPoint* ret) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if(ret == nullptr)
-            {
-                return E_POINTER;
-            }
-            
-            auto cocoaViewPoint =  ToNSPoint([View translateLocalPoint:point]);
-            NSRect convertRect = [Window convertRectToScreen:NSMakeRect(cocoaViewPoint.x, cocoaViewPoint.y, 0.0, 0.0)];
-            auto cocoaScreenPoint = NSPointFromCGPoint(NSMakePoint(convertRect.origin.x, convertRect.origin.y));
-            *ret = ConvertPointY(ToAvnPoint(cocoaScreenPoint));
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT ThreadSafeSetSwRenderedFrame(AvnFramebuffer* fb, IUnknown* dispose) override
-    {
-        START_COM_CALL;
-        
-        [View setSwRenderedFrame: fb dispose: dispose];
-        return S_OK;
-    }
-    
-    virtual HRESULT SetCursor(IAvnCursor* cursor) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            Cursor* avnCursor = dynamic_cast<Cursor*>(cursor);
-            this->cursor = avnCursor->GetNative();
-            UpdateCursor();
-            
-            if(avnCursor->IsHidden())
-            {
-                [NSCursor hide];
-            }
-            else
-            {
-                [NSCursor unhide];
-            }
-            
-            return S_OK;
-        }
-    }
-
-    virtual void UpdateCursor()
-    {
-        if (cursor != nil)
-        {
-            [cursor set];
-        }
-    }
-    
-    virtual HRESULT CreateGlRenderTarget(IAvnGlSurfaceRenderTarget** ppv) override
-    {
-        START_COM_CALL;
-        
-        if(View == NULL)
-            return E_FAIL;
-        *ppv = [renderTarget createSurfaceRenderTarget];
-        return *ppv == nil ? E_FAIL : S_OK;
-    }
-    
-    virtual HRESULT CreateNativeControlHost(IAvnNativeControlHost** retOut) override
-    {
-        START_COM_CALL;
-        
-        if(View == NULL)
-            return E_FAIL;
-        *retOut = ::CreateNativeControlHost(View);
-        return S_OK;
-    }
-    
-    virtual HRESULT SetBlurEnabled (bool enable) override
-    {
-        START_COM_CALL;
-        
-        [StandardContainer ShowBlur:enable];
-        
-        return S_OK;
-    }
-    
-    virtual HRESULT BeginDragAndDropOperation(AvnDragDropEffects effects, AvnPoint point,
-                                              IAvnClipboard* clipboard, IAvnDndResultCallback* cb,
-                                              void* sourceHandle) override
-    {
-        START_COM_CALL;
-        
-        auto item = TryGetPasteboardItem(clipboard);
-        [item setString:@"" forType:GetAvnCustomDataType()];
-        if(item == nil)
-            return E_INVALIDARG;
-        if(View == NULL)
-            return E_FAIL;
-        
-        auto nsevent = [NSApp currentEvent];
-        auto nseventType = [nsevent type];
-        
-        // If current event isn't a mouse one (probably due to malfunctioning user app)
-        // attempt to forge a new one
-        if(!((nseventType >= NSEventTypeLeftMouseDown && nseventType <= NSEventTypeMouseExited)
-           || (nseventType >= NSEventTypeOtherMouseDown && nseventType <= NSEventTypeOtherMouseDragged)))
-        {
-            NSRect convertRect = [Window convertRectToScreen:NSMakeRect(point.X, point.Y, 0.0, 0.0)];
-            auto nspoint = NSMakePoint(convertRect.origin.x, convertRect.origin.y);            
-            CGPoint cgpoint = NSPointToCGPoint(nspoint);
-            auto cgevent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, cgpoint, kCGMouseButtonLeft);
-            nsevent = [NSEvent eventWithCGEvent: cgevent];
-            CFRelease(cgevent);
-        }
-        
-        auto dragItem = [[NSDraggingItem alloc] initWithPasteboardWriter: item];
-        
-        auto dragItemImage = [NSImage imageNamed:NSImageNameMultipleDocuments];
-        NSRect dragItemRect = {(float)point.X, (float)point.Y, [dragItemImage size].width, [dragItemImage size].height};
-        [dragItem setDraggingFrame: dragItemRect contents: dragItemImage];
-        
-        int op = 0; int ieffects = (int)effects;
-        if((ieffects & (int)AvnDragDropEffects::Copy) != 0)
-            op |= NSDragOperationCopy;
-        if((ieffects & (int)AvnDragDropEffects::Link) != 0)
-            op |= NSDragOperationLink;
-        if((ieffects & (int)AvnDragDropEffects::Move) != 0)
-            op |= NSDragOperationMove;
-        [View beginDraggingSessionWithItems: @[dragItem] event: nsevent
-                                     source: CreateDraggingSource((NSDragOperation) op, cb, sourceHandle)];
-        return S_OK;
-    }
-
-    virtual bool IsDialog()
-    {
-        return false;
-    }
-    
-protected:
-    virtual NSWindowStyleMask GetStyle()
-    {
-        return NSWindowStyleMaskBorderless;
-    }
-    
-    void UpdateStyle()
-    {
-        [Window setStyleMask: GetStyle()];
-    }
-    
-public:
-    virtual void OnResized ()
-    {
-        
-    }
-};
-
-class WindowImpl : public virtual WindowBaseImpl, public virtual IAvnWindow, public IWindowStateChanged
-{
-private:
-    bool _canResize;
-    bool _fullScreenActive;
-    SystemDecorations _decorations;
-    AvnWindowState _lastWindowState;
-    AvnWindowState _actualWindowState;
-    bool _inSetWindowState;
-    NSRect _preZoomSize;
-    bool _transitioningWindowState;
-    bool _isClientAreaExtended;
-    bool _isDialog;
-    AvnExtendClientAreaChromeHints _extendClientHints;
-    
-    FORWARD_IUNKNOWN()
-    BEGIN_INTERFACE_MAP()
-    INHERIT_INTERFACE_MAP(WindowBaseImpl)
-    INTERFACE_MAP_ENTRY(IAvnWindow, IID_IAvnWindow)
-    END_INTERFACE_MAP()
-    virtual ~WindowImpl()
-    {
-    }
-    
-    ComPtr<IAvnWindowEvents> WindowEvents;
-    WindowImpl(IAvnWindowEvents* events, IAvnGlContext* gl) : WindowBaseImpl(events, gl)
-    {
-        _isClientAreaExtended = false;
-        _extendClientHints = AvnDefaultChrome;
-        _fullScreenActive = false;
-        _canResize = true;
-        _decorations = SystemDecorationsFull;
-        _transitioningWindowState = false;
-        _inSetWindowState = false;
-        _lastWindowState = Normal;
-        _actualWindowState = Normal;
-        WindowEvents = events;
-        [Window setCanBecomeKeyAndMain];
-        [Window disableCursorRects];
-        [Window setTabbingMode:NSWindowTabbingModeDisallowed];
-        [Window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
-    }
-    
-    void HideOrShowTrafficLights ()
-    {
-        if (Window == nil)
-        {
-            return;
-        }
-        
-        for (id subview in Window.contentView.superview.subviews) {
-            if ([subview isKindOfClass:NSClassFromString(@"NSTitlebarContainerView")]) {
-                NSView *titlebarView = [subview subviews][0];
-                for (id button in titlebarView.subviews) {
-                    if ([button isKindOfClass:[NSButton class]])
-                    {
-                        if(_isClientAreaExtended)
-                        {
-                            auto wantsChrome = (_extendClientHints & AvnSystemChrome) || (_extendClientHints & AvnPreferSystemChrome);
-                            
-                            [button setHidden: !wantsChrome];
-                        }
-                        else
-                        {
-                            [button setHidden: (_decorations != SystemDecorationsFull)];
-                        }
-                        
-                        [button setWantsLayer:true];
-                    }
-                }
-            }
-        }
-    }
-    
-    virtual HRESULT Show (bool activate, bool isDialog) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            _isDialog = isDialog;
-            WindowBaseImpl::Show(activate, isDialog);
-            
-            HideOrShowTrafficLights();
-            
-            return SetWindowState(_lastWindowState);
-        }
-    }
-    
-    virtual HRESULT SetEnabled (bool enable) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            [Window setEnabled:enable];
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT SetParent (IAvnWindow* parent) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if(parent == nullptr)
-                return E_POINTER;
-
-            auto cparent = dynamic_cast<WindowImpl*>(parent);
-            if(cparent == nullptr)
-                return E_INVALIDARG;
-            
-            // If one tries to show a child window with a minimized parent window, then the parent window will be
-            // restored but macOS isn't kind enough to *tell* us that, so the window will be left in a non-interactive
-            // state. Detect this and explicitly restore the parent window ourselves to avoid this situation.
-            if (cparent->WindowState() == Minimized)
-                cparent->SetWindowState(Normal);
-            
-            [Window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
-            [cparent->Window addChildWindow:Window ordered:NSWindowAbove];
-            
-            UpdateStyle();
-            
-            return S_OK;
-        }
-    }
-    
-    void StartStateTransition () override
-    {
-        _transitioningWindowState = true;
-    }
-    
-    void EndStateTransition () override
-    {
-        _transitioningWindowState = false;
-    }
-    
-    SystemDecorations Decorations () override
-    {
-        return _decorations;
-    }
-    
-    AvnWindowState WindowState () override
-    {
-        return _lastWindowState;
-    }
-    
-    void WindowStateChanged () override
-    {
-        if(_shown && !_inSetWindowState && !_transitioningWindowState)
-        {
-            AvnWindowState state;
-            GetWindowState(&state);
-            
-            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;
-                _actualWindowState = state;
-                WindowEvents->WindowStateChanged(state);
-            }
-        }
-    }
-    
-    bool UndecoratedIsMaximized ()
-    {
-        auto windowSize = [Window frame];
-        auto available = [Window screen].visibleFrame;
-        return CGRectEqualToRect(windowSize, available);
-    }
-    
-    bool IsZoomed ()
-    {
-        return _decorations == SystemDecorationsFull ? [Window isZoomed] : UndecoratedIsMaximized();
-    }
-    
-    void DoZoom()
-    {
-        switch (_decorations)
-        {
-            case SystemDecorationsNone:
-            case SystemDecorationsBorderOnly:
-                [Window setFrame:[Window screen].visibleFrame display:true];
-                break;
-
-            
-            case SystemDecorationsFull:
-                [Window performZoom:Window];
-                break;
-        }
-    }
-    
-    virtual HRESULT SetCanResize(bool value) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            _canResize = value;
-            UpdateStyle();
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT SetDecorations(SystemDecorations value) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            auto currentWindowState = _lastWindowState;
-            _decorations = value;
-            
-            if(_fullScreenActive)
-            {
-                return S_OK;
-            }
-            
-            UpdateStyle();
-            
-            HideOrShowTrafficLights();
-
-            switch (_decorations)
-            {
-                case SystemDecorationsNone:
-                    [Window setHasShadow:NO];
-                    [Window setTitleVisibility:NSWindowTitleHidden];
-                    [Window setTitlebarAppearsTransparent:YES];
-                    
-                    if(currentWindowState == Maximized)
-                    {
-                        if(!UndecoratedIsMaximized())
-                        {
-                            DoZoom();
-                        }
-                    }
-                    break;
-
-                case SystemDecorationsBorderOnly:
-                    [Window setHasShadow:YES];
-                    [Window setTitleVisibility:NSWindowTitleHidden];
-                    [Window setTitlebarAppearsTransparent:YES];
-                    
-                    if(currentWindowState == Maximized)
-                    {
-                        if(!UndecoratedIsMaximized())
-                        {
-                            DoZoom();
-                        }
-                    }
-                    break;
-
-                case SystemDecorationsFull:
-                    [Window setHasShadow:YES];
-                    [Window setTitleVisibility:NSWindowTitleVisible];
-                    [Window setTitlebarAppearsTransparent:NO];
-                    [Window setTitle:_lastTitle];
-                    
-                    if(currentWindowState == Maximized)
-                    {
-                        auto newFrame = [Window contentRectForFrameRect:[Window frame]].size;
-                        
-                        [View setFrameSize:newFrame];
-                    }
-                    break;
-            }
-
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT SetTitle (char* utf8title) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            _lastTitle = [NSString stringWithUTF8String:(const char*)utf8title];
-            [Window setTitle:_lastTitle];
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT SetTitleBarColor(AvnColor color) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            float a = (float)color.Alpha / 255.0f;
-            float r = (float)color.Red / 255.0f;
-            float g = (float)color.Green / 255.0f;
-            float b = (float)color.Blue / 255.0f;
-            
-            auto nscolor = [NSColor colorWithSRGBRed:r green:g blue:b alpha:a];
-            
-            // Based on the titlebar color we have to choose either light or dark
-            // OSX doesnt let you set a foreground color for titlebar.
-            if ((r*0.299 + g*0.587 + b*0.114) > 186.0f / 255.0f)
-            {
-                [Window setAppearance:[NSAppearance appearanceNamed:NSAppearanceNameVibrantLight]];
-            }
-            else
-            {
-                [Window setAppearance:[NSAppearance appearanceNamed:NSAppearanceNameVibrantDark]];
-            }
-            
-            [Window setTitlebarAppearsTransparent:true];
-            [Window setBackgroundColor:nscolor];
-        }
-        
-        return S_OK;
-    }
-    
-    virtual HRESULT GetWindowState (AvnWindowState*ret) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if(ret == nullptr)
-            {
-                return E_POINTER;
-            }
-            
-            if(([Window styleMask] & NSWindowStyleMaskFullScreen) == NSWindowStyleMaskFullScreen)
-            {
-                *ret = FullScreen;
-                return S_OK;
-            }
-            
-            if([Window isMiniaturized])
-            {
-                *ret = Minimized;
-                return S_OK;
-            }
-            
-            if(IsZoomed())
-            {
-                *ret = Maximized;
-                return S_OK;
-            }
-            
-            *ret = Normal;
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT TakeFocusFromChildren () override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if(Window == nil)
-                return S_OK;
-            if([Window isKeyWindow])
-                [Window makeFirstResponder: View];
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT SetExtendClientArea (bool enable) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            _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
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            _extendClientHints = hints;
-            
-            SetExtendClientArea(_isClientAreaExtended);
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT GetExtendTitleBarHeight (double*ret) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if(ret == nullptr)
-            {
-                return E_POINTER;
-            }
-            
-            *ret = [Window getExtendedTitleBarHeight];
-            
-            return S_OK;
-        }
-    }
-    
-    virtual HRESULT SetExtendTitleBarHeight (double value) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            [StandardContainer SetTitleBarHeightHint:value];
-            return S_OK;
-        }
-    }
-    
-    void EnterFullScreenMode ()
-    {
-        _fullScreenActive = true;
-        
-        [Window setTitle:_lastTitle];
-        [Window toggleFullScreen:nullptr];
-    }
-    
-    void ExitFullScreenMode ()
-    {
-        [Window toggleFullScreen:nullptr];
-        
-        _fullScreenActive = false;
-        
-        SetDecorations(_decorations);
-    }
-    
-    virtual HRESULT SetWindowState (AvnWindowState state) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if(Window == nullptr)
-            {
-                return  S_OK;
-            }
-            
-            if(_actualWindowState == state)
-            {
-                return S_OK;
-            }
-            
-            _inSetWindowState = true;
-            
-            auto currentState = _actualWindowState;
-            _lastWindowState = state;
-            
-            if(currentState == Normal)
-            {
-                _preZoomSize = [Window frame];
-            }
-            
-            if(_shown)
-            {
-                switch (state) {
-                    case Maximized:
-                        if(currentState == FullScreen)
-                        {
-                            ExitFullScreenMode();
-                        }
-                        
-                        lastPositionSet.X = 0;
-                        lastPositionSet.Y = 0;
-                        
-                        if([Window isMiniaturized])
-                        {
-                            [Window deminiaturize:Window];
-                        }
-                        
-                        if(!IsZoomed())
-                        {
-                            DoZoom();
-                        }
-                        break;
-                        
-                    case Minimized:
-                        if(currentState == FullScreen)
-                        {
-                            ExitFullScreenMode();
-                        }
-                        else
-                        {
-                            [Window miniaturize:Window];
-                        }
-                        break;
-                        
-                    case FullScreen:
-                        if([Window isMiniaturized])
-                        {
-                            [Window deminiaturize:Window];
-                        }
-                        
-                        EnterFullScreenMode();
-                        break;
-                        
-                    case Normal:
-                        if([Window isMiniaturized])
-                        {
-                            [Window deminiaturize:Window];
-                        }
-                        
-                        if(currentState == FullScreen)
-                        {
-                            ExitFullScreenMode();
-                        }
-                        
-                        if(IsZoomed())
-                        {
-                            if(_decorations == SystemDecorationsFull)
-                            {
-                                DoZoom();
-                            }
-                            else
-                            {
-                                [Window setFrame:_preZoomSize display:true];
-                                auto newFrame = [Window contentRectForFrameRect:[Window frame]].size;
-                                
-                                [View setFrameSize:newFrame];
-                            }
-                            
-                        }
-                        break;
-                }
-                
-                _actualWindowState = _lastWindowState;
-                WindowEvents->WindowStateChanged(_actualWindowState);
-            }
-            
-            
-            _inSetWindowState = false;
-            
-            return S_OK;
-        }
-    }
-
-    virtual void OnResized () override
-    {
-        if(_shown && !_inSetWindowState && !_transitioningWindowState)
-        {
-            WindowStateChanged();
-        }
-    }
-    
-    virtual bool IsDialog() override
-    {
-        return _isDialog;
-    }
-    
-protected:
-    virtual NSWindowStyleMask GetStyle() override
-    {
-        unsigned long s = NSWindowStyleMaskBorderless;
-
-        switch (_decorations)
-        {
-            case SystemDecorationsNone:
-                s = s | NSWindowStyleMaskFullSizeContentView;
-                break;
-
-            case SystemDecorationsBorderOnly:
-                s = s | NSWindowStyleMaskTitled | NSWindowStyleMaskFullSizeContentView;
-                break;
-
-            case SystemDecorationsFull:
-                s = s | NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskBorderless;
-                
-                if(_canResize)
-                {
-                    s = s | NSWindowStyleMaskResizable;
-                }
-                break;
-        }
-
-        if([Window parentWindow] == nullptr)
-        {
-            s |= NSWindowStyleMaskMiniaturizable;
-        }
-        
-        if(_isClientAreaExtended)
-        {
-            s |= NSWindowStyleMaskFullSizeContentView | NSWindowStyleMaskTexturedBackground;
-        }
-        return s;
-    }
-};
-
-NSArray* AllLoopModes = [NSArray arrayWithObjects: NSDefaultRunLoopMode, NSEventTrackingRunLoopMode, NSModalPanelRunLoopMode, NSRunLoopCommonModes, NSConnectionReplyMode, nil];
-
-@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;
-    
-    [_blurBehind setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
-    [_content setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
-    
-    [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
-{
-    if(_settingSize)
-    {
-        return;
-    }
-    
-    _settingSize = true;
-    [super 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
-
-@implementation AvnView
-{
-    ComPtr<WindowBaseImpl> _parent;
-    ComPtr<IUnknown> _swRenderedFrame;
-    AvnFramebuffer _swRenderedFrameBuffer;
-    bool _queuedDisplayFromThread;
-    NSTrackingArea* _area;
-    bool _isLeftPressed, _isMiddlePressed, _isRightPressed, _isXButton1Pressed, _isXButton2Pressed, _isMouseOver;
-    AvnInputModifiers _modifierState;
-    NSEvent* _lastMouseDownEvent;
-    bool _lastKeyHandled;
-    AvnPixelSize _lastPixelSize;
-    NSObject<IRenderTarget>* _renderTarget;
-    AvnPlatformResizeReason _resizeReason;
-    AvnAccessibilityElement* _accessibilityChild;
-}
-
-- (void)onClosed
-{
-    @synchronized (self)
-    {
-        _parent = nullptr;
-    }
-}
-
--(AvnPixelSize) getPixelSize
-{
-    return _lastPixelSize;
-}
-
-- (NSEvent*) lastMouseDownEvent
-{
-    return _lastMouseDownEvent;
-}
-
-- (void) updateRenderTarget
-{
-    [_renderTarget resize:_lastPixelSize withScale: [[self window] backingScaleFactor]];
-    [self setNeedsDisplayInRect:[self frame]];
-}
-
--(AvnView*)  initWithParent: (WindowBaseImpl*) parent
-{
-    self = [super init];
-    _renderTarget = parent->renderTarget;
-    [self setWantsLayer:YES];
-    [self setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize];
-    
-    _parent = parent;
-    _area = nullptr;
-    _lastPixelSize.Height = 100;
-    _lastPixelSize.Width = 100;
-    [self registerForDraggedTypes: @[@"public.data", GetAvnCustomDataType()]];
-    
-    _modifierState = AvnInputModifiersNone;
-    return self;
-}
-
-- (BOOL)isFlipped
-{
-    return YES;
-}
-
-- (BOOL)wantsUpdateLayer
-{
-    return YES;
-}
-
-- (void)setLayer:(CALayer *)layer
-{
-    [_renderTarget setNewLayer: layer];
-    [super setLayer: layer];
-}
-
-- (BOOL)isOpaque
-{
-    return YES;
-}
-
-- (BOOL)acceptsFirstResponder
-{
-    return true;
-}
-
-- (BOOL)acceptsFirstMouse:(NSEvent *)event
-{
-    return true;
-}
-
-- (BOOL)canBecomeKeyView
-{
-    return true;
-}
-
--(void)setFrameSize:(NSSize)newSize
-{
-    [super setFrameSize:newSize];
-    
-    if(_area != nullptr)
-    {
-        [self removeTrackingArea:_area];
-        _area = nullptr;
-    }
-
-    if (_parent == nullptr)
-    {
-        return;
-    }
-
-    NSRect rect = NSZeroRect;
-    rect.size = newSize;
-    
-    NSTrackingAreaOptions options = NSTrackingActiveAlways | NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingEnabledDuringMouseDrag;
-    _area = [[NSTrackingArea alloc] initWithRect:rect options:options owner:self userInfo:nullptr];
-    [self addTrackingArea:_area];
-    
-    _parent->UpdateCursor();
-    
-    auto fsize = [self convertSizeToBacking: [self frame].size];
-    
-    if(_lastPixelSize.Width != (int)fsize.width || _lastPixelSize.Height != (int)fsize.height)
-    {
-        _lastPixelSize.Width = (int)fsize.width;
-        _lastPixelSize.Height = (int)fsize.height;
-        [self updateRenderTarget];
-    
-        auto reason = [self inLiveResize] ? ResizeUser : _resizeReason;
-        _parent->BaseEvents->Resized(AvnSize{newSize.width, newSize.height}, reason);
-    }
-}
-
-- (void)updateLayer
-{
-    AvnInsidePotentialDeadlock deadlock;
-    if (_parent == nullptr)
-    {
-        return;
-    }
-    
-    _parent->BaseEvents->RunRenderPriorityJobs();
-    
-    if (_parent == nullptr)
-    {
-        return;
-    }
-        
-    _parent->BaseEvents->Paint();
-}
-
-- (void)drawRect:(NSRect)dirtyRect
-{
-    return;
-}
-
--(void) setSwRenderedFrame: (AvnFramebuffer*) fb dispose: (IUnknown*) dispose
-{
-    @autoreleasepool {
-        [_renderTarget setSwFrame:fb];
-        dispose->Release();
-    }
-}
-
-- (AvnPoint) translateLocalPoint:(AvnPoint)pt
-{
-    pt.Y = [self bounds].size.height - pt.Y;
-    return pt;
-}
-
-+ (AvnPoint)toAvnPoint:(CGPoint)p
-{
-    AvnPoint result;
-    
-    result.X = p.x;
-    result.Y = p.y;
-    
-    return result;
-}
-
-- (void) viewDidChangeBackingProperties
-{
-    auto fsize = [self convertSizeToBacking: [self frame].size];
-    _lastPixelSize.Width = (int)fsize.width;
-    _lastPixelSize.Height = (int)fsize.height;
-    [self updateRenderTarget];
-    
-    if(_parent != nullptr)
-    {
-        _parent->BaseEvents->ScalingChanged([_parent->Window backingScaleFactor]);
-    }
-    
-    [super viewDidChangeBackingProperties];
-}
-
-- (bool) ignoreUserInput:(bool)trigerInputWhenDisabled
-{
-    auto parentWindow = objc_cast<AvnWindow>([self window]);
-    
-    if(parentWindow == nil || ![parentWindow shouldTryToHandleEvents])
-    {
-        if(trigerInputWhenDisabled)
-        {
-            auto window = dynamic_cast<WindowImpl*>(_parent.getRaw());
-            
-            if(window != nullptr)
-            {
-                window->WindowEvents->GotInputWhenDisabled();
-            }
-        }
-        
-        return TRUE;
-    }
-    
-    return FALSE;
-}
-
-- (void)mouseEvent:(NSEvent *)event withType:(AvnRawMouseEventType) type
-{
-    bool triggerInputWhenDisabled = type != Move;
-    
-    if([self ignoreUserInput: triggerInputWhenDisabled])
-    {
-        return;
-    }
-    
-    auto localPoint = [self convertPoint:[event locationInWindow] toView:self];
-    auto avnPoint = [AvnView toAvnPoint:localPoint];
-    auto point = [self translateLocalPoint:avnPoint];
-    AvnVector delta;
-    
-    if(type == Wheel)
-    {
-        auto speed = 5;
-        
-        if([event hasPreciseScrollingDeltas])
-        {
-            speed = 50;
-        }
-        
-        delta.X = [event scrollingDeltaX] / speed;
-        delta.Y = [event scrollingDeltaY] / speed;
-        
-        if(delta.X == 0 && delta.Y == 0)
-        {
-            return;
-        }
-    }
-    else if (type == Magnify)
-    {
-        delta.X = delta.Y = [event magnification];
-    }
-    else if (type == Rotate)
-    {
-        delta.X = delta.Y = [event rotation];
-    }
-    else if (type == Swipe)
-    {
-        delta.X = [event deltaX];
-        delta.Y = [event deltaY];
-    }
-    
-    auto timestamp = [event timestamp] * 1000;
-    auto modifiers = [self getModifiers:[event modifierFlags]];
-    
-    if(type != AvnRawMouseEventType::Move ||
-       (
-           [self window] != nil &&
-           (
-                [[self window] firstResponder] == nil
-                || ![[[self window] firstResponder] isKindOfClass: [NSView class]]
-           )
-       )
-    )
-        [self becomeFirstResponder];
-    
-    if(_parent != nullptr)
-    {
-        _parent->BaseEvents->RawMouseEvent(type, timestamp, modifiers, point, delta);
-    }
-    
-    [super mouseMoved:event];
-}
-
-- (BOOL) resignFirstResponder
-{
-    _parent->BaseEvents->LostFocus();
-    return YES;
-}
-
-- (void)mouseMoved:(NSEvent *)event
-{
-    [self mouseEvent:event withType:Move];
-}
-
-- (void)mouseDown:(NSEvent *)event
-{
-    _isLeftPressed = true;
-    _lastMouseDownEvent = event;
-    [self mouseEvent:event withType:LeftButtonDown];
-}
-
-- (void)otherMouseDown:(NSEvent *)event
-{
-    _lastMouseDownEvent = event;
-
-    switch(event.buttonNumber)
-    {
-        case 2:
-        case 3:
-            _isMiddlePressed = true;
-            [self mouseEvent:event withType:MiddleButtonDown];
-            break;
-        case 4:
-            _isXButton1Pressed = true;
-            [self mouseEvent:event withType:XButton1Down];
-            break;
-        case 5:
-            _isXButton2Pressed = true;
-            [self mouseEvent:event withType:XButton2Down];
-            break;
-    }
-}
-
-- (void)rightMouseDown:(NSEvent *)event
-{
-    _isRightPressed = true;
-    _lastMouseDownEvent = event;
-    [self mouseEvent:event withType:RightButtonDown];
-}
-
-- (void)mouseUp:(NSEvent *)event
-{
-    _isLeftPressed = false;
-    [self mouseEvent:event withType:LeftButtonUp];
-}
-
-- (void)otherMouseUp:(NSEvent *)event
-{
-    switch(event.buttonNumber)
-    {
-        case 2:
-        case 3:
-            _isMiddlePressed = false;
-            [self mouseEvent:event withType:MiddleButtonUp];
-            break;
-        case 4:
-            _isXButton1Pressed = false;
-            [self mouseEvent:event withType:XButton1Up];
-            break;
-        case 5:
-            _isXButton2Pressed = false;
-            [self mouseEvent:event withType:XButton2Up];
-            break;
-    }
-}
-
-- (void)rightMouseUp:(NSEvent *)event
-{
-    _isRightPressed = false;
-    [self mouseEvent:event withType:RightButtonUp];
-}
-
-- (void)mouseDragged:(NSEvent *)event
-{
-    [self mouseEvent:event withType:Move];
-    [super mouseDragged:event];
-}
-
-- (void)otherMouseDragged:(NSEvent *)event
-{
-    [self mouseEvent:event withType:Move];
-    [super otherMouseDragged:event];
-}
-
-- (void)rightMouseDragged:(NSEvent *)event
-{
-    [self mouseEvent:event withType:Move];
-    [super rightMouseDragged:event];
-}
-
-- (void)scrollWheel:(NSEvent *)event
-{
-    [self mouseEvent:event withType:Wheel];
-    [super scrollWheel:event];
-}
-
-- (void)magnifyWithEvent:(NSEvent *)event
-{
-    [self mouseEvent:event withType:Magnify];
-    [super magnifyWithEvent:event];
-}
-
-- (void)rotateWithEvent:(NSEvent *)event
-{
-    [self mouseEvent:event withType:Rotate];
-    [super rotateWithEvent:event];
-}
-
-- (void)swipeWithEvent:(NSEvent *)event
-{
-    [self mouseEvent:event withType:Swipe];
-    [super swipeWithEvent:event];
-}
-
-- (void)mouseEntered:(NSEvent *)event
-{
-    _isMouseOver = true;
-    [super mouseEntered:event];
-}
-
-- (void)mouseExited:(NSEvent *)event
-{
-    _isMouseOver = false;
-    [self mouseEvent:event withType:LeaveWindow];
-    [super mouseExited:event];
-} 
-
-- (void) keyboardEvent: (NSEvent *) event withType: (AvnRawKeyEventType)type
-{
-    if([self ignoreUserInput: false])
-    {
-        return;
-    }
-    
-    auto key = s_KeyMap[[event keyCode]];
-    
-    auto timestamp = [event timestamp] * 1000;
-    auto modifiers = [self getModifiers:[event modifierFlags]];
-     
-    if(_parent != nullptr)
-    {
-        _lastKeyHandled = _parent->BaseEvents->RawKeyEvent(type, timestamp, modifiers, key);
-    }
-}
-
-- (BOOL)performKeyEquivalent:(NSEvent *)event
-{
-    bool result = _lastKeyHandled;
-    
-    _lastKeyHandled = false;
-    
-    return result;
-}
-
-- (void)flagsChanged:(NSEvent *)event
-{
-    auto newModifierState = [self getModifiers:[event modifierFlags]];
-    
-    bool isAltCurrentlyPressed = (_modifierState & Alt) == Alt;
-    bool isControlCurrentlyPressed = (_modifierState & Control) == Control;
-    bool isShiftCurrentlyPressed = (_modifierState & Shift) == Shift;
-    bool isCommandCurrentlyPressed = (_modifierState & Windows) == Windows;
-    
-    bool isAltPressed = (newModifierState & Alt) == Alt;
-    bool isControlPressed = (newModifierState & Control) == Control;
-    bool isShiftPressed = (newModifierState & Shift) == Shift;
-    bool isCommandPressed = (newModifierState & Windows) == Windows;
-    
-    
-    if (isAltPressed && !isAltCurrentlyPressed)
-    {
-        [self keyboardEvent:event withType:KeyDown];
-    }
-    else if (isAltCurrentlyPressed && !isAltPressed)
-    {
-        [self keyboardEvent:event withType:KeyUp];
-    }
-    
-    if (isControlPressed && !isControlCurrentlyPressed)
-    {
-        [self keyboardEvent:event withType:KeyDown];
-    }
-    else if (isControlCurrentlyPressed && !isControlPressed)
-    {
-        [self keyboardEvent:event withType:KeyUp];
-    }
-    
-    if (isShiftPressed && !isShiftCurrentlyPressed)
-    {
-        [self keyboardEvent:event withType:KeyDown];
-    }
-    else if(isShiftCurrentlyPressed && !isShiftPressed)
-    {
-        [self keyboardEvent:event withType:KeyUp];
-    }
-    
-    if(isCommandPressed && !isCommandCurrentlyPressed)
-    {
-        [self keyboardEvent:event withType:KeyDown];
-    }
-    else if(isCommandCurrentlyPressed && ! isCommandPressed)
-    {
-        [self keyboardEvent:event withType:KeyUp];
-    }
-    
-    _modifierState = newModifierState;
-    
-    [[self inputContext] handleEvent:event];
-    [super flagsChanged:event];
-}
-
-- (void)keyDown:(NSEvent *)event
-{
-    [self keyboardEvent:event withType:KeyDown];
-    [[self inputContext] handleEvent:event];
-    [super keyDown:event];
-}
-
-- (void)keyUp:(NSEvent *)event
-{
-    [self keyboardEvent:event withType:KeyUp];
-    [super keyUp:event];
-}
-
-- (AvnInputModifiers)getModifiers:(NSEventModifierFlags)mod
-{
-    unsigned int rv = 0;
-    
-    if (mod & NSEventModifierFlagControl)
-        rv |= Control;
-    if (mod & NSEventModifierFlagShift)
-        rv |= Shift;
-    if (mod & NSEventModifierFlagOption)
-        rv |= Alt;
-    if (mod & NSEventModifierFlagCommand)
-        rv |= Windows;
-    
-    if (_isLeftPressed)
-        rv |= LeftMouseButton;
-    if (_isMiddlePressed)
-        rv |= MiddleMouseButton;
-    if (_isRightPressed)
-        rv |= RightMouseButton;
-    if (_isXButton1Pressed)
-        rv |= XButton1MouseButton;
-    if (_isXButton2Pressed)
-        rv |= XButton2MouseButton;
-    
-    return (AvnInputModifiers)rv;
-}
-
-- (BOOL)hasMarkedText
-{
-    return _lastKeyHandled;
-}
-
-- (NSRange)markedRange
-{
-    return NSMakeRange(NSNotFound, 0);
-}
-
-- (NSRange)selectedRange
-{
-    return NSMakeRange(NSNotFound, 0);
-}
-
-- (void)setMarkedText:(id)string selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
-{
-    
-}
-
-- (void)unmarkText
-{
-    
-}
-
-- (NSArray<NSString *> *)validAttributesForMarkedText
-{
-    return [NSArray new];
-}
-
-- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)range actualRange:(NSRangePointer)actualRange
-{
-    return [NSAttributedString new];
-}
-
-- (void)insertText:(id)string replacementRange:(NSRange)replacementRange
-{
-    if(!_lastKeyHandled)
-    {
-        if(_parent != nullptr)
-        {
-            _lastKeyHandled = _parent->BaseEvents->RawTextInputEvent(0, [string UTF8String]);
-        }
-    }
-}
-
-- (NSUInteger)characterIndexForPoint:(NSPoint)point
-{
-    return 0;
-}
-
-- (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(NSRangePointer)actualRange
-{
-    CGRect result;
-    
-    return result;
-}
-
-- (NSDragOperation)triggerAvnDragEvent: (AvnDragEventType) type info: (id <NSDraggingInfo>)info
-{
-    auto localPoint = [self convertPoint:[info draggingLocation] toView:self];
-    auto avnPoint = [AvnView toAvnPoint:localPoint];
-    auto point = [self translateLocalPoint:avnPoint];
-    auto modifiers = [self getModifiers:[[NSApp currentEvent] modifierFlags]];
-    NSDragOperation nsop = [info draggingSourceOperationMask];
-   
-        auto effects = ConvertDragDropEffects(nsop);
-    int reffects = (int)_parent->BaseEvents
-    ->DragEvent(type, point, modifiers, effects,
-                CreateClipboard([info draggingPasteboard], nil),
-                GetAvnDataObjectHandleFromDraggingInfo(info));
-    
-    NSDragOperation ret = 0;
-    
-    // Ensure that the managed part didn't add any new effects
-    reffects = (int)effects & (int)reffects;
-    
-    // OSX requires exactly one operation
-    if((reffects & (int)AvnDragDropEffects::Copy) != 0)
-        ret = NSDragOperationCopy;
-    else if((reffects & (int)AvnDragDropEffects::Move) != 0)
-        ret = NSDragOperationMove;
-    else if((reffects & (int)AvnDragDropEffects::Link) != 0)
-        ret = NSDragOperationLink;
-    if(ret == 0)
-        ret = NSDragOperationNone;
-    return ret;
-}
-
-- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
-{
-    return [self triggerAvnDragEvent: AvnDragEventType::Enter info:sender];
-}
-
-- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
-{
-    return [self triggerAvnDragEvent: AvnDragEventType::Over info:sender];
-}
-
-- (void)draggingExited:(id <NSDraggingInfo>)sender
-{
-    [self triggerAvnDragEvent: AvnDragEventType::Leave info:sender];
-}
-
-- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
-{
-    return [self triggerAvnDragEvent: AvnDragEventType::Over info:sender] != NSDragOperationNone;
-}
-
-- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
-{
-    return [self triggerAvnDragEvent: AvnDragEventType::Drop info:sender] != NSDragOperationNone;
-}
-
-- (void)concludeDragOperation:(nullable id <NSDraggingInfo>)sender
-{
-    
-}
-
-- (AvnPlatformResizeReason)getResizeReason
-{
-    return _resizeReason;
-}
-
-- (void)setResizeReason:(AvnPlatformResizeReason)reason
-{
-    _resizeReason = reason;
-}
-
-- (AvnAccessibilityElement *) accessibilityChild
-{
-    if (_accessibilityChild == nil)
-    {
-        auto peer = _parent->BaseEvents->GetAutomationPeer();
-        
-        if (peer == nil)
-            return nil;
-
-        _accessibilityChild = [AvnAccessibilityElement acquire:peer];
-    }
-    
-    return _accessibilityChild;
-}
-
-- (NSArray *)accessibilityChildren
-{
-    auto child = [self accessibilityChild];
-    return NSAccessibilityUnignoredChildrenForOnlyChild(child);
-}
-
-- (id)accessibilityHitTest:(NSPoint)point
-{
-    return [[self accessibilityChild] accessibilityHitTest:point];
-}
-
-- (id)accessibilityFocusedUIElement
-{
-    return [[self accessibilityChild] accessibilityFocusedUIElement];
-}
-
-@end
-
-
-@implementation AvnWindow
-{
-    ComPtr<WindowBaseImpl> _parent;
-    bool _canBecomeKeyAndMain;
-    bool _closed;
-    bool _isEnabled;
-    bool _isExtended;
-    AvnMenu* _menu;
-    double _lastScaling;
-    IAvnAutomationPeer* _automationPeer;
-    NSMutableArray* _automationChildren;
-}
-
--(void) setIsExtended:(bool)value;
-{
-    _isExtended = value;
-}
-
--(bool) isDialog
-{
-    return _parent->IsDialog();
-}
-
--(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
-{
-    [[NSApplication sharedApplication] terminate:self];
-}
-
-- (void)performClose:(id)sender
-{
-    if([[self delegate] respondsToSelector:@selector(windowShouldClose:)])
-    {
-        if(![[self delegate] windowShouldClose:self]) return;
-    }
-    else if([self respondsToSelector:@selector(windowShouldClose:)])
-    {
-        if(![self windowShouldClose:self]) return;
-    }
-
-    [self close];
-}
-
-- (void)pollModalSession:(nonnull NSModalSession)session
-{
-    auto response = [NSApp runModalSession:session];
-    
-    if(response == NSModalResponseContinue)
-    {
-        dispatch_async(dispatch_get_main_queue(), ^{
-            [self pollModalSession:session];
-        });
-    }
-    else if (!_closed)
-    {
-        [self orderOut:self];
-        [NSApp endModalSession:session];
-    }
-}
-
--(void) showWindowMenuWithAppMenu
-{
-    if(_menu != nullptr)
-    {
-        auto appMenuItem = ::GetAppMenuItem();
-        
-        if(appMenuItem != nullptr)
-        {
-            auto appMenu = [appMenuItem menu];
-            
-            [appMenu removeItem:appMenuItem];
-            
-            [_menu insertItem:appMenuItem atIndex:0];
-            
-            [_menu setHasGlobalMenuItem:true];
-        }
-        
-        [NSApp setMenu:_menu];
-    }
-    else
-    {
-        [self showAppMenuOnly];
-    }
-}
-
--(void) showAppMenuOnly
-{
-    auto appMenuItem = ::GetAppMenuItem();
-    
-    if(appMenuItem != nullptr)
-    {
-        auto appMenu = ::GetAppMenu();
-        
-        auto nativeAppMenu = dynamic_cast<AvnAppMenu*>(appMenu);
-        
-        [[appMenuItem menu] removeItem:appMenuItem];
-        
-        if(_menu != nullptr)
-        {
-            [_menu setHasGlobalMenuItem:false];
-        }
-        
-        [nativeAppMenu->GetNative() addItem:appMenuItem];
-        
-        [NSApp setMenu:nativeAppMenu->GetNative()];
-    }
-    else
-    {
-        [NSApp setMenu:nullptr];
-    }
-}
-
--(void) applyMenu:(AvnMenu *)menu
-{
-    if(menu == nullptr)
-    {
-        menu = [AvnMenu new];
-    }
-    
-    _menu = menu;
-}
-
--(void) setCanBecomeKeyAndMain
-{
-    _canBecomeKeyAndMain = true;
-}
-
--(AvnWindow*)  initWithParent: (WindowBaseImpl*) parent
-{
-    self = [super init];
-    [self setReleasedWhenClosed:false];
-    _parent = parent;
-    [self setDelegate:self];
-    _closed = false;
-    _isEnabled = true;
-    
-    _lastScaling = [self backingScaleFactor];
-    [self setOpaque:NO];
-    [self setBackgroundColor: [NSColor clearColor]];
-    _isExtended = false;
-    return self;
-}
-
-- (BOOL)windowShouldClose:(NSWindow *)sender
-{
-    auto window = dynamic_cast<WindowImpl*>(_parent.getRaw());
-    
-    if(window != nullptr)
-    {
-        return !window->WindowEvents->Closing();
-    }
-    
-    return true;
-}
-
-- (void)windowDidChangeBackingProperties:(NSNotification *)notification
-{
-    _lastScaling = [self backingScaleFactor];
-}
-
-- (void)windowWillClose:(NSNotification *)notification
-{
-    _closed = true;
-    if(_parent)
-    {
-        ComPtr<WindowBaseImpl> parent = _parent;
-        _parent = NULL;
-        [self restoreParentWindow];
-        parent->BaseEvents->Closed();
-        [parent->View onClosed];
-    }
-}
-
--(BOOL)canBecomeKeyWindow
-{
-    if (_canBecomeKeyAndMain)
-    {
-        // If the window has a child window being shown as a dialog then don't allow it to become the key window.
-        for(NSWindow* uch in [self childWindows])
-        {
-            auto ch = objc_cast<AvnWindow>(uch);
-            if(ch == nil)
-                continue;
-            if (ch.isDialog)
-                return false;
-        }
-        
-        return true;
-    }
-    
-    return false;
-}
-
--(BOOL)canBecomeMainWindow
-{
-    return _canBecomeKeyAndMain;
-}
-
--(bool)shouldTryToHandleEvents
-{
-    return _isEnabled;
-}
-
--(void) setEnabled:(bool)enable
-{
-    _isEnabled = enable;
-}
-
--(void)becomeKeyWindow
-{
-    [self showWindowMenuWithAppMenu];
-    
-    if(_parent != nullptr)
-    {
-        _parent->BaseEvents->Activated();
-    }
-
-    [super becomeKeyWindow];
-}
-
--(void) restoreParentWindow;
-{
-    auto parent = objc_cast<AvnWindow>([self parentWindow]);
-    if(parent != nil)
-    {
-        [parent removeChildWindow:self];
-    }
-}
-
-- (void)windowDidMiniaturize:(NSNotification *)notification
-{
-    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
-    
-    if(parent != nullptr)
-    {
-        parent->WindowStateChanged();
-    }
-}
-
-- (void)windowDidDeminiaturize:(NSNotification *)notification
-{
-    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
-    
-    if(parent != nullptr)
-    {
-        parent->WindowStateChanged();
-    }
-}
-
-- (void)windowDidResize:(NSNotification *)notification
-{
-    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
-    
-    if(parent != nullptr)
-    {
-        parent->WindowStateChanged();
-    }
-}
-
-- (void)windowWillExitFullScreen:(NSNotification *)notification
-{
-    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
-    
-    if(parent != nullptr)
-    {
-        parent->StartStateTransition();
-    }
-}
-
-- (void)windowDidExitFullScreen:(NSNotification *)notification
-{
-    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
-    
-    if(parent != nullptr)
-    {
-        parent->EndStateTransition();
-        
-        if(parent->Decorations() != SystemDecorationsFull && parent->WindowState() == Maximized)
-        {
-            NSRect screenRect = [[self screen] visibleFrame];
-            [self setFrame:screenRect display:YES];
-        }
-        
-        if(parent->WindowState() == Minimized)
-        {
-            [self miniaturize:nullptr];
-        }
-        
-        parent->WindowStateChanged();
-    }
-}
-
-- (void)windowWillEnterFullScreen:(NSNotification *)notification
-{
-    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
-    
-    if(parent != nullptr)
-    {
-        parent->StartStateTransition();
-    }
-}
-
-- (void)windowDidEnterFullScreen:(NSNotification *)notification
-{
-    auto parent = dynamic_cast<IWindowStateChanged*>(_parent.operator->());
-    
-    if(parent != nullptr)
-    {
-        parent->EndStateTransition();
-        parent->WindowStateChanged();
-    }
-}
-
-- (BOOL)windowShouldZoom:(NSWindow *)window toFrame:(NSRect)newFrame
-{
-    return true;
-}
-
--(void)resignKeyWindow
-{
-    if(_parent)
-        _parent->BaseEvents->Deactivated();
-    
-    [self showAppMenuOnly];
-    
-    [super resignKeyWindow];
-}
-
-- (void)windowDidMove:(NSNotification *)notification
-{
-    AvnPoint position;
-    
-    if(_parent != nullptr)
-    {
-        auto cparent = dynamic_cast<WindowImpl*>(_parent.getRaw());
-        
-        if(cparent != nullptr)
-        {
-            if(cparent->WindowState() == Maximized)
-            {
-                cparent->SetWindowState(Normal);
-            }
-        }
-        
-        _parent->GetPosition(&position);
-        _parent->BaseEvents->PositionChanged(position);
-    }
-}
-
-- (AvnPoint) translateLocalPoint:(AvnPoint)pt
-{
-    pt.Y = [self frame].size.height - pt.Y;
-    return pt;
-}
-
-- (void)sendEvent:(NSEvent *)event
-{
-    [super sendEvent:event];
-    
-    /// This is to detect non-client clicks. This can only be done on Windows... not popups, hence the dynamic_cast.
-    if(_parent != nullptr && dynamic_cast<WindowImpl*>(_parent.getRaw()) != nullptr)
-    {
-        switch(event.type)
-        {
-            case NSEventTypeLeftMouseDown:
-            {
-                AvnView* view = _parent->View;
-                NSPoint windowPoint = [event locationInWindow];
-                NSPoint viewPoint = [view convertPoint:windowPoint fromView:nil];
-                
-                if (!NSPointInRect(viewPoint, view.bounds))
-                {
-                    auto avnPoint = [AvnView toAvnPoint:windowPoint];
-                    auto point = [self translateLocalPoint:avnPoint];
-                    AvnVector delta;
-                   
-                    _parent->BaseEvents->RawMouseEvent(NonClientLeftButtonDown, [event timestamp] * 1000, AvnInputModifiersNone, point, delta);
-                }
-            }
-            break;
-                
-            case NSEventTypeMouseEntered:
-            {
-                _parent->UpdateCursor();
-            }
-            break;
-                
-            case NSEventTypeMouseExited:
-            {
-                [[NSCursor arrowCursor] set];
-            }
-            break;
-                
-            default:
-                break;
-        }
-    }
-}
-
-@end
-
-class PopupImpl : public virtual WindowBaseImpl, public IAvnPopup
-{
-private:
-    BEGIN_INTERFACE_MAP()
-    INHERIT_INTERFACE_MAP(WindowBaseImpl)
-    INTERFACE_MAP_ENTRY(IAvnPopup, IID_IAvnPopup)
-    END_INTERFACE_MAP()
-    virtual ~PopupImpl(){}
-    ComPtr<IAvnWindowEvents> WindowEvents;
-    PopupImpl(IAvnWindowEvents* events, IAvnGlContext* gl) : WindowBaseImpl(events, gl)
-    {
-        WindowEvents = events;
-        [Window setLevel:NSPopUpMenuWindowLevel];
-    }
-protected:
-    virtual NSWindowStyleMask GetStyle() override
-    {
-        return NSWindowStyleMaskBorderless;
-    }
-    
-    virtual HRESULT Resize(double x, double y, AvnPlatformResizeReason reason) override
-    {
-        START_COM_CALL;
-        
-        @autoreleasepool
-        {
-            if (Window != nullptr)
-            {
-                [Window setContentSize:NSSize{x, y}];
-            
-                [Window setFrameTopLeftPoint:ToNSPoint(ConvertPointY(lastPositionSet))];
-            }
-            
-            return S_OK;
-        }
-    }
-public:
-    virtual bool ShouldTakeFocusOnShow() override
-    {
-        return false;
-    }
-};
-
-extern IAvnPopup* CreateAvnPopup(IAvnWindowEvents*events, IAvnGlContext* gl)
-{
-    @autoreleasepool
-    {
-        IAvnPopup* ptr = dynamic_cast<IAvnPopup*>(new PopupImpl(events, gl));
-        return ptr;
-    }
-}
-
-extern IAvnWindow* CreateAvnWindow(IAvnWindowEvents*events, IAvnGlContext* gl)
-{
-    @autoreleasepool
-    {
-        IAvnWindow* ptr = (IAvnWindow*)new WindowImpl(events, gl);
-        return ptr;
-    }
-}

+ 1 - 0
samples/BindingDemo/BindingDemo.csproj

@@ -5,6 +5,7 @@
   </PropertyGroup>
   <ItemGroup>
     <ProjectReference Include="..\..\src\Avalonia.Diagnostics\Avalonia.Diagnostics.csproj" />
+    <ProjectReference Include="..\..\src\Avalonia.Themes.Default\Avalonia.Themes.Default.csproj" />
     <ProjectReference Include="..\..\src\Linux\Avalonia.LinuxFramebuffer\Avalonia.LinuxFramebuffer.csproj" />
     <ProjectReference Include="..\MiniMvvm\MiniMvvm.csproj" />
   </ItemGroup>

+ 0 - 1
samples/ControlCatalog.NetCore/Program.cs

@@ -117,7 +117,6 @@ namespace ControlCatalog.NetCore
                     EnableMultitouch = true
                 })
                 .UseSkia()
-                .UseManagedSystemDialogs()
                 .AfterSetup(builder =>
                 {
                     builder.Instance!.AttachDevTools(new Avalonia.Diagnostics.DevToolsOptions()

+ 2 - 2
samples/ControlCatalog/App.xaml.cs

@@ -20,12 +20,12 @@ namespace ControlCatalog
 
         public static readonly StyleInclude ColorPickerFluent = new StyleInclude(new Uri("avares://ControlCatalog/Styles"))
         {
-            Source = new Uri("avares://Avalonia.Controls.ColorPicker/Themes/Fluent.xaml")
+            Source = new Uri("avares://Avalonia.Controls.ColorPicker/Themes/Fluent/Fluent.xaml")
         };
 
         public static readonly StyleInclude ColorPickerDefault = new StyleInclude(new Uri("avares://ControlCatalog/Styles"))
         {
-            Source = new Uri("avares://Avalonia.Controls.ColorPicker/Themes/Default.xaml")
+            Source = new Uri("avares://Avalonia.Controls.ColorPicker/Themes/Default/Default.xaml")
         };
 
         public static readonly StyleInclude DataGridFluent = new StyleInclude(new Uri("avares://ControlCatalog/Styles"))

+ 4 - 1
samples/ControlCatalog/ControlCatalog.csproj

@@ -1,7 +1,8 @@
 <Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
     <TargetFramework>netstandard2.0</TargetFramework>
-    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>    
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+    <Nullable>enable</Nullable>    
   </PropertyGroup>
   <ItemGroup>
     <Compile Update="**\*.xaml.cs">
@@ -25,6 +26,8 @@
     <ProjectReference Include="..\..\packages\Avalonia\Avalonia.csproj" />
     <ProjectReference Include="..\..\src\Avalonia.Controls.ColorPicker\Avalonia.Controls.ColorPicker.csproj" />
     <ProjectReference Include="..\..\src\Avalonia.Controls.DataGrid\Avalonia.Controls.DataGrid.csproj" />
+    <ProjectReference Include="..\..\src\Avalonia.Themes.Default\Avalonia.Themes.Default.csproj" />
+    <ProjectReference Include="..\..\src\Avalonia.Themes.Fluent\Avalonia.Themes.Fluent.csproj" />
     <ProjectReference Include="..\MiniMvvm\MiniMvvm.csproj" />
     <ProjectReference Include="..\SampleControls\ControlSamples.csproj" />
   </ItemGroup>

+ 1 - 2
samples/ControlCatalog/Pages/CalendarDatePickerPage.xaml

@@ -10,8 +10,7 @@
                 Margin="0,16,0,0"
                 HorizontalAlignment="Center"
                 Spacing="16">
-      <StackPanel Orientation="Vertical"
-                  Width="200">
+      <StackPanel Orientation="Vertical">
         <TextBlock Text="SelectedDateFormat: Short"/>
         <CalendarDatePicker Name="DatePicker1"
                     SelectedDateFormat="Short"

+ 1 - 0
samples/ControlCatalog/Pages/CarouselPage.xaml

@@ -29,6 +29,7 @@
         <ComboBoxItem>None</ComboBoxItem>
         <ComboBoxItem>Slide</ComboBoxItem>
         <ComboBoxItem>Crossfade</ComboBoxItem>
+        <ComboBoxItem>3D Rotation</ComboBoxItem>
       </ComboBox>
     </StackPanel>
 

+ 3 - 0
samples/ControlCatalog/Pages/CarouselPage.xaml.cs

@@ -45,6 +45,9 @@ namespace ControlCatalog.Pages
                 case 2:
                     _carousel.PageTransition = new CrossFade(TimeSpan.FromSeconds(0.25));
                     break;
+                case 3:
+                    _carousel.PageTransition = new Rotate3DTransition(TimeSpan.FromSeconds(0.5), _orientation.SelectedIndex == 0 ? PageSlide.SlideAxis.Horizontal : PageSlide.SlideAxis.Vertical);
+                    break;
             }
         }
     }

+ 68 - 18
samples/ControlCatalog/Pages/ColorPickerPage.xaml

@@ -3,27 +3,77 @@
              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
              xmlns:primitives="clr-namespace:Avalonia.Controls.Primitives;assembly=Avalonia.Controls"
-             mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
+             xmlns:pc="clr-namespace:Avalonia.Controls.Primitives.Converters;assembly=Avalonia.Controls.ColorPicker"
+             mc:Ignorable="d"
+             d:DesignWidth="800"
+             d:DesignHeight="450"
              x:Class="ControlCatalog.Pages.ColorPickerPage">
 
-  <Grid ColumnDefinitions="Auto,Auto"
-        RowDefinitions="Auto,Auto">
-    <ColorSpectrum Grid.Column="0"
+  <UserControl.Resources>
+    <pc:ThirdComponentConverter x:Key="ThirdComponent" />
+  </UserControl.Resources>
+
+  <Grid ColumnDefinitions="Auto,10,Auto">
+    <Grid Grid.Column="0"
+          Grid.Row="0"
+          RowDefinitions="Auto,Auto,Auto,Auto,Auto,Auto">
+      <ColorSpectrum x:Name="ColorSpectrum1"
+                     Grid.Row="0"
+                     Color="Red"
+                     CornerRadius="10"
+                     Height="256"
+                     Width="256" />
+      <ColorSlider Grid.Row="1"
+                   Margin="0,10,0,0"
+                   ColorComponent="Component1"
+                   ColorModel="Hsva"
+                   HsvColor="{Binding HsvColor, ElementName=ColorSpectrum1}" />
+      <ColorSlider Grid.Row="2"
+                   ColorComponent="Component2"
+                   ColorModel="Hsva"
+                   HsvColor="{Binding HsvColor, ElementName=ColorSpectrum1}" />
+      <ColorSlider Grid.Row="3"
+                   ColorComponent="Component3"
+                   ColorModel="Hsva"
+                   HsvColor="{Binding HsvColor, ElementName=ColorSpectrum1}" />
+      <ColorSlider Grid.Row="4"
+                   ColorComponent="Alpha"
+                   ColorModel="Hsva"
+                   HsvColor="{Binding HsvColor, ElementName=ColorSpectrum1}" />
+      <ColorPreviewer Grid.Row="5"
+                      ShowAccentColors="True"
+                      HsvColor="{Binding HsvColor, ElementName=ColorSpectrum1}" />
+    </Grid>
+    <Grid Grid.Column="2"
+          Grid.Row="0"
+          ColumnDefinitions="Auto,Auto,Auto"
+          RowDefinitions="Auto,Auto">
+      <ColorSlider Grid.Column="0"
                    Grid.Row="0"
-                   Color="Red"
-                   Height="256"
-                   Width="256" />
-    <ColorSpectrum Grid.Column="1"
+                   IsAlphaMaxForced="True"
+                   IsSaturationValueMaxForced="False"
+                   ColorComponent="{Binding Components, ElementName=ColorSpectrum2, Converter={StaticResource ThirdComponent}}"
+                   ColorModel="Hsva"
+                   Orientation="Vertical"
+                   HsvColor="{Binding HsvColor, ElementName=ColorSpectrum2}" />
+      <ColorSpectrum x:Name="ColorSpectrum2"
+                     Grid.Column="1"
+                     Grid.Row="0"
+                     Color="Green"
+                     Shape="Ring"
+                     Height="256"
+                     Width="256" />
+      <ColorSlider Grid.Column="2"
                    Grid.Row="0"
-                   Color="Green"
-                   Shape="Ring"
-                   Height="256"
-                   Width="256" />
-    <ColorSpectrum Grid.Column="0"
-                   Grid.Row="1"
-                   CornerRadius="10"
-                   Color="Blue"
-                   Height="256"
-                   Width="256" />
+                   ColorComponent="Alpha"
+                   ColorModel="Hsva"
+                   Orientation="Vertical"
+                   HsvColor="{Binding HsvColor, ElementName=ColorSpectrum2}" />
+      <ColorPreviewer Grid.Column="0"
+                      Grid.ColumnSpan="3"
+                      Grid.Row="1"
+                      ShowAccentColors="True"
+                      HsvColor="{Binding HsvColor, ElementName=ColorSpectrum2}" />
+    </Grid>
   </Grid>
 </UserControl>

+ 10 - 0
samples/ControlCatalog/Pages/ComboBoxPage.xaml

@@ -86,6 +86,16 @@
                         <sys:Exception />
                     </DataValidationErrors.Error>
                 </ComboBox>
+
+                <ComboBox PlaceholderText="Scaled" Width="166" RenderTransformOrigin="0,0">
+                    <ComboBox.RenderTransform>
+                      <ScaleTransform ScaleX="1.5" ScaleY="1.5"/>
+                    </ComboBox.RenderTransform>
+                    <ComboBoxItem>Inline Items</ComboBoxItem>
+                    <ComboBoxItem>Inline Item 2</ComboBoxItem>
+                    <ComboBoxItem>Inline Item 3</ComboBoxItem>
+                    <ComboBoxItem>Inline Item 4</ComboBoxItem>
+                </ComboBox>
             </WrapPanel>
 
             <CheckBox IsChecked="{Binding WrapSelection}">WrapSelection</CheckBox>

+ 1 - 2
samples/ControlCatalog/Pages/DialogsPage.xaml.cs

@@ -8,7 +8,6 @@ using Avalonia.Dialogs;
 using Avalonia.Layout;
 using Avalonia.Markup.Xaml;
 #pragma warning disable 4014
-
 namespace ControlCatalog.Pages
 {
     public class DialogsPage : UserControl
@@ -22,7 +21,7 @@ namespace ControlCatalog.Pages
 
             string lastSelectedDirectory = null;
 
-            List<FileDialogFilter> GetFilters()
+            List<FileDialogFilter>? GetFilters()
             {
                 if (this.FindControl<CheckBox>("UseFilters").IsChecked != true)
                     return null;

+ 6 - 0
samples/ControlCatalog/Pages/TextBoxPage.xaml

@@ -66,6 +66,12 @@
                  FontFamily="Comic Sans MS"
                  InputMethod.IsInputMethodEnabled="False"
                  Foreground="Red"/>
+        <TextBox AcceptsReturn="True" 
+                 TextWrapping="Wrap" 
+                 Width="200" 
+                 Height="125"
+                 LineHeight="32"
+                 Text="Multiline TextBox with TextWrapping and increased LineHeight.&#xD;&#xD;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est." />
       </StackPanel>
       <StackPanel Orientation="Vertical" Spacing="8" Margin="8">
         <Label Classes="h2" Target="{Binding #firstResMFont}">res_m fonts</Label>

+ 1 - 1
samples/ControlCatalog/ViewModels/MainWindowViewModel.cs

@@ -18,7 +18,7 @@ namespace ControlCatalog.ViewModels
         private WindowState _windowState;
         private WindowState[] _windowStates;
         private int _transparencyLevel;
-        private ExtendClientAreaChromeHints _chromeHints;
+        private ExtendClientAreaChromeHints _chromeHints = ExtendClientAreaChromeHints.PreferSystemChrome;
         private bool _extendClientAreaEnabled;
         private bool _systemTitleBarEnabled;        
         private bool _preferSystemChromeEnabled;

+ 2 - 1
samples/IntegrationTestApp/IntegrationTestApp.csproj

@@ -1,4 +1,4 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
     <OutputType>WinExe</OutputType>
     <TargetFramework>net6.0</TargetFramework>
@@ -18,6 +18,7 @@
 
   <ItemGroup>
     <ProjectReference Include="..\..\src\Avalonia.Diagnostics\Avalonia.Diagnostics.csproj" />
+    <ProjectReference Include="..\..\src\Avalonia.Themes.Fluent\Avalonia.Themes.Fluent.csproj" />
   </ItemGroup>
   
   <Import Project="..\..\build\BuildTargets.targets" />

+ 1 - 0
samples/PlatformSanityChecks/PlatformSanityChecks.csproj

@@ -7,6 +7,7 @@
 
   <ItemGroup>
     <ProjectReference Include="..\..\src\Avalonia.Desktop\Avalonia.Desktop.csproj" />
+    <ProjectReference Include="..\..\src\Avalonia.Themes.Default\Avalonia.Themes.Default.csproj" />
     <ProjectReference Include="..\..\src\Avalonia.X11\Avalonia.X11.csproj" />
   </ItemGroup>
 

+ 3 - 0
samples/Previewer/Previewer.csproj

@@ -9,6 +9,9 @@
     </Compile>
     <EmbeddedResource Include="**\*.xaml" />
   </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\src\Avalonia.Themes.Default\Avalonia.Themes.Default.csproj" />
+  </ItemGroup>
   
   <Import Project="..\..\build\SampleApp.props" />
   <Import Project="..\..\build\ReferenceCoreLibraries.props" />

+ 3 - 0
samples/RenderDemo/MainWindow.xaml

@@ -72,5 +72,8 @@
     <TabItem Header="Brushes">
       <pages:BrushesPage />
     </TabItem>
+    <TabItem Header="3D Transformation">
+      <pages:Transform3DPage />
+    </TabItem>
   </controls:HamburgerMenu>
 </Window>

+ 210 - 0
samples/RenderDemo/Pages/Transform3DPage.axaml

@@ -0,0 +1,210 @@
+<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="600" d:DesignHeight="700"
+             x:Class="RenderDemo.Pages.Transform3DPage">
+    <UserControl.Styles>
+        <Styles>
+            <Styles.Resources>
+                <Template x:Key="TestContent">
+                    <Grid RowDefinitions="*,*" ColumnDefinitions="*,*" Margin="5">
+                        <TextBlock>I'm a text</TextBlock>
+                        <Button Grid.Row="0" Grid.Column="1" Content="A Button"></Button>
+                        <Slider Grid.Row="1"
+                                Grid.Column="0"
+                                Grid.ColumnSpan="2"
+                                Value="{Binding Depth}"
+                                Minimum="100"
+                                Maximum="300" />
+                    </Grid>
+                </Template>
+            </Styles.Resources>
+        </Styles>
+        <Style Selector="Border.Test">
+            <Setter Property="Width" Value="200" />
+            <Setter Property="Height" Value="200" />
+            <Setter Property="Child" Value="{StaticResource TestContent}" />
+            <Setter Property="BorderThickness" Value="2" />
+            <Setter Property="BorderBrush" Value="Black" />
+            <Setter Property="Grid.ColumnSpan" Value="2" />
+        </Style>
+        <Style Selector="TextBlock, Label, Slider">
+            <Setter Property="VerticalAlignment" Value="Center" />
+            <Setter Property="Margin" Value="10,0,10,0" />
+        </Style>
+        <Style Selector="Border TextBlock">
+            <Setter Property="Foreground" Value="White" />
+        </Style>
+        <Style Selector="Border Button">
+            <Setter Property="Background" Value="White"></Setter>
+            <Setter Property="Foreground" Value="Black" />
+        </Style>
+        
+        <Style Selector="Border#B1">
+            <Style.Animations>
+                <Animation Duration="0:0:10"
+                           IterationCount="Infinite">
+                    <KeyFrame Cue="0%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="0" />
+                        <Setter Property="ZIndex" Value="4" />
+                    </KeyFrame>
+                    <KeyFrame Cue="25%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="90" />
+                        <Setter Property="ZIndex" Value="1" />
+                    </KeyFrame>
+                    <KeyFrame Cue="100%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="360" />
+                        <Setter Property="ZIndex" Value="4" />
+                    </KeyFrame>
+                </Animation>
+            </Style.Animations>
+        </Style>
+        <Style Selector="Border#B2">
+            <Style.Animations>
+                <Animation Duration="0:0:10"
+                           IterationCount="Infinite">
+                    <KeyFrame Cue="0%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="90" />
+                        <Setter Property="ZIndex" Value="1" />
+                    </KeyFrame>
+                    <KeyFrame Cue="25%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="180" />
+                        <Setter Property="ZIndex" Value="1" />
+                    </KeyFrame>
+                    <KeyFrame Cue="75%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="360" />
+                        <Setter Property="ZIndex" Value="4" />
+                    </KeyFrame>
+                    <KeyFrame Cue="100%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="450" />
+                        <Setter Property="ZIndex" Value="1" />
+                    </KeyFrame>
+                </Animation>
+            </Style.Animations>
+        </Style>
+        <Style Selector="Border#B3">
+            <Style.Animations>
+                <Animation Duration="0:0:10"
+                           IterationCount="Infinite">
+                    <KeyFrame Cue="0%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="180" />
+                        <Setter Property="ZIndex" Value="1" />
+                    </KeyFrame>
+                    <KeyFrame Cue="50%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="360" />
+                        <Setter Property="ZIndex" Value="4" />
+                    </KeyFrame>
+                    <KeyFrame Cue="75%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="450" />
+                        <Setter Property="ZIndex" Value="1" />
+                    </KeyFrame>
+                    <KeyFrame Cue="100%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="540" />
+                        <Setter Property="ZIndex" Value="1" />
+                    </KeyFrame>
+                </Animation>
+            </Style.Animations>
+        </Style>
+        <Style Selector="Border#B4">
+            <Style.Animations>
+                <Animation Duration="0:0:10"
+                           IterationCount="Infinite">
+                    <KeyFrame Cue="0%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="270" />
+                        <Setter Property="ZIndex" Value="1" />
+                    </KeyFrame>
+                    <KeyFrame Cue="25%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="360" />
+                        <Setter Property="ZIndex" Value="4" />
+                    </KeyFrame>
+                    <KeyFrame Cue="50%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="450" />
+                        <Setter Property="ZIndex" Value="1" />
+                    </KeyFrame>
+                    <KeyFrame Cue="100%">
+                        <Setter Property="Rotate3DTransform.AngleX" Value="630" />
+                        <Setter Property="ZIndex" Value="1" />
+                    </KeyFrame>
+                </Animation>
+            </Style.Animations>
+        </Style>
+    </UserControl.Styles>
+
+    <Grid ColumnDefinitions="Auto,*,Auto,*" RowDefinitions="*, Auto, Auto, Auto, Auto, Auto, Auto, Auto">
+        <Grid.Clock>
+            <Clock />
+        </Grid.Clock>
+        <Border Name="B1" Background="DarkRed" Classes="Test">
+            <Border.RenderTransform>
+                <Rotate3DTransform CenterZ="-100"
+                                   Depth="{Binding Depth}" />
+            </Border.RenderTransform>
+        </Border>
+        <Border Name="B2" Grid.Row="0" Grid.Column="0" Classes="Test" Background="DarkGreen">
+            <Border.RenderTransform>
+                <Rotate3DTransform CenterZ="-100"
+                                   Depth="{Binding Depth}" />
+            </Border.RenderTransform>
+        </Border>
+        <Border Name="B3" Grid.Row="0" Grid.Column="0" Classes="Test" Background="DarkBlue">
+            <Border.RenderTransform>
+                <Rotate3DTransform CenterZ="-100"
+                                   Depth="{Binding Depth}" />
+            </Border.RenderTransform>
+        </Border>
+        <Border Name="B4" Grid.Row="0" Grid.Column="0" Classes="Test" Background="Orange">
+            <Border.RenderTransform>
+                <Rotate3DTransform CenterZ="-100"
+                                   Depth="{Binding Depth}" />
+            </Border.RenderTransform>
+        </Border>
+
+        <Label Grid.Column="0" Grid.Row="1">Depth: </Label>
+        <Slider Grid.Column="1" Grid.Row="1" Value="{Binding Depth}" Minimum="100" Maximum="300" />
+
+        <Border Grid.Row="0" Grid.Column="2" Classes="Test" ZIndex="-2">
+            <Border.Background>
+                <LinearGradientBrush StartPoint="0%,0%" EndPoint="0%,100%">
+                    <GradientStop Offset="0" Color="Red" />
+                    <GradientStop Offset="1" Color="Blue" />
+                </LinearGradientBrush>
+            </Border.Background>
+            <Border.Styles>
+                <Style Selector="Label">
+                    <Setter Property="VerticalAlignment" Value="Center" />
+                </Style>
+                <Style Selector="Slider">
+                    <Setter Property="Width" Value="100" />
+                </Style>
+            </Border.Styles>
+            <Border.RenderTransform>
+                <Rotate3DTransform Depth="{Binding Depth}"
+                                   CenterX="{Binding CenterX}"
+                                   CenterY="{Binding CenterY}"
+                                   CenterZ="{Binding CenterZ}"
+                                   AngleX="{Binding AngleX}"
+                                   AngleY="{Binding AngleY}"
+                                   AngleZ="{Binding AngleZ}" />
+            </Border.RenderTransform>
+        </Border>
+
+        <Label Grid.Row="1" Grid.Column="2">Center X: </Label>
+        <Slider Grid.Row="1" Grid.Column="3" Value="{Binding CenterX}" Minimum="-100" Maximum="100" />
+
+        <Label Grid.Row="2" Grid.Column="2">Center Y: </Label>
+        <Slider Grid.Row="2" Grid.Column="3" Value="{Binding CenterY}" Minimum="-100" Maximum="100" />
+
+        <Label Grid.Row="3" Grid.Column="2">Center Z: </Label>
+        <Slider Grid.Row="3" Grid.Column="3" Value="{Binding CenterZ}" Minimum="-100" Maximum="100" />
+
+        <Label Grid.Row="4" Grid.Column="2">Angle X: </Label>
+        <Slider Grid.Row="4" Grid.Column="3" Value="{Binding AngleX}" Minimum="-180" Maximum="180" />
+
+        <Label Grid.Row="5" Grid.Column="2">Angle Y: </Label>
+        <Slider Grid.Row="5" Grid.Column="3" Value="{Binding AngleY}" Minimum="-180" Maximum="180" />
+
+        <Label Grid.Row="6" Grid.Column="2">Angle Z: </Label>
+        <Slider Grid.Row="6" Grid.Column="3" Value="{Binding AngleZ}" Minimum="-180" Maximum="180" />
+    </Grid>
+</UserControl>

+ 21 - 0
samples/RenderDemo/Pages/Transform3DPage.axaml.cs

@@ -0,0 +1,21 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Markup.Xaml;
+using RenderDemo.ViewModels;
+
+namespace RenderDemo.Pages;
+
+public class Transform3DPage : UserControl
+{
+    public Transform3DPage()
+    {
+        InitializeComponent();
+        this.DataContext = new Transform3DPageViewModel();
+    }
+
+    private void InitializeComponent()
+    {
+        AvaloniaXamlLoader.Load(this);
+    }
+}
+

+ 1 - 0
samples/RenderDemo/RenderDemo.csproj

@@ -12,6 +12,7 @@
   </ItemGroup>
   <ItemGroup>
     <ProjectReference Include="..\..\src\Avalonia.Diagnostics\Avalonia.Diagnostics.csproj" />
+    <ProjectReference Include="..\..\src\Avalonia.Themes.Fluent\Avalonia.Themes.Fluent.csproj" />
     <ProjectReference Include="..\..\src\Linux\Avalonia.LinuxFramebuffer\Avalonia.LinuxFramebuffer.csproj" />
     <ProjectReference Include="..\MiniMvvm\MiniMvvm.csproj" />
     <ProjectReference Include="..\SampleControls\ControlSamples.csproj" />

+ 55 - 0
samples/RenderDemo/ViewModels/Transform3DPageViewModel.cs

@@ -0,0 +1,55 @@
+using System;
+using MiniMvvm;
+using Avalonia.Animation;
+
+namespace RenderDemo.ViewModels
+{
+    public class Transform3DPageViewModel : ViewModelBase
+    {
+        private double _depth = 200;
+
+        private double _centerX = 0;
+        private double _centerY = 0;
+        private double _centerZ = 0;
+        private double _angleX = 0;
+        private double _angleY = 0;
+        private double _angleZ = 0;
+        
+        public double Depth
+        {
+            get => _depth;
+            set => RaiseAndSetIfChanged(ref _depth, value);
+        }
+        
+        public double CenterX
+        {
+            get => _centerX;
+            set => RaiseAndSetIfChanged(ref _centerX, value);
+        }
+        public double CenterY
+        {
+            get => _centerY;
+            set => RaiseAndSetIfChanged(ref _centerY, value);
+        }
+        public double CenterZ
+        {
+            get => _centerZ;
+            set => RaiseAndSetIfChanged(ref _centerZ, value);
+        }
+        public double AngleX
+        {
+            get => _angleX;
+            set => RaiseAndSetIfChanged(ref _angleX, value);
+        }
+        public double AngleY
+        {
+            get => _angleY;
+            set => RaiseAndSetIfChanged(ref _angleY, value);
+        }
+        public double AngleZ
+        {
+            get => _angleZ;
+            set => RaiseAndSetIfChanged(ref _angleZ, value);
+        }
+    }
+}

+ 1 - 0
samples/Sandbox/Sandbox.csproj

@@ -10,6 +10,7 @@
     <ProjectReference Include="..\..\src\Avalonia.Diagnostics\Avalonia.Diagnostics.csproj" />
     <ProjectReference Include="..\..\src\Avalonia.Controls.ColorPicker\Avalonia.Controls.ColorPicker.csproj" />
     <ProjectReference Include="..\..\src\Avalonia.Controls.DataGrid\Avalonia.Controls.DataGrid.csproj" />
+    <ProjectReference Include="..\..\src\Avalonia.Themes.Fluent\Avalonia.Themes.Fluent.csproj" />
   </ItemGroup>
   
   <Import Project="..\..\build\SampleApp.props" />

+ 1 - 0
samples/VirtualizationDemo/VirtualizationDemo.csproj

@@ -5,6 +5,7 @@
   </PropertyGroup>
   <ItemGroup>
     <ProjectReference Include="..\..\src\Avalonia.Diagnostics\Avalonia.Diagnostics.csproj" />
+    <ProjectReference Include="..\..\src\Avalonia.Themes.Default\Avalonia.Themes.Default.csproj" />
     <ProjectReference Include="..\..\src\Linux\Avalonia.LinuxFramebuffer\Avalonia.LinuxFramebuffer.csproj" />
     <ProjectReference Include="..\MiniMvvm\MiniMvvm.csproj" />
   </ItemGroup>

+ 1 - 0
samples/interop/Direct3DInteropSample/Direct3DInteropSample.csproj

@@ -22,6 +22,7 @@
       </EmbeddedResource>
     </ItemGroup>
     <ItemGroup>
+        <ProjectReference Include="..\..\..\src\Avalonia.Themes.Default\Avalonia.Themes.Default.csproj" />
         <ProjectReference Include="..\..\..\src\Windows\Avalonia.Direct2D1\Avalonia.Direct2D1.csproj" />
         <ProjectReference Include="..\..\..\src\Windows\Avalonia.Win32\Avalonia.Win32.csproj" />
         <ProjectReference Include="..\..\MiniMvvm\MiniMvvm.csproj" />

+ 1 - 0
samples/interop/NativeEmbedSample/NativeEmbedSample.csproj

@@ -9,6 +9,7 @@
 
   <ItemGroup>
     <PackageReference Include="MonoMac.NetStandard" Version="0.0.4" />
+    <ProjectReference Include="..\..\..\src\Avalonia.Themes.Default\Avalonia.Themes.Default.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" />

+ 1 - 1
src/Android/Avalonia.Android/Platform/SkiaPlatform/TopLevelImpl.cs

@@ -40,7 +40,7 @@ namespace Avalonia.Android.Platform.SkiaPlatform
             _gl = GlPlatformSurface.TryCreate(this);
             _framebuffer = new FramebufferManager(this);
 
-            RenderScaling = (int)_view.Scaling;
+            RenderScaling = _view.Scaling;
 
             MaxClientSize = new PixelSize(_view.Resources.DisplayMetrics.WidthPixels,
                 _view.Resources.DisplayMetrics.HeightPixels).ToSize(RenderScaling);

+ 1 - 0
src/Avalonia.Base/Animation/Animators/TransformAnimator.cs

@@ -43,6 +43,7 @@ namespace Avalonia.Animation.Animators
                     normalTransform.Children.Add(new SkewTransform());
                     normalTransform.Children.Add(new RotateTransform());
                     normalTransform.Children.Add(new TranslateTransform());
+                    normalTransform.Children.Add(new Rotate3DTransform());
 
                     ctrl.RenderTransform = normalTransform;
                 }

+ 2 - 0
src/Avalonia.Base/Animation/IAnimation.cs

@@ -1,12 +1,14 @@
 using System;
 using System.Threading;
 using System.Threading.Tasks;
+using Avalonia.Metadata;
 
 namespace Avalonia.Animation
 {
     /// <summary>
     /// Interface for Animation objects
     /// </summary>
+    [NotClientImplementable]
     public interface IAnimation
     {
         /// <summary>

+ 3 - 0
src/Avalonia.Base/Animation/IAnimationSetter.cs

@@ -1,5 +1,8 @@
+using Avalonia.Metadata;
+
 namespace Avalonia.Animation
 {
+    [NotClientImplementable]
     public interface IAnimationSetter
     {
         AvaloniaProperty? Property { get; set; }

+ 2 - 0
src/Avalonia.Base/Animation/IAnimator.cs

@@ -1,11 +1,13 @@
 using System;
 using System.Collections.Generic;
+using Avalonia.Metadata;
 
 namespace Avalonia.Animation
 {
     /// <summary>
     /// Interface for Animator objects
     /// </summary>
+    [NotClientImplementable]
     public interface IAnimator : IList<AnimatorKeyFrame>
     {
         /// <summary>

+ 2 - 2
src/Avalonia.Base/Animation/IClock.cs

@@ -1,9 +1,9 @@
 using System;
-using System.Collections.Generic;
-using System.Text;
+using Avalonia.Metadata;
 
 namespace Avalonia.Animation
 {
+    [NotClientImplementable]
     public interface IClock : IObservable<TimeSpan>
     {
         PlayState PlayState { get; set; }

+ 2 - 3
src/Avalonia.Base/Animation/IGlobalClock.cs

@@ -1,9 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
+using Avalonia.Metadata;
 
 namespace Avalonia.Animation
 {
+    [NotClientImplementable]
     public interface IGlobalClock : IClock
     {
     }

+ 2 - 0
src/Avalonia.Base/Animation/ITransition.cs

@@ -1,10 +1,12 @@
 using System;
+using Avalonia.Metadata;
 
 namespace Avalonia.Animation
 {
     /// <summary>
     /// Interface for Transition objects.
     /// </summary>
+    [NotClientImplementable]
     public interface ITransition
     {
         /// <summary>

+ 3 - 3
src/Avalonia.Base/Animation/PageSlide.cs

@@ -10,7 +10,7 @@ using Avalonia.VisualTree;
 namespace Avalonia.Animation
 {
     /// <summary>
-    /// Transitions between two pages by sliding them horizontally.
+    /// Transitions between two pages by sliding them horizontally or vertically.
     /// </summary>
     public class PageSlide : IPageTransition
     {
@@ -62,7 +62,7 @@ namespace Avalonia.Animation
         public Easing SlideOutEasing { get; set; } = new LinearEasing();
 
         /// <inheritdoc />
-        public async Task Start(Visual? from, Visual? to, bool forward, CancellationToken cancellationToken)
+        public virtual async Task Start(Visual? from, Visual? to, bool forward, CancellationToken cancellationToken)
         {
             if (cancellationToken.IsCancellationRequested)
             {
@@ -157,7 +157,7 @@ namespace Avalonia.Animation
         /// <remarks>
         /// Any one of the parameters may be null, but not both.
         /// </remarks>
-        private static IVisual GetVisualParent(IVisual? from, IVisual? to)
+        protected static IVisual GetVisualParent(IVisual? from, IVisual? to)
         {
             var p1 = (from ?? to)!.VisualParent;
             var p2 = (to ?? from)!.VisualParent;

+ 121 - 0
src/Avalonia.Base/Animation/Transitions/Rotate3DTransition.cs

@@ -0,0 +1,121 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Avalonia.Media;
+using Avalonia.Styling;
+
+namespace Avalonia.Animation;
+
+public class Rotate3DTransition: PageSlide
+{
+
+    /// <summary>
+    ///  Creates a new instance of the <see cref="Rotate3DTransition"/>
+    /// </summary>
+    /// <param name="duration">How long the rotation should take place</param>
+    /// <param name="orientation">The orientation of the rotation</param>
+    /// <param name="depth">Defines the depth of the 3D Effect. If null, depth will be calculated automatically from the width or height of the common parent of the visual being rotated</param>
+    public Rotate3DTransition(TimeSpan duration, SlideAxis orientation = SlideAxis.Horizontal, double? depth = null)
+        : base(duration, orientation)
+    {
+        Depth = depth;
+    }
+    
+    /// <summary>
+    ///  Defines the depth of the 3D Effect. If null, depth will be calculated automatically from the width or height
+    ///  of the common parent of the visual being rotated.
+    /// </summary>
+    public double? Depth { get; set; }
+
+    /// <summary>
+    ///  Creates a new instance of the <see cref="Rotate3DTransition"/>
+    /// </summary>
+    public Rotate3DTransition() { }
+
+    /// <inheritdoc />
+    public override async Task Start(Visual? @from, Visual? to, bool forward, CancellationToken cancellationToken)
+    {
+        if (cancellationToken.IsCancellationRequested)
+        {
+            return;
+        }
+
+        var tasks = new Task[from != null && to != null ? 2 : 1];
+        var parent = GetVisualParent(from, to);
+        var (rotateProperty, center) = Orientation switch
+        {
+            SlideAxis.Vertical => (Rotate3DTransform.AngleXProperty, parent.Bounds.Height),
+            SlideAxis.Horizontal => (Rotate3DTransform.AngleYProperty, parent.Bounds.Width),
+            _ => throw new ArgumentOutOfRangeException()
+        };
+
+        var depthSetter = new Setter {Property = Rotate3DTransform.DepthProperty, Value = Depth ?? center};
+        var centerZSetter = new Setter {Property = Rotate3DTransform.CenterZProperty, Value = -center / 2};
+
+        KeyFrame CreateKeyFrame(double cue, double rotation, int zIndex, bool isVisible = true) => 
+            new() {
+                Setters =
+                {
+                    new Setter { Property = rotateProperty, Value = rotation },
+                    new Setter { Property = Visual.ZIndexProperty, Value = zIndex },
+                    new Setter { Property = Visual.IsVisibleProperty, Value = isVisible },
+                    centerZSetter,
+                    depthSetter
+                },
+                Cue = new Cue(cue)
+            };
+
+        if (from != null)
+        {
+            var animation = new Animation
+            {
+                Easing = SlideOutEasing,
+                Duration = Duration,
+                FillMode = FillMode.Forward,
+                Children =
+                {
+                    CreateKeyFrame(0d, 0d, 2),
+                    CreateKeyFrame(0.5d, 45d * (forward ? -1 : 1), 1),
+                    CreateKeyFrame(1d, 90d * (forward ? -1 : 1), 1, isVisible: false)
+                }
+            };
+
+            tasks[0] = animation.RunAsync(from, null, cancellationToken);
+        }
+
+        if (to != null)
+        {
+            to.IsVisible = true;
+            var animation = new Animation
+            {
+                Easing = SlideInEasing,
+                Duration = Duration,
+                FillMode = FillMode.Forward,
+                Children =
+                {
+                    CreateKeyFrame(0d, 90d * (forward ? 1 : -1), 1),
+                    CreateKeyFrame(0.5d, 45d * (forward ? 1 : -1), 1),
+                    CreateKeyFrame(1d, 0d, 2)
+                }
+            };
+
+            tasks[from != null ? 1 : 0] = animation.RunAsync(to, null, cancellationToken);
+        }
+
+        await Task.WhenAll(tasks);
+
+        if (!cancellationToken.IsCancellationRequested)
+        {
+            if (to != null)
+            {
+                to.ZIndex = 2;
+            }
+            
+            if (from != null)
+            {
+                from.IsVisible = false;
+                from.ZIndex = 1;
+            }
+        }
+    }
+}

+ 1 - 1
src/Avalonia.Base/AvaloniaPropertyChangedEventArgs.cs

@@ -55,7 +55,7 @@ namespace Avalonia
         /// </summary>
         /// <remarks>
         /// This will usually be true, except in
-        /// <see cref="AvaloniaObject.OnPropertyChangedCore{T}(AvaloniaPropertyChangedEventArgs{T})"/>
+        /// <see cref="AvaloniaObject.OnPropertyChangedCore(AvaloniaPropertyChangedEventArgs)"/>
         /// which receives notifications for all changes to property values, whether a value with a higher
         /// priority is present or not. When this property is false, the change that is being signaled
         /// has not resulted in a change to the property value on the object.

+ 6 - 0
src/Avalonia.Base/Collections/AvaloniaList.cs

@@ -394,7 +394,13 @@ namespace Avalonia.Collections
                         } while (en.MoveNext());
 
                         if (notificationItems is not null)
+                        {
                             NotifyAdd(notificationItems, index);
+                        }
+                        else
+                        {
+                            NotifyCountChanged();
+                        }
                     }
                 }
             }

+ 2 - 2
src/Avalonia.Base/Controls/INameScope.cs

@@ -1,5 +1,4 @@
-using System;
-using System.Threading.Tasks;
+using Avalonia.Metadata;
 using Avalonia.Utilities;
 
 namespace Avalonia.Controls
@@ -7,6 +6,7 @@ namespace Avalonia.Controls
     /// <summary>
     /// Defines a name scope.
     /// </summary>
+    [NotClientImplementable]
     public interface INameScope
     {
         /// <summary>

+ 2 - 0
src/Avalonia.Base/Controls/IPseudoClasses.cs

@@ -1,9 +1,11 @@
+using Avalonia.Metadata;
 
 namespace Avalonia.Controls
 {
     /// <summary>
     /// Exposes an interface for setting pseudoclasses on a <see cref="Classes"/> collection.
     /// </summary>
+    [NotClientImplementable]
     public interface IPseudoClasses
     {
         /// <summary>

+ 2 - 2
src/Avalonia.Base/Controls/IResourceHost.cs

@@ -1,6 +1,5 @@
 using System;
-
-#nullable enable
+using Avalonia.Metadata;
 
 namespace Avalonia.Controls
 {
@@ -10,6 +9,7 @@ namespace Avalonia.Controls
     /// <remarks>
     /// This interface is implemented by <see cref="StyledElement"/> and `Application`.
     /// </remarks>
+    [NotClientImplementable]
     public interface IResourceHost : IResourceNode
     {
         /// <summary>

+ 2 - 2
src/Avalonia.Base/Controls/IResourceNode.cs

@@ -1,6 +1,5 @@
 using System;
-
-#nullable enable
+using Avalonia.Metadata;
 
 namespace Avalonia.Controls
 {
@@ -12,6 +11,7 @@ namespace Avalonia.Controls
     /// (<see cref="IResourceHost"/>) and resource providers such as <see cref="ResourceDictionary"/>
     /// (see <see cref="IResourceProvider"/>).
     /// </remarks>
+    [NotClientImplementable]
     public interface IResourceNode
     {
         /// <summary>

+ 2 - 1
src/Avalonia.Base/Controls/ISetInheritanceParent.cs

@@ -1,4 +1,4 @@
-#nullable enable
+using Avalonia.Metadata;
 
 namespace Avalonia.Controls
 {
@@ -10,6 +10,7 @@ namespace Avalonia.Controls
     /// Additionally, <see cref="ISetLogicalParent"/> also sets the inheritance parent; this
     /// interface is only needed where the logical and inheritance parents differ.
     /// </remarks>
+    [NotClientImplementable]
     public interface ISetInheritanceParent
     {
         /// <summary>

+ 2 - 2
src/Avalonia.Base/Controls/ISetLogicalParent.cs

@@ -1,6 +1,5 @@
 using Avalonia.LogicalTree;
-
-#nullable enable
+using Avalonia.Metadata;
 
 namespace Avalonia.Controls
 {
@@ -10,6 +9,7 @@ namespace Avalonia.Controls
     /// <remarks>
     /// You should not usually need to use this interface - it is for advanced scenarios only.
     /// </remarks>
+    [NotClientImplementable]
     public interface ISetLogicalParent
     {
         /// <summary>

+ 4 - 7
src/Avalonia.Base/Controls/ResourceNodeExtensions.cs

@@ -40,19 +40,16 @@ namespace Avalonia.Controls
             control = control ?? throw new ArgumentNullException(nameof(control));
             key = key ?? throw new ArgumentNullException(nameof(key));
 
-            IResourceHost? current = control;
+            IResourceNode? current = control;
 
             while (current != null)
             {
-                if (current is IResourceHost host)
+                if (current.TryGetResource(key, out value))
                 {
-                    if (host.TryGetResource(key, out value))
-                    {
-                        return true;
-                    }
+                    return true;
                 }
 
-                current = (current as IStyledElement)?.StylingParent as IResourceHost;
+                current = (current as IStyledElement)?.StylingParent as IResourceNode;
             }
 
             value = null;

+ 23 - 23
src/Avalonia.Base/Data/Core/ExpressionNode.cs

@@ -98,36 +98,36 @@ namespace Avalonia.Data.Core
 
         private void ValueChanged(object? value, bool notify)
         {
-            if (_subscriber is null)
-                return;
-
-            var notification = value as BindingNotification;
-
-            if (notification == null)
+            if (_subscriber is { } subscriber)
             {
-                LastValue = value != null ? new WeakReference<object?>(value) : NullReference;
+                var notification = value as BindingNotification;
+                var next = Next;
 
-                if (Next != null)
+                if (notification == null)
                 {
-                    Next.Target = LastValue;
+                    LastValue = value != null ? new WeakReference<object?>(value) : NullReference;
+                    if (next != null)
+                    {
+                        next.Target = LastValue;
+                    }
+                    else if (notify)
+                    {
+                        subscriber(value);
+                    }
                 }
-                else if (notify)
+                else
                 {
-                    _subscriber(value);
-                }
-            }
-            else
-            {
-                LastValue = notification.Value != null ? new WeakReference<object?>(notification.Value) : NullReference;
+                    LastValue = notification.Value != null ? new WeakReference<object?>(notification.Value) : NullReference;
 
-                if (Next != null)
-                {
-                    Next.Target = LastValue;
-                }
+                    if (next != null)
+                    {
+                        next.Target = LastValue;
+                    }
 
-                if (Next == null || notification.Error != null)
-                {
-                    _subscriber(value);
+                    if (next == null || notification.Error != null)
+                    {
+                        subscriber(value);
+                    }
                 }
             }
         }

+ 2 - 0
src/Avalonia.Base/Data/Core/IPropertyInfo.cs

@@ -1,7 +1,9 @@
 using System;
+using Avalonia.Metadata;
 
 namespace Avalonia.Data.Core
 {
+    [NotClientImplementable]
     public interface IPropertyInfo
     {
         string Name { get; }

+ 12 - 7
src/Avalonia.Base/Data/Core/Plugins/InpcPropertyAccessorPlugin.cs

@@ -17,7 +17,7 @@ namespace Avalonia.Data.Core.Plugins
             new Dictionary<(Type, string), PropertyInfo?>();
 
         /// <inheritdoc/>
-        public bool Match(object obj, string propertyName) => GetFirstPropertyWithName(obj.GetType(), propertyName) != null;
+        public bool Match(object obj, string propertyName) => GetFirstPropertyWithName(obj, propertyName) != null;
 
         /// <summary>
         /// Starts monitoring the value of a property on an object.
@@ -36,7 +36,7 @@ namespace Avalonia.Data.Core.Plugins
             if (!reference.TryGetTarget(out var instance) || instance is null)
                 return null;
 
-            var p = GetFirstPropertyWithName(instance.GetType(), propertyName);
+            var p = GetFirstPropertyWithName(instance, propertyName);
 
             if (p != null)
             {
@@ -50,8 +50,16 @@ namespace Avalonia.Data.Core.Plugins
             }
         }
 
-        private PropertyInfo? GetFirstPropertyWithName(Type type, string propertyName)
+        private const BindingFlags PropertyBindingFlags =
+            BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
+        
+        private PropertyInfo? GetFirstPropertyWithName(object instance, string propertyName)
         {
+            if (instance is IReflectableType reflectableType)
+                return reflectableType.GetTypeInfo().GetProperty(propertyName, PropertyBindingFlags);
+
+            var type = instance.GetType();
+            
             var key = (type, propertyName);
 
             if (!_propertyLookup.TryGetValue(key, out var propertyInfo))
@@ -66,10 +74,7 @@ namespace Avalonia.Data.Core.Plugins
         {
             PropertyInfo? found = null;
 
-            const BindingFlags bindingFlags =
-                BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
-
-            var properties = type.GetProperties(bindingFlags);
+            var properties = type.GetProperties(PropertyBindingFlags);
 
             foreach (PropertyInfo propertyInfo in properties)
             {

+ 3 - 0
src/Avalonia.Base/Data/IBinding.cs

@@ -1,8 +1,11 @@
+using Avalonia.Metadata;
+
 namespace Avalonia.Data
 {
     /// <summary>
     /// Holds a binding that can be applied to a property on an object.
     /// </summary>
+    [NotClientImplementable]
     public interface IBinding
     {
         /// <summary>

+ 2 - 3
src/Avalonia.Base/DirectPropertyBase.cs

@@ -2,7 +2,6 @@
 using Avalonia.Data;
 using Avalonia.Reactive;
 using Avalonia.Styling;
-using Avalonia.Utilities;
 
 namespace Avalonia
 {
@@ -188,10 +187,10 @@ namespace Avalonia
             }
             else if (value is ITemplate template && !typeof(ITemplate).IsAssignableFrom(PropertyType))
             {
-                return new PropertySetterLazyInstance<TValue>(
+                return new PropertySetterTemplateInstance<TValue>(
                     target,
                     this,
-                    () => (TValue)template.Build());
+                    template);
             }
             else
             {

+ 2 - 0
src/Avalonia.Base/IAvaloniaObject.cs

@@ -1,11 +1,13 @@
 using System;
 using Avalonia.Data;
+using Avalonia.Metadata;
 
 namespace Avalonia
 {
     /// <summary>
     /// Interface for getting/setting <see cref="AvaloniaProperty"/> values on an object.
     /// </summary>
+    [NotClientImplementable]
     public interface IAvaloniaObject
     {
         /// <summary>

+ 2 - 1
src/Avalonia.Base/IDataContextProvider.cs

@@ -1,10 +1,11 @@
-#nullable enable
+using Avalonia.Metadata;
 
 namespace Avalonia
 {
     /// <summary>
     /// Defines an element with a data context that can be used for binding.
     /// </summary>
+    [NotClientImplementable]
     public interface IDataContextProvider : IAvaloniaObject
     {
         /// <summary>

+ 1 - 0
src/Avalonia.Base/IDirectPropertyAccessor.cs

@@ -1,4 +1,5 @@
 using System;
+using Avalonia.Metadata;
 
 namespace Avalonia
 {

+ 3 - 0
src/Avalonia.Base/IDirectPropertyMetadata.cs

@@ -1,8 +1,11 @@
+using Avalonia.Metadata;
+
 namespace Avalonia
 {
     /// <summary>
     /// Untyped interface to <see cref="DirectPropertyMetadata{TValue}"/>
     /// </summary>
+    [NotClientImplementable]
     public interface IDirectPropertyMetadata
     {
         /// <summary>

+ 2 - 2
src/Avalonia.Base/IStyledElement.cs

@@ -2,12 +2,12 @@
 using System.ComponentModel;
 using Avalonia.Controls;
 using Avalonia.LogicalTree;
+using Avalonia.Metadata;
 using Avalonia.Styling;
 
-#nullable enable
-
 namespace Avalonia
 {
+    [NotClientImplementable]
     public interface IStyledElement :
         IStyleable,
         IStyleHost,

+ 3 - 0
src/Avalonia.Base/IStyledPropertyMetadata.cs

@@ -1,8 +1,11 @@
+using Avalonia.Metadata;
+
 namespace Avalonia
 {
     /// <summary>
     /// Untyped interface to <see cref="StyledPropertyMetadata{TValue}"/>
     /// </summary>
+    [NotClientImplementable]
     public interface IStyledPropertyMetadata
     {
         /// <summary>

+ 3 - 0
src/Avalonia.Base/Input/IAccessKeyHandler.cs

@@ -1,8 +1,11 @@
+using Avalonia.Metadata;
+
 namespace Avalonia.Input
 {
     /// <summary>
     /// Defines the interface for classes that handle access keys for a window.
     /// </summary>
+    [Unstable]
     public interface IAccessKeyHandler
     {
         /// <summary>

+ 3 - 0
src/Avalonia.Base/Input/IFocusManager.cs

@@ -1,8 +1,11 @@
+using Avalonia.Metadata;
+
 namespace Avalonia.Input
 {
     /// <summary>
     /// Manages focus for the application.
     /// </summary>
+    [NotClientImplementable]
     public interface IFocusManager
     {
         /// <summary>

+ 2 - 0
src/Avalonia.Base/Input/IInputDevice.cs

@@ -1,7 +1,9 @@
 using Avalonia.Input.Raw;
+using Avalonia.Metadata;
 
 namespace Avalonia.Input
 {
+    [NotClientImplementable]
     public interface IInputDevice
     {
         /// <summary>

+ 2 - 0
src/Avalonia.Base/Input/IInputElement.cs

@@ -1,6 +1,7 @@
 using System;
 using System.Collections.Generic;
 using Avalonia.Interactivity;
+using Avalonia.Metadata;
 using Avalonia.VisualTree;
 
 #nullable enable
@@ -10,6 +11,7 @@ namespace Avalonia.Input
     /// <summary>
     /// Defines input-related functionality for a control.
     /// </summary>
+    [NotClientImplementable]
     public interface IInputElement : IInteractive, IVisual
     {
         /// <summary>

+ 2 - 0
src/Avalonia.Base/Input/IInputManager.cs

@@ -1,5 +1,6 @@
 using System;
 using Avalonia.Input.Raw;
+using Avalonia.Metadata;
 
 namespace Avalonia.Input
 {
@@ -7,6 +8,7 @@ namespace Avalonia.Input
     /// Receives input from the windowing subsystem and dispatches it to interested parties
     /// for processing.
     /// </summary>
+    [NotClientImplementable]
     public interface IInputManager
     {
         /// <summary>

+ 3 - 0
src/Avalonia.Base/Input/IInputRoot.cs

@@ -1,8 +1,11 @@
+using Avalonia.Metadata;
+
 namespace Avalonia.Input
 {
     /// <summary>
     /// Defines the interface for top-level input elements.
     /// </summary>
+    [NotClientImplementable]
     public interface IInputRoot : IInputElement
     {
         /// <summary>

+ 2 - 0
src/Avalonia.Base/Input/IKeyboardDevice.cs

@@ -1,5 +1,6 @@
 using System;
 using System.ComponentModel;
+using Avalonia.Metadata;
 
 namespace Avalonia.Input
 {
@@ -50,6 +51,7 @@ namespace Avalonia.Input
         KeyboardMask = Alt | Control | Shift | Meta
     }
 
+    [NotClientImplementable]
     public interface IKeyboardDevice : IInputDevice, INotifyPropertyChanged
     {
         IInputElement? FocusedElement { get; }

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно