diff --git a/v2rayN/ServiceLib/Handler/AutoStartupHandler.cs b/v2rayN/ServiceLib/Handler/AutoStartupHandler.cs index e6ac42d3b8a..2858ac232aa 100644 --- a/v2rayN/ServiceLib/Handler/AutoStartupHandler.cs +++ b/v2rayN/ServiceLib/Handler/AutoStartupHandler.cs @@ -1,4 +1,5 @@ -using System.Security.Principal; +using System.Diagnostics; +using System.Security.Principal; using System.Text.RegularExpressions; namespace ServiceLib.Handler @@ -29,7 +30,12 @@ public static async Task UpdateTask(Config config) } else if (Utils.IsOSX()) { - //TODO + await ClearTaskOSX(); + + if (config.GuiItem.AutoRun) + { + await SetTaskOSX(); + } } return true; @@ -161,5 +167,77 @@ private static string GetHomePathLinux() } #endregion Linux + + #region macOS + + private static async Task ClearTaskOSX() + { + try + { + var launchAgentPath = GetLaunchAgentPathMacOS(); + if (File.Exists(launchAgentPath)) + { + var args = new[] { "-c", $"launchctl unload -w \"{launchAgentPath}\"" }; + await Utils.GetCliWrapOutput("/bin/bash", args); + + File.Delete(launchAgentPath); + } + } + catch (Exception ex) + { + Logging.SaveLog(_tag, ex); + } + } + + private static async Task SetTaskOSX() + { + try + { + var plistContent = GenerateLaunchAgentPlist(); + var launchAgentPath = GetLaunchAgentPathMacOS(); + await File.WriteAllTextAsync(launchAgentPath, plistContent); + + var args = new[] { "-c", $"launchctl load -w \"{launchAgentPath}\"" }; + await Utils.GetCliWrapOutput("/bin/bash", args); + } + catch (Exception ex) + { + Logging.SaveLog(_tag, ex); + } + } + + private static string GetLaunchAgentPathMacOS() + { + var homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + var launchAgentPath = Path.Combine(homePath, "Library", "LaunchAgents", $"{Global.AppName}-LaunchAgent.plist"); + Directory.CreateDirectory(Path.GetDirectoryName(launchAgentPath)); + return launchAgentPath; + } + + private static string GenerateLaunchAgentPlist() + { + var exePath = Utils.GetExePath(); + var appName = Path.GetFileNameWithoutExtension(exePath); + return $@" + + + + Label + {Global.AppName}-LaunchAgent + ProgramArguments + + /bin/sh + -c + if ! pgrep -x ""{appName}"" > /dev/null; then ""{exePath}""; fi + + RunAtLoad + + KeepAlive + + +"; + } + + #endregion macOS } -} \ No newline at end of file +} diff --git a/v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs index 35a85bd974d..ebc45bf5290 100644 --- a/v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs @@ -176,13 +176,6 @@ public OptionSettingWindow() txbSettingsExceptionTip.IsVisible = false; panSystemProxyAdvanced.IsVisible = false; } - - if (Utils.IsOSX()) - { - tbAutoRun.IsVisible = false; - togAutoRun.IsVisible = false; - //TODO - } } private async Task UpdateViewHandler(EViewAction action, object? obj)