Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avalonia updates #39

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion build/update-avalonia.csx
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ CopyFile ("Avalonia.Controls/AcrylicPlatformCompensationLevels.cs", "AcrylicPlat
CopyFile ("Avalonia.Native/AvaloniaNativeApplicationPlatform.cs", "Avalonia.Mac/AvaloniaNativeApplicationPlatform.cs");
CopyFile ("Avalonia.Native/AvaloniaNativePlatform.cs", "Avalonia.Mac/AvaloniaNativePlatform.cs");
CopyFile ("Avalonia.Native/AvaloniaNativePlatformExtensions.cs", "Avalonia.Mac/AvaloniaNativePlatformExtensions.cs");
CopyFile ("Avalonia.Native/AvnDispatcher.cs", "Avalonia.Mac/AvnDispatcher.cs");
CopyFile ("Avalonia.Native/CallbackBase.cs", "Avalonia.Mac/CallbackBase.cs");
CopyFile ("Avalonia.Native/ClipboardImpl.cs", "Avalonia.Mac/ClipboardImpl.cs");
CopyFile ("Avalonia.Native/Cursor.cs", "Avalonia.Mac/Cursor.cs");
Expand Down Expand Up @@ -177,7 +178,9 @@ CopyFile ("Windows/Avalonia.Win32/WindowImpl.AppWndProc.cs", "Avalonia.Win32/Win
CopyFile ("Windows/Avalonia.Win32/Input/WindowsKeyboardDevice.cs", "Avalonia.Win32/WindowsKeyboardDevice.cs");
CopyFile ("Windows/Avalonia.Win32/Input/WindowsMouseDevice.cs", "Avalonia.Win32/WindowsMouseDevice.cs");
CopyFile ("Windows/Avalonia.Win32/WinScreen.cs", "Avalonia.Win32/WinScreen.cs");
CopyFile ("Windows/Avalonia.Win32/WinRT/Composition/WinUiCompositionShared.cs", "Avalonia.Win32/WinUiCompositionShared.cs");
CopyFile ("Windows/Avalonia.Win32/Win32DispatcherImpl.cs", "Avalonia.Win32/Win32DispatcherImpl.cs");
CopyFile ("Windows/Avalonia.Win32/Win32PlatformOptions.cs", "Avalonia.Win32/Win32PlatformOptions.cs");
CopyFile ("Windows/Avalonia.Win32/Win32PlatformSettings.cs", "Avalonia.Win32/Win32PlatformSettings.cs");
CopyFile ("Windows/Avalonia.Win32/Win32StorageProvider.cs", "Avalonia.Win32/Win32StorageProvider.cs");
CopyFile ("Windows/Avalonia.Win32/Win32TypeExtensions.cs", "Avalonia.Win32/Win32TypeExtensions.cs");
Expand Down Expand Up @@ -347,7 +350,7 @@ private void CopyFile (string src, string dst)
text = text.Replace ("AvaloniaNativePlatformOptions opts,", "AvaloniaNativePlatformOptions opts)");
text = text.Replace ("IAvnScreens screens, IGlContext glContext", "IAvnScreens screens");
text = text.Replace ("_inputRoot, text)", "_inputRoot, text, RawInputModifiers.None)");
text = text.Replace ("AvaloniaLocator.Current.GetService<IKeyboardDevice>()", "AvaloniaNativePlatform.KeyboardDevice");
text = text.Replace ("{ new GlPlatformSurface(window), new MetalPlatformSurface(window), this };", "{ /*new GlPlatformSurface(window), new MetalPlatformSurface(window), */ this };");
break;
case "WindowImpl.AppWndProc.cs": // Win
text = text.Replace ("new RawTextInputEventArgs(WindowsKeyboardDevice.Instance, timestamp, Owner, text);", "new RawTextInputEventArgs(WindowsKeyboardDevice.Instance, timestamp, Owner, text, WindowsKeyboardDevice.Instance.Modifiers);");
Expand Down
36 changes: 21 additions & 15 deletions samples/Demo/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Modern.WindowKit.Controls.Primitives.PopupPositioning;
using Modern.WindowKit.Input.Raw;
using Modern.WindowKit.Platform;
using Modern.WindowKit.Platform.Storage;
using Modern.WindowKit.Skia;
using Modern.WindowKit.Threading;
using SkiaSharp;
Expand Down Expand Up @@ -75,7 +76,7 @@ private static void DoPaint(Rect bounds)
// Get the framebuffer for the window
var skia_framebuffer = window.Surfaces.OfType<IFramebufferPlatformSurface>().First();

using var framebuffer = skia_framebuffer.Lock();
using var framebuffer = skia_framebuffer.CreateFramebufferRenderTarget ().Lock();

var framebufferImageInfo = new SKImageInfo(framebuffer.Size.Width, framebuffer.Size.Height,
framebuffer.Format.ToSkColorType(), framebuffer.Format == PixelFormat.Rgb565 ? SKAlphaType.Opaque : SKAlphaType.Premul);
Expand Down Expand Up @@ -145,43 +146,48 @@ private static async void HandleKeyboardInput(RawKeyEventArgs e)
anchor_rect = new SKRect(300, 300, 301, 301);

var popup = window.CreatePopup();
var ppp = new PopupPositionerParameters

if (popup is not null)
{
AnchorRectangle = anchor_rect.Value.ToAvaloniaRect(),
Anchor = PopupAnchor.TopLeft,
Gravity = PopupGravity.BottomRight,
Size = new Size(200, 200),
ConstraintAdjustment = PopupPositionerConstraintAdjustment.None,

};
popup.PopupPositioner.Update(ppp);
popup.Show(true, true);
var ppp = new PopupPositionerParameters
{
AnchorRectangle = anchor_rect.Value.ToAvaloniaRect(),
Anchor = PopupAnchor.TopLeft,
Gravity = PopupGravity.BottomRight,
Size = new Size(200, 200),
ConstraintAdjustment = PopupPositionerConstraintAdjustment.None,

};
popup.PopupPositioner?.Update(ppp);
popup.Show(true, true);
}

//show_diagnostics = !show_diagnostics;
e.Handled = true;
}

