WindowFunctions.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. using Avalonia;
  2. using Avalonia.Controls;
  3. using Avalonia.Controls.ApplicationLifetimes;
  4. using Avalonia.Input;
  5. using Avalonia.Layout;
  6. using Avalonia.Threading;
  7. using PicView.Avalonia.Input;
  8. using PicView.Avalonia.Interfaces;
  9. using PicView.Avalonia.Navigation;
  10. using PicView.Avalonia.UI;
  11. using PicView.Avalonia.ViewModels;
  12. using PicView.Core.ArchiveHandling;
  13. using PicView.Core.Config;
  14. using PicView.Core.DebugTools;
  15. using PicView.Core.FileHandling;
  16. using PicView.Core.FileHistory;
  17. using PicView.Core.Sizing;
  18. // ReSharper disable CompareOfFloatsByEqualityOperator
  19. namespace PicView.Avalonia.WindowBehavior;
  20. public static class WindowFunctions
  21. {
  22. public static async Task WindowClosingBehavior()
  23. {
  24. if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop)
  25. {
  26. return;
  27. }
  28. await WindowClosingBehavior(desktop.MainWindow);
  29. }
  30. public static async Task WindowClosingBehavior(Window window)
  31. {
  32. WindowResizing.SaveSize(window);
  33. if (Dispatcher.UIThread.CheckAccess())
  34. {
  35. window.Hide();
  36. }
  37. else
  38. {
  39. await Dispatcher.UIThread.InvokeAsync(window.Hide);
  40. }
  41. var vm = window.DataContext as MainViewModel;
  42. string? lastFile;
  43. if (NavigationManager.CanNavigate(vm))
  44. {
  45. if (!string.IsNullOrEmpty(ArchiveExtraction.LastOpenedArchive))
  46. {
  47. lastFile = ArchiveExtraction.LastOpenedArchive;
  48. }
  49. else
  50. {
  51. lastFile = vm?.PicViewer.FileInfo?.CurrentValue.FullName ?? FileHistoryManager.GetLastEntry();
  52. }
  53. }
  54. else
  55. {
  56. var url = vm?.PicViewer.Title?.CurrentValue?.GetURL();
  57. lastFile = !string.IsNullOrWhiteSpace(url) ? url : FileHistoryManager.GetLastEntry();
  58. }
  59. Settings.StartUp.LastFile = lastFile ?? "";
  60. await SaveSettingsAsync();
  61. await KeybindingManager.UpdateKeyBindingsFile(); // Save keybindings
  62. TempFileHelper.DeleteTempFiles();
  63. await FileHistoryManager.SaveToFileAsync();
  64. ArchiveExtraction.Cleanup();
  65. if (vm.Window.SettingsWindowConfig is not null)
  66. {
  67. await vm.Window.SettingsWindowConfig.SaveAsync();
  68. }
  69. if (vm.Window.ImageInfoWindowConfig is not null)
  70. {
  71. await vm.Window.ImageInfoWindowConfig.SaveAsync();
  72. }
  73. if (vm.Window.BatchResizeWindowConfig is not null)
  74. {
  75. await vm.Window.BatchResizeWindowConfig.SaveAsync();
  76. }
  77. Environment.Exit(0);
  78. }
  79. #region Window State
  80. /// <summary>
  81. /// Restores the interface based on settings
  82. /// </summary>
  83. public static void RestoreInterface(MainViewModel vm)
  84. {
  85. vm.MainWindow.IsUIShown.Value = Settings.UIProperties.ShowInterface;
  86. if (!Settings.UIProperties.ShowInterface)
  87. {
  88. return;
  89. }
  90. vm.MainWindow.IsTopToolbarShown.Value = true;
  91. vm.MainWindow.TitlebarHeight.Value = SizeDefaults.MainTitlebarHeight;
  92. if (!Settings.UIProperties.ShowBottomNavBar)
  93. {
  94. return;
  95. }
  96. vm.MainWindow.IsBottomToolbarShown.Value = true;
  97. vm.MainWindow.BottombarHeight.Value = SizeDefaults.BottombarHeight;
  98. }
  99. public static async Task ResizeAndFixRenderingError(MainViewModel vm)
  100. {
  101. await Dispatcher.UIThread.InvokeAsync(() =>
  102. {
  103. if (Settings.WindowProperties.AutoFit)
  104. {
  105. if (vm.PicViewer.PixelWidth.Value > UIHelper.GetMainView.Bounds.Width ||
  106. vm.PicViewer.PixelHeight.Value > UIHelper.GetMainView.Bounds.Height)
  107. {
  108. vm.ImageViewer.MainBorder.Height = double.NaN;
  109. vm.ImageViewer.MainBorder.Width = double.NaN;
  110. WindowResizing.SetSize(1, 1, 0, 0, 0, vm);
  111. }
  112. else
  113. {
  114. WindowResizing.SetSize(vm);
  115. }
  116. CenterWindowOnScreen(false);
  117. }
  118. else
  119. {
  120. WindowResizing.SetSize(vm);
  121. }
  122. if (Settings.WindowProperties.AutoFit)
  123. {
  124. if (Settings.ImageScaling.StretchImage)
  125. {
  126. // Setting horizontal and vertical alignment fixes the rendering error
  127. if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop)
  128. {
  129. return;
  130. }
  131. Dispatcher.UIThread.Post(() => WindowResizing.SetSize(vm), DispatcherPriority.Render);
  132. desktop.MainWindow.HorizontalAlignment = HorizontalAlignment.Center;
  133. desktop.MainWindow.VerticalAlignment = VerticalAlignment.Center;
  134. }
  135. else
  136. {
  137. if (vm.PicViewer.PixelWidth.CurrentValue > UIHelper.GetMainView.Bounds.Width ||
  138. vm.PicViewer.PixelHeight.CurrentValue > UIHelper.GetMainView.Bounds.Height)
  139. {
  140. Dispatcher.UIThread.Post(() => WindowResizing.SetSize(vm), DispatcherPriority.Render);
  141. }
  142. }
  143. }
  144. }, DispatcherPriority.Send);
  145. if (Settings.ImageScaling.StretchImage)
  146. {
  147. if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop)
  148. {
  149. return;
  150. }
  151. Dispatcher.UIThread.Post(() =>
  152. {
  153. WindowResizing.SetSize(vm);
  154. // Reset the horizontal and vertical alignment after fixing the rendering error
  155. desktop.MainWindow.HorizontalAlignment = HorizontalAlignment.Stretch;
  156. desktop.MainWindow.VerticalAlignment = VerticalAlignment.Stretch;
  157. }, DispatcherPriority.Render);
  158. }
  159. }
  160. public static void ShowMinimizedWindow(Window window)
  161. {
  162. window.BringIntoView();
  163. window.WindowState = WindowState.Normal;
  164. window.Activate();
  165. window.Focus();
  166. }
  167. public static async Task ToggleTopMost(MainViewModel vm)
  168. {
  169. if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop)
  170. {
  171. return;
  172. }
  173. if (Settings.WindowProperties.TopMost)
  174. {
  175. vm.GlobalSettings.IsTopMost.Value = false;
  176. desktop.MainWindow.Topmost = false;
  177. Settings.WindowProperties.TopMost = false;
  178. }
  179. else
  180. {
  181. vm.GlobalSettings.IsTopMost.Value = true;
  182. desktop.MainWindow.Topmost = true;
  183. Settings.WindowProperties.TopMost = true;
  184. }
  185. await SaveSettingsAsync().ConfigureAwait(false);
  186. }
  187. public static async Task ToggleAutoFit(MainViewModel vm)
  188. {
  189. if (Settings.WindowProperties.AutoFit)
  190. {
  191. vm.MainWindow.SizeToContent.Value = SizeToContent.Manual;
  192. vm.MainWindow.CanResize.Value = true;
  193. Settings.WindowProperties.AutoFit = false;
  194. vm.GlobalSettings.IsAutoFit.Value = false;
  195. }
  196. else
  197. {
  198. vm.MainWindow.SizeToContent.Value = SizeToContent.WidthAndHeight;
  199. vm.MainWindow.CanResize.Value = false;
  200. Settings.WindowProperties.AutoFit = true;
  201. vm.GlobalSettings.IsAutoFit.Value = true;
  202. // Fix unpleasant window placement
  203. Dispatcher.UIThread.Post(() => { CenterWindowOnScreen(); }, DispatcherPriority.Background);
  204. }
  205. await ResizeAndFixRenderingError(vm);
  206. await SaveSettingsAsync().ConfigureAwait(false);
  207. }
  208. public static async Task AutoFitAndStretch(MainViewModel vm)
  209. {
  210. if (Settings.WindowProperties.AutoFit)
  211. {
  212. vm.MainWindow.SizeToContent.Value = SizeToContent.Manual;
  213. vm.MainWindow.CanResize.Value = true;
  214. Settings.WindowProperties.AutoFit = false;
  215. Settings.ImageScaling.StretchImage = false;
  216. vm.GlobalSettings.IsStretched.Value = false;
  217. vm.GlobalSettings.IsAutoFit.Value = false;
  218. }
  219. else
  220. {
  221. vm.MainWindow.SizeToContent.Value = SizeToContent.WidthAndHeight;
  222. vm.MainWindow.CanResize.Value = false;
  223. Settings.WindowProperties.AutoFit = true;
  224. Settings.ImageScaling.StretchImage = true;
  225. vm.GlobalSettings.IsAutoFit.Value = true;
  226. vm.GlobalSettings.IsStretched.Value = true;
  227. }
  228. await ResizeAndFixRenderingError(vm);
  229. await SaveSettingsAsync().ConfigureAwait(false);
  230. }
  231. public static async Task NormalWindow(MainViewModel vm)
  232. {
  233. vm.MainWindow.SizeToContent.Value = SizeToContent.Manual;
  234. vm.MainWindow.CanResize.Value = true;
  235. Settings.WindowProperties.AutoFit = false;
  236. await WindowResizing.SetSizeAsync(vm);
  237. vm.ImageViewer.MainImage.InvalidateVisual();
  238. await SaveSettingsAsync().ConfigureAwait(false);
  239. }
  240. public static async Task NormalWindowStretch(MainViewModel vm)
  241. {
  242. vm.MainWindow.SizeToContent.Value = SizeToContent.Manual;
  243. vm.MainWindow.CanResize.Value = true;
  244. Settings.WindowProperties.AutoFit = false;
  245. Settings.ImageScaling.StretchImage = true;
  246. vm.GlobalSettings.IsStretched.Value = true;
  247. await WindowResizing.SetSizeAsync(vm);
  248. vm.ImageViewer.MainImage.InvalidateVisual();
  249. await SaveSettingsAsync().ConfigureAwait(false);
  250. }
  251. public static async Task Stretch(MainViewModel vm)
  252. {
  253. if (Settings.ImageScaling.StretchImage)
  254. {
  255. Settings.ImageScaling.StretchImage = false;
  256. vm.GlobalSettings.IsStretched.Value = false;
  257. }
  258. else
  259. {
  260. Settings.ImageScaling.StretchImage = true;
  261. vm.GlobalSettings.IsStretched.Value = true;
  262. }
  263. //vm.ImageViewer.MainImage.InvalidateVisual();
  264. await WindowResizing.SetSizeAsync(vm);
  265. await SaveSettingsAsync().ConfigureAwait(false);
  266. }
  267. public static async Task Minimize()
  268. {
  269. if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop)
  270. {
  271. return;
  272. }
  273. await Dispatcher.UIThread.InvokeAsync(() =>
  274. desktop.MainWindow.WindowState = WindowState.Minimized);
  275. }
  276. public static async Task Close()
  277. {
  278. if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop)
  279. {
  280. return;
  281. }
  282. await Dispatcher.UIThread.InvokeAsync(() =>
  283. desktop.MainWindow.Close());
  284. }
  285. #endregion
  286. #region Window Size and Position
  287. public static void CenterWindowOnScreen(bool horizontal = true, bool top = false)
  288. {
  289. if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop)
  290. {
  291. return;
  292. }
  293. Dispatcher.UIThread.Post(() =>
  294. {
  295. var window = desktop.MainWindow;
  296. if (window.WindowState is WindowState.Maximized or WindowState.FullScreen)
  297. {
  298. return;
  299. }
  300. ScreenHelper.UpdateScreenSize(window);
  301. var screen = ScreenHelper.ScreenSize;
  302. // Get the size of the window
  303. var windowSize = window.ClientSize;
  304. var x = screen.X;
  305. var y = screen.Y;
  306. // Calculate the position to center the window on the screen
  307. var centeredX = x + (screen.WorkingAreaWidth - windowSize.Width) / 2;
  308. var centeredY = y + (top ? 0 : (screen.WorkingAreaHeight - windowSize.Height) / 2);
  309. // Set the window's new position
  310. window.Position = horizontal
  311. ? new PixelPoint((int)centeredX, (int)centeredY)
  312. : new PixelPoint(window.Position.X, (int)centeredY);
  313. });
  314. }
  315. public static void InitializeWindowSizeAndPosition(Window window)
  316. {
  317. if (Dispatcher.UIThread.CheckAccess())
  318. {
  319. window.Position = new PixelPoint((int)Settings.WindowProperties.Left,
  320. (int)Settings.WindowProperties.Top);
  321. window.Width = Settings.WindowProperties.Width;
  322. window.Height = Settings.WindowProperties.Height;
  323. }
  324. else
  325. {
  326. Dispatcher.UIThread.InvokeAsync(() =>
  327. {
  328. window.Position = new PixelPoint((int)Settings.WindowProperties.Left,
  329. (int)Settings.WindowProperties.Top);
  330. window.Width = Settings.WindowProperties.Width;
  331. window.Height = Settings.WindowProperties.Height;
  332. });
  333. }
  334. }
  335. public static void InitializeWindowPosition(Window window, IWindowProperties properties)
  336. {
  337. if (Dispatcher.UIThread.CheckAccess())
  338. {
  339. Set();
  340. }
  341. else
  342. {
  343. Dispatcher.UIThread.InvokeAsync(Set);
  344. }
  345. return;
  346. void Set()
  347. {
  348. if (properties is { Left: not null, Top: not null })
  349. {
  350. window.WindowStartupLocation = WindowStartupLocation.Manual;
  351. window.Position = new PixelPoint(properties.Left.GetValueOrDefault(),
  352. properties.Top.GetValueOrDefault());
  353. }
  354. else
  355. {
  356. window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
  357. }
  358. }
  359. }
  360. public static void InitializeWindowSizeAndPosition(Window window, IWindowProperties properties)
  361. {
  362. if (Dispatcher.UIThread.CheckAccess())
  363. {
  364. Set();
  365. }
  366. else
  367. {
  368. Dispatcher.UIThread.InvokeAsync(Set);
  369. }
  370. return;
  371. void Set()
  372. {
  373. if (properties.Maximized)
  374. {
  375. window.WindowState = WindowState.Maximized;
  376. }
  377. else if (properties is { Left: not null, Top: not null })
  378. {
  379. window.WindowStartupLocation = WindowStartupLocation.Manual;
  380. window.Position = new PixelPoint(properties.Left.GetValueOrDefault(),
  381. properties.Top.GetValueOrDefault());
  382. }
  383. else
  384. {
  385. window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
  386. }
  387. if (properties is not { Width: not null, Height: not null })
  388. {
  389. return;
  390. }
  391. if (properties.Width > window.MinWidth && properties.Width < window.MaxWidth &&
  392. properties.Height > window.MinHeight && properties.Height < window.MaxHeight)
  393. {
  394. window.Width = properties.Width.Value;
  395. window.Height = properties.Height.Value;
  396. }
  397. else
  398. {
  399. DebugHelper.LogDebug(nameof(WindowFunctions), nameof(InitializeWindowSizeAndPosition),
  400. "Invalid width and height values");
  401. }
  402. }
  403. }
  404. public static void SetWindowSize(Window window, AvaloniaPropertyChangedEventArgs<Size> size,
  405. IWindowProperties properties)
  406. {
  407. if (!size.NewValue.HasValue)
  408. {
  409. return;
  410. }
  411. if (size.NewValue.Value == size.OldValue.Value)
  412. {
  413. return;
  414. }
  415. if (size.NewValue.Value.Width < window.MinWidth)
  416. {
  417. return;
  418. }
  419. if (size.NewValue.Value.Height < window.MinHeight)
  420. {
  421. return;
  422. }
  423. properties.Width = window.Bounds.Width;
  424. properties.Height = window.Bounds.Height;
  425. }
  426. #endregion
  427. #region Window Drag and Behavior
  428. public static void WindowDragAndDoubleClickBehavior(Window window, PointerPressedEventArgs e,
  429. IPlatformWindowService platformWindowService)
  430. {
  431. var currentScreen = ScreenHelper.ScreenSize;
  432. var screen = window.Screens.ScreenFromVisual(window);
  433. if (screen == null)
  434. {
  435. return;
  436. }
  437. if (e.ClickCount == 2 && e.GetCurrentPoint(window).Properties.IsLeftButtonPressed)
  438. {
  439. platformWindowService.MaximizeRestore();
  440. return;
  441. }
  442. window.BeginMoveDrag(e);
  443. if (screen.WorkingArea.Width == currentScreen.WorkingAreaWidth &&
  444. screen.WorkingArea.Height == currentScreen.WorkingAreaHeight && screen.Scaling == currentScreen.Scaling)
  445. {
  446. return;
  447. }
  448. ScreenHelper.UpdateScreenSize(window);
  449. WindowResizing.SetSize(window.DataContext as MainViewModel);
  450. }
  451. public static void WindowDragBehavior(Window window, PointerPressedEventArgs e)
  452. {
  453. var currentScreen = ScreenHelper.ScreenSize;
  454. window.BeginMoveDrag(e);
  455. var screen = window.Screens.ScreenFromVisual(window);
  456. if (screen == null)
  457. {
  458. return;
  459. }
  460. if (screen.WorkingArea.Width == currentScreen.WorkingAreaWidth &&
  461. screen.WorkingArea.Height == currentScreen.WorkingAreaHeight && screen.Scaling == currentScreen.Scaling)
  462. {
  463. return;
  464. }
  465. ScreenHelper.UpdateScreenSize(window);
  466. WindowResizing.SetSize(window.DataContext as MainViewModel);
  467. }
  468. #endregion
  469. }