ClassicDesktopEntry.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. using System.Collections.Generic;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Avalonia;
  9. using Avalonia.Controls;
  10. using Avalonia.Controls.ApplicationLifetimes;
  11. using Avalonia.Threading;
  12. using PixiEditor.Extensions.Common.Localization;
  13. using PixiEditor.Extensions.Runtime;
  14. using PixiEditor.Helpers;
  15. using PixiEditor.Models.Controllers;
  16. using PixiEditor.Models.Dialogs;
  17. using PixiEditor.Models.ExceptionHandling;
  18. using PixiEditor.Models.IO;
  19. using PixiEditor.OperatingSystem;
  20. using PixiEditor.PixiAuth;
  21. using PixiEditor.Platform;
  22. using PixiEditor.Views;
  23. using PixiEditor.Views.Dialogs;
  24. using ViewModelMain = PixiEditor.ViewModels.ViewModelMain;
  25. using ViewModels_ViewModelMain = PixiEditor.ViewModels.ViewModelMain;
  26. namespace PixiEditor.Initialization;
  27. internal class ClassicDesktopEntry
  28. {
  29. public static ClassicDesktopEntry? Active { get; private set; }
  30. private bool restartQueued;
  31. private IClassicDesktopStyleApplicationLifetime desktop;
  32. public ClassicDesktopEntry(IClassicDesktopStyleApplicationLifetime desktop)
  33. {
  34. this.desktop = desktop;
  35. IActivatableLifetime? activable =
  36. (IActivatableLifetime?)App.Current.TryGetFeature(typeof(IActivatableLifetime));
  37. Active = this;
  38. if (activable != null)
  39. {
  40. activable.Activated += ActivableOnActivated;
  41. }
  42. desktop.Startup += Start;
  43. desktop.ShutdownRequested += ShutdownRequested;
  44. }
  45. private void ActivableOnActivated(object? sender, ActivatedEventArgs e)
  46. {
  47. if (e.Kind == ActivationKind.File && e is FileActivatedEventArgs fileActivatedEventArgs)
  48. {
  49. IOperatingSystem.Current.HandleActivatedWithFile(fileActivatedEventArgs);
  50. }
  51. else if (e.Kind == ActivationKind.OpenUri && e is ProtocolActivatedEventArgs openUriEventArgs)
  52. {
  53. IOperatingSystem.Current.HandleActivatedWithUri(openUriEventArgs);
  54. }
  55. }
  56. private void Start(object? sender, ControlledApplicationLifetimeStartupEventArgs e)
  57. {
  58. StartupArgs.Args = e.Args.ToList();
  59. string arguments = string.Join(' ', e.Args);
  60. InitOperatingSystem();
  61. bool safeMode = arguments.Contains("--safeMode", StringComparison.OrdinalIgnoreCase);
  62. if (ParseArgument(@"--crash (""?)([\w:\/\ -_.]+)\1", arguments, out Group[] groups))
  63. {
  64. try
  65. {
  66. CrashReport report = CrashReport.Parse(groups[2].Value);
  67. desktop.MainWindow = new CrashReportDialog(report);
  68. desktop.MainWindow.Show();
  69. }
  70. catch (Exception exception)
  71. {
  72. try
  73. {
  74. CrashHelper.SendExceptionInfo(exception, true);
  75. }
  76. finally
  77. {
  78. // TODO: find an avalonia replacement for messagebox
  79. //MessageBox.Show("Fatal error", $"Fatal error while trying to open crash report in App.OnStartup()\n{exception}");
  80. }
  81. }
  82. return;
  83. }
  84. #if !STEAM && !DEBUG
  85. if (!HandleNewInstance(Dispatcher.UIThread))
  86. {
  87. return;
  88. }
  89. #endif
  90. var extensionLoader = InitApp(safeMode);
  91. desktop.MainWindow = new MainWindow(extensionLoader);
  92. desktop.MainWindow.Show();
  93. }
  94. private void InitPlatform()
  95. {
  96. var platform = GetActivePlatform();
  97. IPlatform.RegisterPlatform(platform);
  98. platform.PerformHandshake();
  99. }
  100. public ExtensionLoader InitApp(bool safeMode)
  101. {
  102. LoadingWindow.ShowInNewThread();
  103. InitPlatform();
  104. ExtensionLoader extensionLoader = new ExtensionLoader(Paths.ExtensionPackagesPath, Paths.UserExtensionsPath);
  105. if (!safeMode)
  106. {
  107. extensionLoader.LoadExtensions();
  108. }
  109. return extensionLoader;
  110. }
  111. public void Restart()
  112. {
  113. restartQueued = true;
  114. desktop.TryShutdown();
  115. }
  116. private IPlatform GetActivePlatform()
  117. {
  118. #if STEAM || DEV_STEAM
  119. return new PixiEditor.Platform.Steam.SteamPlatform();
  120. #elif MSIX || MSIX_DEBUG
  121. return new PixiEditor.Platform.MSStore.MicrosoftStorePlatform();
  122. #else
  123. return new PixiEditor.Platform.Standalone.StandalonePlatform(Paths.ExtensionPackagesPath, GetApiUrl());
  124. #endif
  125. }
  126. private void InitOperatingSystem()
  127. {
  128. IOperatingSystem.RegisterOS(GetActiveOperatingSystem());
  129. }
  130. private IOperatingSystem GetActiveOperatingSystem()
  131. {
  132. #if WINDOWS
  133. return new PixiEditor.Windows.WindowsOperatingSystem();
  134. #elif LINUX
  135. return new PixiEditor.Linux.LinuxOperatingSystem();
  136. #elif MACOS
  137. return new PixiEditor.MacOs.MacOperatingSystem();
  138. #else
  139. throw new PlatformNotSupportedException("This platform is not supported");
  140. #endif
  141. }
  142. private bool HandleNewInstance(Dispatcher? dispatcher)
  143. {
  144. return IOperatingSystem.Current.HandleNewInstance(dispatcher, OpenInExisting, desktop);
  145. }
  146. private void OpenInExisting(string passedArgs, bool isInline)
  147. {
  148. if (desktop.MainWindow is MainWindow mainWindow)
  149. {
  150. mainWindow.BringIntoView();
  151. List<string> args = new List<string>();
  152. if (isInline)
  153. {
  154. args = CommandLineHelpers.SplitCommandLine(passedArgs)
  155. .ToList();
  156. }
  157. else if (File.Exists(passedArgs))
  158. {
  159. args = CommandLineHelpers.SplitCommandLine(File.ReadAllText(passedArgs))
  160. .ToList();
  161. File.Delete(passedArgs);
  162. }
  163. StartupArgs.Args = args;
  164. StartupArgs.Args.Add("--openedInExisting");
  165. ViewModels_ViewModelMain viewModel = (ViewModels_ViewModelMain)mainWindow.DataContext;
  166. viewModel.OnStartup();
  167. }
  168. }
  169. private bool ParseArgument(string pattern, string args, out Group[] groups)
  170. {
  171. Match match = Regex.Match(args, pattern, RegexOptions.IgnoreCase);
  172. groups = null;
  173. if (match.Success)
  174. {
  175. groups = match.Groups.Values.ToArray();
  176. }
  177. return match.Success;
  178. }
  179. private void ShutdownRequested(object? sender, ShutdownRequestedEventArgs e)
  180. {
  181. // TODO: Make sure this works
  182. var vm = ViewModels_ViewModelMain.Current;
  183. if (vm is null)
  184. return;
  185. e.Cancel = true;
  186. Dispatcher.UIThread.InvokeAsync(async () =>
  187. {
  188. await vm.CloseWindow();
  189. if (vm.DocumentManagerSubViewModel.Documents.Any(x => !x.AllChangesSaved))
  190. {
  191. await Dispatcher.UIThread.InvokeAsync(async () =>
  192. {
  193. ConfirmationType confirmation = await ConfirmationDialog.Show(
  194. new LocalizedString("SESSION_UNSAVED_DATA", "Shutdown"),
  195. $"Shutdown");
  196. if (confirmation == ConfirmationType.Yes)
  197. {
  198. if (restartQueued)
  199. {
  200. var process = Process.GetCurrentProcess().MainModule.FileName;
  201. desktop.Exit += (_, _) =>
  202. {
  203. Process.Start(process);
  204. };
  205. }
  206. desktop.Shutdown();
  207. }
  208. else
  209. {
  210. restartQueued = false;
  211. }
  212. });
  213. }
  214. else
  215. {
  216. if (restartQueued)
  217. {
  218. var process = Process.GetCurrentProcess().MainModule.FileName;
  219. desktop.Exit += (_, _) =>
  220. {
  221. Process.Start(process);
  222. };
  223. }
  224. desktop.Shutdown();
  225. }
  226. });
  227. }
  228. private string GetApiUrl()
  229. {
  230. string baseUrl = BuildConstants.PixiEditorApiUrl;
  231. #if DEBUG
  232. if (baseUrl.Contains('{') && baseUrl.Contains('}'))
  233. {
  234. string? envUrl = Environment.GetEnvironmentVariable("PIXIAUTH_API_URL");
  235. if (envUrl != null)
  236. {
  237. baseUrl = envUrl;
  238. }
  239. }
  240. #endif
  241. return baseUrl;
  242. }
  243. }