if (window is ITopLevelImplWithStorageProvider storageProvider)
if (window.TryGetFeature(typeof(IStorageProvider)) is IStorageProvider storageProvider)
{
// Use F9 key to open a File Open dialog
if (e.Type == RawKeyEventType.KeyDown && e.Key == Modern.WindowKit.Input.Key.F9)
{
var result = await storageProvider.StorageProvider.OpenFilePickerAsync(new Modern.WindowKit.Platform.Storage.FilePickerOpenOptions { });
var result = await storageProvider.OpenFilePickerAsync(new Modern.WindowKit.Platform.Storage.FilePickerOpenOptions { });
open_file = result?.FirstOrDefault()?.Name;
e.Handled = true;
}

// Use F10 key to open a Folder Open dialog
if (e.Type == RawKeyEventType.KeyDown && e.Key == Modern.WindowKit.Input.Key.F10)
{
var result = await storageProvider.StorageProvider.OpenFolderPickerAsync(new Modern.WindowKit.Platform.Storage.FolderPickerOpenOptions { });
var result = await storageProvider.OpenFolderPickerAsync(new Modern.WindowKit.Platform.Storage.FolderPickerOpenOptions { });
open_folder = result?.FirstOrDefault()?.Name;
e.Handled = true;
}

// Use F12 key to open a File Save dialog (F11 is a system key on Mac?)
if (e.Type == RawKeyEventType.KeyDown && e.Key == Modern.WindowKit.Input.Key.F12)
{
var result = await storageProvider.StorageProvider.SaveFilePickerAsync(new Modern.WindowKit.Platform.Storage.FilePickerSaveOptions { });
var result = await storageProvider.SaveFilePickerAsync(new Modern.WindowKit.Platform.Storage.FilePickerSaveOptions { });
save_file = result?.Name;
e.Handled = true;
}
Expand Down
53 changes: 41 additions & 12 deletions src/Modern.WindowKit/Avalonia.Mac/AvaloniaNativePlatform.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
using Modern.WindowKit.Controls.Platform;
using Modern.WindowKit.Input;
using Modern.WindowKit.Input.Platform;
using Modern.WindowKit.MicroCom;
using Modern.WindowKit.Mac.Interop;
//using Modern.WindowKit.OpenGL;
using Modern.WindowKit.Platform;
//using Modern.WindowKit.Rendering;
//using Modern.WindowKit.Rendering.Composition;
Expand All @@ -19,7 +17,7 @@ partial class AvaloniaNativePlatform : IWindowingPlatform
{
private readonly IAvaloniaNativeFactory _factory;
private AvaloniaNativePlatformOptions? _options;
//private AvaloniaNativeGlPlatformGraphics? _platformGl;
//private IPlatformGraphics? _platformGraphics;

[DllImport("libAvaloniaNative")]
static extern IntPtr CreateAvaloniaNative();
Expand Down Expand Up @@ -93,7 +91,7 @@ void DoInitialize(AvaloniaNativePlatformOptions options)
if (_factory.MacOptions != null)
_factory.MacOptions.SetDisableAppDelegate(macOpts.DisableAvaloniaAppDelegate ? 1 : 0);

_factory.Initialize(new GCHandleDeallocator(), applicationPlatform);
_factory.Initialize(new GCHandleDeallocator(), applicationPlatform, new AvnDispatcher());

if (_factory.MacOptions != null)
{
Expand Down Expand Up @@ -124,22 +122,53 @@ void DoInitialize(AvaloniaNativePlatformOptions options)

//AvaloniaLocator.CurrentMutable.Bind<PlatformHotkeyConfiguration>().ToConstant(hotkeys);

//if (_options.UseGpu)
//foreach (var mode in _options.RenderingMode)
//{
// try
// if (mode == AvaloniaNativeRenderingMode.OpenGl)
// {
// _platformGl = new AvaloniaNativeGlPlatformGraphics(_factory.ObtainGlDisplay());
// AvaloniaLocator.CurrentMutable
// .Bind<IPlatformGraphics>().ToConstant(_platformGl);

// try
// {
// _platformGraphics = new AvaloniaNativeGlPlatformGraphics(_factory.ObtainGlDisplay());
// break;
// }
// catch (Exception)
// {
// // ignored
// }
//}
#pragma warning disable CS0618
// else if (mode == AvaloniaNativeRenderingMode.Metal)
#pragma warning restore CS0618
// {
// try
// {
// var metal = new MetalPlatformGraphics(_factory);
// metal.CreateContext().Dispose();
// _platformGraphics = metal;
// }
// catch
// {
// // Ignored
// }
// }
// else if (mode == AvaloniaNativeRenderingMode.Software)
// break;
//}

//if (_platformGraphics != null)
// AvaloniaLocator.CurrentMutable
// .Bind<IPlatformGraphics>().ToConstant(_platformGraphics);

//Compositor = new Compositor(_platformGl, true);

//Compositor = new Compositor(_platformGraphics, true);

AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
}

private void OnProcessExit(object? sender, EventArgs e)
{
AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
_factory.Dispose();
}

//public ITrayIconImpl CreateTrayIcon()
Expand All @@ -149,7 +178,7 @@ void DoInitialize(AvaloniaNativePlatformOptions options)

//public IWindowImpl CreateWindow()
//{
// return new WindowImpl(_factory, _options, _platformGl);
// return new WindowImpl(_factory, _options);
//}

public IWindowImpl CreateEmbeddableWindow()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using Modern.WindowKit.Controls;
using Modern.WindowKit.Native;

Expand All @@ -8,7 +9,9 @@ public static class AvaloniaNativePlatformExtensions
{
//public static AppBuilder UseAvaloniaNative(this AppBuilder builder)
//{
// builder.UseWindowingSubsystem(() =>
// builder
// .UseStandardRuntimePlatformSubsystem()
// .UseWindowingSubsystem(() =>
// {
// var platform = AvaloniaNativePlatform.Initialize(
// AvaloniaLocator.Current.GetService<AvaloniaNativePlatformOptions>() ??
Expand All @@ -25,16 +28,44 @@ public static class AvaloniaNativePlatformExtensions
//}
}

/// <summary>
public enum AvaloniaNativeRenderingMode
{
/// <summary>
/// Avalonia would try to use native OpenGL with GPU rendering.
/// </summary>
OpenGl = 1,
/// <summary>
/// Avalonia is rendered into a framebuffer.
/// </summary>
Software = 2,
/// <summary>
/// Avalonia would try to use Metal with GPU rendering.
/// </summary>
[Obsolete("Experimental, unstable, not for production usage")]
Metal = 3
}

/// </summary>
/// OSX backend options.
/// </summary>
public class AvaloniaNativePlatformOptions
{
/// <summary>
/// Determines whether to use GPU for rendering in your project. The default value is true.
/// Gets or sets Avalonia rendering modes with fallbacks.
/// The first element in the array has the highest priority.
/// The default value is: <see cref="AvaloniaNativeRenderingMode.OpenGl"/>, <see cref="AvaloniaNativeRenderingMode.Software"/>.
/// </summary>
public bool UseGpu { get; set; } = true;

/// <remarks>
/// If application should work on as wide range of devices as possible,
/// at least add <see cref="AvaloniaNativeRenderingMode.Software"/> as a fallback value.
/// </remarks>
/// <exception cref="System.InvalidOperationException">Thrown if no values were matched.</exception>
public IReadOnlyList<AvaloniaNativeRenderingMode> RenderingMode { get; set; } = new[]
{
AvaloniaNativeRenderingMode.OpenGl,
AvaloniaNativeRenderingMode.Software
};

/// <summary>
/// Embeds popups to the window when set to true. The default value is false.
/// </summary>
Expand Down
18 changes: 18 additions & 0 deletions src/Modern.WindowKit/Avalonia.Mac/AvnDispatcher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Modern.WindowKit.Mac.Interop;
using Modern.WindowKit.Threading;
using Modern.WindowKit.MicroCom;

namespace Modern.WindowKit.Native;

class AvnDispatcher : NativeCallbackBase, IAvnDispatcher
{
public void Post(IAvnActionCallback cb)
{
var callback = cb.CloneReference();
Dispatcher.UIThread.Post(() =>
{
using (callback)
callback.Run();
}, DispatcherPriority.Send);
}
}
49 changes: 13 additions & 36 deletions src/Modern.WindowKit/Avalonia.Mac/DeferredFramebuffer.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
using System;
using System.Runtime.InteropServices;
using Modern.WindowKit.Controls.Platform.Surfaces;
using Modern.WindowKit.Mac.Interop;
using Modern.WindowKit.Platform;

namespace Modern.WindowKit.Native
{
internal unsafe class DeferredFramebuffer : ILockedFramebuffer
{
private readonly Func<Action<IAvnWindowBase>, bool> _lockWindow;

public DeferredFramebuffer(Func<Action<IAvnWindowBase>, bool> lockWindow,
private readonly IAvnSoftwareRenderTarget _renderTarget;
private readonly Action<Action<IAvnWindowBase>> _lockWindow;

public DeferredFramebuffer(IAvnSoftwareRenderTarget renderTarget, Action<Action<IAvnWindowBase>> lockWindow,
int width, int height, Vector dpi)
{
_renderTarget = renderTarget;
_lockWindow = lockWindow;
Address = Marshal.AllocHGlobal(width * height * 4);
Size = new PixelSize(width, height);
Expand All @@ -27,54 +30,28 @@ public DeferredFramebuffer(Func<Action<IAvnWindowBase>, bool> lockWindow,
public Vector Dpi { get; set; }
public PixelFormat Format { get; set; }

class Disposer : NativeCallbackBase
{
private IntPtr _ptr;

public Disposer(IntPtr ptr)
{
_ptr = ptr;
}

protected override void Destroyed()
{
if(_ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(_ptr);
_ptr = IntPtr.Zero;
}
}
}

public void Dispose()
{
if (Address == IntPtr.Zero)
return;

if (!_lockWindow(win =>
_lockWindow(win =>
{
var fb = new AvnFramebuffer
{
Data = Address.ToPointer(),
Dpi = new AvnVector
{
X = Dpi.X,
Y = Dpi.Y
},
Dpi = new AvnVector { X = Dpi.X, Y = Dpi.Y },
Width = Size.Width,
Height = Size.Height,
PixelFormat = (AvnPixelFormat)Format.FormatEnum,
Stride = RowBytes
};

using (var d = new Disposer(Address))
{
win.ThreadSafeSetSwRenderedFrame(&fb, d);
}
}))
{
Marshal.FreeHGlobal(Address);
}
_renderTarget.SetFrame(&fb);

});

Marshal.FreeHGlobal(Address);

Address = IntPtr.Zero;
}
Expand Down
Loading
Loading