StartUpHelper.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. using System.Diagnostics;
  2. using System.Runtime.InteropServices;
  3. using Avalonia;
  4. using Avalonia.Controls;
  5. using Avalonia.Controls.ApplicationLifetimes;
  6. using Avalonia.Controls.Primitives;
  7. using Avalonia.Threading;
  8. using ImageMagick;
  9. using PicView.Avalonia.ColorManagement;
  10. using PicView.Avalonia.Input;
  11. using PicView.Avalonia.Navigation;
  12. using PicView.Avalonia.SettingsManagement;
  13. using PicView.Avalonia.UI;
  14. using PicView.Avalonia.ViewModels;
  15. using PicView.Avalonia.Views;
  16. using PicView.Avalonia.WindowBehavior;
  17. using PicView.Core.FileAssociations;
  18. using PicView.Core.FileHistory;
  19. using PicView.Core.ProcessHandling;
  20. namespace PicView.Avalonia.StartUp;
  21. public static class StartUpHelper
  22. {
  23. public static void StartWithArguments(MainViewModel vm, bool settingsExists, IClassicDesktopStyleApplicationLifetime desktop,
  24. Window window)
  25. {
  26. var args = Environment.GetCommandLineArgs();
  27. if (settingsExists)
  28. {
  29. if (args.Length > 1)
  30. {
  31. var arg = args[1];
  32. if (arg.StartsWith("associate:", StringComparison.OrdinalIgnoreCase))
  33. {
  34. // Set file associations and exit
  35. Task.Run(async () =>
  36. {
  37. try
  38. {
  39. vm.PlatformService.InitiateFileAssociationService();
  40. Debug.WriteLine($"Processing file association argument: {arg}");
  41. await FileAssociationProcessor.ProcessFileAssociationArguments(arg);
  42. }
  43. catch (Exception ex)
  44. {
  45. Debug.WriteLine($"Error in file association processing: {ex.Message}");
  46. }
  47. finally
  48. {
  49. // Always exit the elevated process after processing associations
  50. Environment.Exit(0);
  51. }
  52. });
  53. }
  54. else
  55. {
  56. if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  57. {
  58. if (Settings.UIProperties.OpenInSameWindow &&
  59. ProcessHelper.CheckIfAnotherInstanceIsRunning())
  60. {
  61. HandleMultipleInstances(args);
  62. }
  63. }
  64. }
  65. }
  66. }
  67. SettingsUpdater.InitializeSettings(vm);
  68. HandleWindowScalingMode(vm, window);
  69. HandleStartUpMenuOrImage(vm, args);
  70. window.Show();
  71. HandlePostWindowUpdates(vm, settingsExists, desktop, window);
  72. }
  73. public static void StartWithoutArguments(MainViewModel vm, bool settingsExists, IClassicDesktopStyleApplicationLifetime desktop,
  74. Window window, string? arg = null)
  75. {
  76. SettingsUpdater.InitializeSettings(vm);
  77. HandleWindowScalingMode(vm, window);
  78. HandleStartUpMenuOrImage(vm, arg);
  79. window.Show();
  80. HandlePostWindowUpdates(vm, settingsExists, desktop, window);
  81. }
  82. private static void HandleWindowScalingMode(MainViewModel vm, Window window)
  83. {
  84. ScreenHelper.UpdateScreenSize(window);
  85. if (Settings.WindowProperties.Margin < 0)
  86. {
  87. Settings.WindowProperties.Margin = 45;
  88. }
  89. if (Settings.WindowProperties.AutoFit)
  90. {
  91. HandleAutoFit(vm, window);
  92. }
  93. else
  94. {
  95. HandleNormalWindow(vm, window);
  96. }
  97. }
  98. private static void HandlePostWindowUpdates(MainViewModel vm, bool settingsExists, IClassicDesktopStyleApplicationLifetime desktop, Window window)
  99. {
  100. ResourceLimits.LimitMemory(new Percentage(90));
  101. Task.Run(() => LanguageUpdater.UpdateLanguageAsync(vm.Translation, vm.PicViewer, settingsExists));
  102. if (settingsExists)
  103. {
  104. Task.Run(() => KeybindingManager.LoadKeybindings(vm.PlatformService));
  105. }
  106. else
  107. {
  108. Task.Run(() => KeybindingManager.SetDefaultKeybindings(vm.PlatformService));
  109. }
  110. Task.Run(FileHistoryManager.InitializeAsync);
  111. HandleThemeUpdates(vm);
  112. UIHelper.SetControls(desktop);
  113. Task.Run(() =>
  114. {
  115. HandleWindowControlSettings(vm, desktop);
  116. SettingsUpdater.ValidateGallerySettings(vm, settingsExists);
  117. });
  118. vm.MainWindow.LayoutButtonSubscription();
  119. SetWindowEventHandlers(window);
  120. MenuManager.AddMenus();
  121. if (!Settings.WindowProperties.AutoFit)
  122. {
  123. // Need to update the screen size after the window is shown,
  124. // to avoid rendering error when switching between auto-fit
  125. ScreenHelper.UpdateScreenSize(window);
  126. }
  127. // Need to delay setting fullscreen or maximized until after the window is shown to select the correct monitor
  128. if (Settings.WindowProperties.Maximized && !Settings.WindowProperties.Fullscreen)
  129. {
  130. Dispatcher.UIThread.InvokeAsync(() =>
  131. {
  132. vm.PlatformWindowService.Maximize(false);
  133. }, DispatcherPriority.Background).Wait();
  134. }
  135. else if (Settings.WindowProperties.Fullscreen)
  136. {
  137. Dispatcher.UIThread.InvokeAsync(() =>
  138. {
  139. vm.PlatformWindowService.Fullscreen(false);
  140. }, DispatcherPriority.Background).Wait();
  141. }
  142. Application.Current.Name = "PicView";
  143. if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  144. {
  145. if (Settings.UIProperties.OpenInSameWindow && !ProcessHelper.CheckIfAnotherInstanceIsRunning())
  146. {
  147. // No other instance is running, create named pipe server
  148. _ = IPC.StartListeningForArguments(vm);
  149. }
  150. }
  151. }
  152. private static void HandleThemeUpdates(MainViewModel vm)
  153. {
  154. if (Settings.Theme.GlassTheme)
  155. {
  156. GlassThemeHelper.GlassThemeUpdates();
  157. }
  158. BackgroundManager.SetBackground(vm);
  159. ColorManager.UpdateAccentColors(Settings.Theme.ColorTheme);
  160. }
  161. private static void HandleWindowControlSettings(MainViewModel vm, IClassicDesktopStyleApplicationLifetime desktop)
  162. {
  163. if (Settings.Zoom.ScrollEnabled)
  164. {
  165. SettingsUpdater.TurnOnScroll(vm);
  166. }
  167. else
  168. {
  169. vm.MainWindow.ToggleScrollBarVisibility.Value = ScrollBarVisibility.Disabled;
  170. vm.GlobalSettings.IsScrollingEnabled.Value = false;
  171. }
  172. if (Settings.WindowProperties.TopMost)
  173. {
  174. desktop.MainWindow.Topmost = true;
  175. }
  176. }
  177. private static void HandleStartUpMenuOrImage(MainViewModel vm, string[] args)
  178. {
  179. vm.ImageViewer = new ImageViewer();
  180. if (args.Length > 1)
  181. {
  182. vm.MainWindow.CurrentView.Value = vm.ImageViewer;
  183. Task.Run(() => QuickLoad.QuickLoadAsync(vm, args[1]));
  184. }
  185. else StartUpMenuOrLastFile(vm);
  186. }
  187. private static void HandleStartUpMenuOrImage(MainViewModel vm, string? arg = null)
  188. {
  189. vm.ImageViewer = new ImageViewer();
  190. if (arg is not null)
  191. {
  192. vm.MainWindow.CurrentView.Value = vm.ImageViewer;
  193. Task.Run(() => QuickLoad.QuickLoadAsync(vm, arg));
  194. }
  195. else StartUpMenuOrLastFile(vm);
  196. }
  197. private static void StartUpMenuOrLastFile(MainViewModel vm)
  198. {
  199. if (Settings.StartUp.OpenLastFile)
  200. {
  201. if (string.IsNullOrWhiteSpace(Settings.StartUp.LastFile))
  202. {
  203. ShowStartUpMenu();
  204. }
  205. else
  206. {
  207. vm.MainWindow.CurrentView.Value = vm.ImageViewer;
  208. Task.Run(() => QuickLoad.QuickLoadAsync(vm, Settings.StartUp.LastFile));
  209. }
  210. }
  211. else
  212. {
  213. ShowStartUpMenu();
  214. }
  215. return;
  216. void ShowStartUpMenu()
  217. {
  218. // Starting it in Dispatcher with post fixes occurrences where the text is not centered or the text is missing
  219. Dispatcher.UIThread.Post(() => { ErrorHandling.ShowStartUpMenu(vm); });
  220. Dispatcher.UIThread.Post(() =>
  221. {
  222. if (Settings.WindowProperties.AutoFit)
  223. {
  224. WindowFunctions.CenterWindowOnScreen();
  225. }
  226. }, DispatcherPriority.Background);
  227. }
  228. }
  229. private static void HandleNormalWindow(MainViewModel vm, Window window)
  230. {
  231. vm.MainWindow.CanResize.Value = true;
  232. vm.GlobalSettings.IsAutoFit.Value = false;
  233. if (Settings.UIProperties.ShowInterface)
  234. {
  235. vm.MainWindow.IsTopToolbarShown.Value = true;
  236. vm.MainWindow.IsBottomToolbarShown.Value = Settings.UIProperties.ShowBottomNavBar;
  237. }
  238. WindowFunctions.InitializeWindowSizeAndPosition(window);
  239. }
  240. private static void HandleAutoFit(MainViewModel vm, Window window)
  241. {
  242. vm.MainWindow.SizeToContent.Value = SizeToContent.WidthAndHeight;
  243. vm.MainWindow.CanResize.Value = false;
  244. vm.GlobalSettings.IsAutoFit.Value = true;
  245. if (Settings.UIProperties.ShowInterface)
  246. {
  247. vm.MainWindow.IsTopToolbarShown.Value = true;
  248. vm.MainWindow.IsBottomToolbarShown.Value = Settings.UIProperties.ShowBottomNavBar;
  249. }
  250. window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
  251. }
  252. private static void HandleMultipleInstances(string[] args)
  253. {
  254. if (args.Length > 1)
  255. {
  256. Task.Run(async () =>
  257. {
  258. var retries = 0;
  259. while (!await IPC.SendArgumentToRunningInstance(args[1]))
  260. {
  261. await Task.Delay(1000);
  262. if (++retries > 20)
  263. {
  264. break;
  265. }
  266. }
  267. Environment.Exit(0);
  268. });
  269. }
  270. }
  271. private static void SetWindowEventHandlers(Window w)
  272. {
  273. w.KeyDown += async (_, e) => await MainKeyboardShortcuts.MainWindow_KeysDownAsync(e).ConfigureAwait(false);
  274. w.KeyUp += (_, e) => MainKeyboardShortcuts.MainWindow_KeysUp(e);
  275. w.PointerPressed += async (_, e) => await MouseShortcuts.MainWindow_PointerPressed(e).ConfigureAwait(false);
  276. w.Deactivated += delegate
  277. {
  278. MainKeyboardShortcuts.Reset();
  279. MainKeyboardShortcuts.ClearKeyDownModifiers();
  280. };
  281. }
  282. }