40 lines
1.1 KiB
C#
40 lines
1.1 KiB
C#
using Avalonia.Controls.ApplicationLifetimes;
|
|
using Avalonia.Controls;
|
|
using Avalonia.Rendering;
|
|
using Avalonia;
|
|
using Avalonia.VisualTree;
|
|
|
|
namespace Harmonia.UI.Platform;
|
|
|
|
public abstract class PlatformServiceLocator<T> : IPlatformServiceLocator<T>
|
|
{
|
|
public T? Get()
|
|
{
|
|
//Desktop
|
|
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
|
{
|
|
if (desktop.MainWindow == null)
|
|
return default;
|
|
|
|
return GetFromWindow(desktop.MainWindow);
|
|
}
|
|
//Android (and iOS?)
|
|
else if (Application.Current?.ApplicationLifetime is ISingleViewApplicationLifetime singleViewPlatform)
|
|
{
|
|
if (singleViewPlatform.MainView == null)
|
|
return default;
|
|
|
|
IRenderRoot? visualRoot = singleViewPlatform.MainView.GetVisualRoot();
|
|
|
|
if (visualRoot is TopLevel topLevel)
|
|
{
|
|
return GetFromTopLevel(topLevel);
|
|
}
|
|
}
|
|
|
|
return default;
|
|
}
|
|
|
|
protected abstract T? GetFromWindow(Window mainWindow);
|
|
protected abstract T? GetFromTopLevel(TopLevel topLevel);
|
|
} |