Skip to content

Commit

Permalink
add macOS igonre, fix macOS notifyIcon
Browse files Browse the repository at this point in the history
  • Loading branch information
AigioL committed Feb 28, 2021
1 parent f9681b6 commit 6793f7a
Show file tree
Hide file tree
Showing 20 changed files with 223 additions and 57 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -338,4 +338,6 @@ ASALocalRun/
.localhistory/

# BeatPulse healthcheck temp database
healthchecksdb
healthchecksdb

.DS_Store
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
#if WINDOWS
using System.Windows.Shell;
using WpfApplication = System.Windows.Application;
#elif MAC
using MonoMac.AppKit;
#endif

namespace System.Application.UI
Expand Down Expand Up @@ -60,10 +62,12 @@ public override void OnFrameworkInitializationCompleted()

if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
if (!AppHelper.IsOfficialChannelPackage)
{
IsNotOfficialChannelPackageWarning();
}
#if MAC
NSApplication.Init();
var appDelegate = DI.Get<AppDelegate>();
//AvaloniaLocator.CurrentMutable.Bind<AppDelegate>().ToConstant(appDelegate);
NSApplication.SharedApplication.Delegate = appDelegate;
#endif

#region NotifyIcon

Expand Down Expand Up @@ -115,6 +119,11 @@ public override void OnFrameworkInitializationCompleted()
AddJumpTask();
#endif

if (!AppHelper.IsOfficialChannelPackage)
{
IsNotOfficialChannelPackageWarning();
}

desktop.MainWindow = MainWindow;
desktop.Exit += ApplicationLifetime_Exit;
desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
Expand All @@ -126,6 +135,9 @@ public override void OnFrameworkInitializationCompleted()
void ApplicationLifetime_Exit(object? sender, ControlledApplicationLifetimeExitEventArgs e)
{
compositeDisposable.Dispose();
#if WINDOWS
WpfApplication.Current.Shutdown();
#endif
}

void NotifyIcon_Click(object? sender, EventArgs e)
Expand Down Expand Up @@ -175,9 +187,6 @@ public static void Shutdown()
{
desktop.Shutdown(0);
}
#if WINDOWS
WpfApplication.Current.Shutdown();
#endif
}

#region IDisposable members
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Avalonia;
using Avalonia.ReactiveUI;
using NLog;
using System.IO;
using System.Threading.Tasks;

namespace System.Application.UI
Expand All @@ -13,6 +14,8 @@ static class Program
[STAThread]
static void Main(string[] args)
{
FixNLogConfig();

// 目前桌面端默认使用 SystemTextJson 如果出现兼容性问题可取消下面这行代码
// Serializable.DefaultJsonImplType = Serializable.JsonImplType.NewtonsoftJson;

Expand Down Expand Up @@ -49,5 +52,30 @@ static AppBuilder BuildAvaloniaApp()
.With(new Win32PlatformOptions { AllowEglInitialization = true })
.LogToTrace()
.UseReactiveUI();

static void FixNLogConfig()
{
const char directorySeparatorChar = '\\';
if (Path.DirectorySeparatorChar != directorySeparatorChar)
{
const string fileName = "nlog.config";
var filePath = Path.Combine(AppContext.BaseDirectory, fileName);
if (File.Exists(filePath))
{
string logConfigStr;
try
{
logConfigStr = File.ReadAllText(filePath);
}
catch
{
return;
}
logConfigStr = logConfigStr.Replace(@"logs\", $"logs{Path.DirectorySeparatorChar}");
File.Delete(filePath);
File.WriteAllText(filePath, logConfigStr);
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<DefineConstants>PUBLISH;$(DefineConstants)</DefineConstants>
<DefineConstants>MAC;PUBLISH;$(DefineConstants)</DefineConstants>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>bin\Release\Publish\osx-x64</PublishDir>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
<TargetFramework>net5.0-windows</TargetFramework>
</PropertyGroup>

<PropertyGroup Condition=" $(RuntimeIdentifier.Contains(`osx`)) Or ('$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::OSX)))' == 'true' And !$(DefineConstants.Contains(`PUBLISH`))) ">
<DefineConstants>MAC;$(DefineConstants)</DefineConstants>
</PropertyGroup>

<ItemGroup>
<Compile Include="..\System.Common.CoreLib\Properties\AssemblyInfo.cs">
<Link>Properties\AssemblyInfo.cs</Link>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<TargetFramework>netstandard2.1</TargetFramework>
<RootNamespace>System</RootNamespace>
<SignAssembly>false</SignAssembly>
<!--(SignAssembly)对此程序集进行签名会导致编译失败(CompileAvaloniaXamlTask)-->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@ public string GetCommandLineArgs(Process process)
return string.Empty;
}

public const string kate = "kate";
public const string vi = "vi";

public string? GetFileName(TextReaderProvider provider)
{
return null;
return vi;
}

public void SetBootAutoStart(bool isAutoStart, string name)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ void UpdateMenu()
new LinuxTrayIcon<TContextMenu>(ToolTipText, IconPath, ContextMenu));
}
, canTok.Token, TaskCreationOptions.AttachedToParent, TaskScheduler.Default);
}, MainThreadDesktop.DispatcherPriority.MaxValue);
}, MainThreadDesktop.DispatcherPriority.MaxValue, true);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<TargetFramework>netstandard2.1</TargetFramework>
<RootNamespace>System</RootNamespace>
</PropertyGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,32 @@ public string GetCommandLineArgs(Process process)
return string.Empty;
}

void IDesktopPlatformService.StartProcess(string name, string filePath)
{
var p = Process.Start(new ProcessStartInfo
{
FileName = "open",
Arguments = $"-a \"{name}\" \"{filePath}\"",
});
p?.Close();
}

public string? GetFileName(TextReaderProvider provider)
{
return null;
switch (provider)
{
case TextReaderProvider.VSCode:
return "Visual Studio Code";
case TextReaderProvider.Notepad:
case TextReaderProvider.NotepadPlusPlus:
return "TextEdit";
default:
return null;
}
}

public void SetBootAutoStart(bool isAutoStart, string name)
{

}

public string? GetSteamDirPath()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using MonoMac.AppKit;
using MonoMac.Foundation;

namespace System.Application.UI
{
/// <summary>
/// This class is an AppDelegate helper specifically for Mac OSX
/// Int it's infinite wisdom and unlike Linux and or Windows Mac does not pass in the URL from a sqrl:// invokation
/// directly as a startup app paramter, instead it uses a System Event to do this which has to be registered
/// and listed to.
/// This requires us to use MonoMac to make it work with .net core
/// </summary>
[Register("AppDelegate")]
public sealed class AppDelegate : NSApplicationDelegate
{
public AppDelegate()
{
Init();
}

/// <summary>
/// Registers an event for handling URL Invokation
/// </summary>
void Init()
{
//Register this Apple Delegate globablly with Avalonia for Later Use
NSAppleEventManager.SharedAppleEventManager.SetEventHandler(this, new MonoMac.ObjCRuntime.Selector("handleGetURLEvent:withReplyEvent:"), AEEventClass.Internet, AEEventID.GetUrl);
}

/// <summary>
/// Because we are creating our own mac application delegate we are removing / overriding
/// the one that Avalonia creates. This causes the application to not be handled as it should.
/// This is the Avalonia Implementation: https://github.com/AvaloniaUI/Avalonia/blob/5a2ef35dacbce0438b66d9f012e5f629045beb3d/native/Avalonia.Native/src/OSX/app.mm
/// So what we are doing here is re-creating this implementation to mimick their behavior.
/// </summary>
/// <param name="notification"></param>
public override void WillFinishLaunching(NSNotification notification)
{
if (NSApplication.SharedApplication.ActivationPolicy != NSApplicationActivationPolicy.Regular)
{
foreach (var x in NSRunningApplication.GetRunningApplications(@"com.apple.dock"))
{
x.Activate(NSApplicationActivationOptions.ActivateIgnoringOtherWindows);
break;
}
NSApplication.SharedApplication.ActivationPolicy = NSApplicationActivationPolicy.Regular;
}
}

/// <summary>
/// Because we are creating our own mac application delegate we are removing / overriding
/// the one that Avalonia creates. This causes the application to not be handled as it should.
/// This is the Avalonia Implementation: https://github.com/AvaloniaUI/Avalonia/blob/5a2ef35dacbce0438b66d9f012e5f629045beb3d/native/Avalonia.Native/src/OSX/app.mm
/// So what we are doing here is re-creating this implementation to mimick their behavior.
/// </summary>
/// <param name="notification"></param>
public override void DidFinishLaunching(NSNotification notification)
{
NSRunningApplication.CurrentApplication.Activate(NSApplicationActivationOptions.ActivateIgnoringOtherWindows);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using AppKit;
using MonoMac.AppKit;
using System.Diagnostics.CodeAnalysis;

namespace System.Application.UI
Expand Down Expand Up @@ -99,19 +99,24 @@ public void Remove()
StatusBarItem?.Dispose();
}

void Init()
{
var isMainThread = MainThreadDesktop.IsMainThread;
Console.WriteLine($"isMainThread: {isMainThread}");
var systemStatusBar = NSStatusBar.SystemStatusBar;
StatusBarItem = systemStatusBar.CreateStatusItem(30);
StatusBarItem.ToolTip = ToolTipText;
}

/// <summary>
/// Creates a new <c>NotifyIcon</c> instance and sets up some
/// required resources.
/// </summary>

public NotifyIcon()
{
MainThreadDesktop.BeginInvokeOnMainThread(() =>
{
var systemStatusBar = NSStatusBar.SystemStatusBar;
StatusBarItem = systemStatusBar.CreateStatusItem(30);
StatusBarItem.ToolTip = ToolTipText;
}, MainThreadDesktop.DispatcherPriority.MaxValue);
MainThreadDesktop.BeginInvokeOnMainThread(Init,
MainThreadDesktop.DispatcherPriority.MaxValue, true);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Application.Services;
using System.Application.Services.Implementation;
using System.Application.UI;

// ReSharper disable once CheckNamespace
namespace Microsoft.Extensions.DependencyInjection
Expand All @@ -11,6 +12,7 @@ public static IServiceCollection AddDesktopPlatformService(this IServiceCollecti
{
if (DI.Platform == Platform.Apple)
{
services.AddSingleton<AppDelegate>();
services.AddSingleton<IDesktopPlatformService, MacDesktopPlatformServiceImpl>();
}
else
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<TargetFramework>netstandard2.1</TargetFramework>
<RootNamespace>System</RootNamespace>
</PropertyGroup>

Expand All @@ -12,13 +12,11 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\System.Application.SteamTools.Client.Desktop\System.Application.SteamTools.Client.Desktop.csproj" />
<PackageReference Include="MonoMac.NetStandard" Version="0.0.4" />
</ItemGroup>

<ItemGroup>
<Reference Include="Xamarin.Mac">
<HintPath>$(MSBuildExtensionsPath)\..\Common7\IDE\ReferenceAssemblies\Microsoft\Framework\Xamarin.Mac\v2.0\Xamarin.Mac.dll</HintPath>
</Reference>
<ProjectReference Include="..\System.Application.SteamTools.Client.Desktop\System.Application.SteamTools.Client.Desktop.csproj" />
</ItemGroup>

</Project>
Loading

0 comments on commit 6793f7a

Please sign in to comment.