SingleImageResizeView.axaml.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. using System.Reactive.Linq;
  2. using Avalonia;
  3. using Avalonia.Controls;
  4. using Avalonia.Controls.ApplicationLifetimes;
  5. using Avalonia.Input;
  6. using Avalonia.Threading;
  7. using PicView.Avalonia.FileSystem;
  8. using PicView.Avalonia.Navigation;
  9. using PicView.Avalonia.Resizing;
  10. using PicView.Avalonia.UI;
  11. using PicView.Avalonia.ViewModels;
  12. using PicView.Core.ImageDecoding;
  13. using PicView.Core.Localization;
  14. using ReactiveUI;
  15. namespace PicView.Avalonia.Views;
  16. public partial class SingleImageResizeView : UserControl
  17. {
  18. private double _aspectRatio;
  19. private IDisposable? _imageUpdateSubscription;
  20. private bool _isKeepingAspectRatio = true;
  21. public SingleImageResizeView()
  22. {
  23. InitializeComponent();
  24. Loaded += OnLoaded;
  25. Unloaded += OnUnloaded;
  26. }
  27. private void OnLoaded(object? sender, EventArgs e)
  28. {
  29. if (DataContext is not MainViewModel vm)
  30. {
  31. return;
  32. }
  33. _aspectRatio = (double)vm.PicViewer.PixelWidth / vm.PicViewer.PixelHeight;
  34. RegisterEventHandlers(vm);
  35. _imageUpdateSubscription = vm.PicViewer.WhenAnyValue(x => x.FileInfo)
  36. .ObserveOn(RxApp.MainThreadScheduler)
  37. .Select(x => x is not null)
  38. .Subscribe(_ =>
  39. {
  40. UpdateQualitySliderState();
  41. ShowCancelButton();
  42. });
  43. }
  44. private void OnUnloaded(object? sender, EventArgs e)
  45. {
  46. _imageUpdateSubscription?.Dispose();
  47. }
  48. private void RegisterEventHandlers(MainViewModel vm)
  49. {
  50. UpdateQualitySliderState();
  51. QualitySlider.ValueChanged += (_, _) => ShowResetButton();
  52. SaveButton.Click += async (_, _) => await SaveImage(vm).ConfigureAwait(false);
  53. SaveAsButton.Click += async (_, _) => await SaveImageAs(vm).ConfigureAwait(false);
  54. PixelWidthTextBox.KeyDown += async (_, e) => await SaveImageOnEnter(e, vm);
  55. PixelHeightTextBox.KeyDown += async (_, e) => await SaveImageOnEnter(e, vm);
  56. PixelWidthTextBox.KeyUp += (_, _) => AdjustAspectRatio(PixelWidthTextBox);
  57. PixelHeightTextBox.KeyUp += (_, _) => AdjustAspectRatio(PixelHeightTextBox);
  58. ConversionComboBox.SelectionChanged += (_, _) =>
  59. {
  60. UpdateQualitySliderState();
  61. ShowResetButton();
  62. };
  63. ResetButton.Click += (_, _) => ResetSettings(vm);
  64. CancelButton.Click += (_, _) => (VisualRoot as Window)?.Close();
  65. LinkChainButton.Click += (_, _) => ToggleAspectRatio();
  66. }
  67. private void ShowResetButton()
  68. {
  69. CancelButton.IsVisible = false;
  70. ResetButton.IsVisible = true;
  71. }
  72. private void ShowCancelButton()
  73. {
  74. CancelButton.IsVisible = true;
  75. ResetButton.IsVisible = false;
  76. }
  77. private void AdjustAspectRatio(TextBox sender)
  78. {
  79. if (!_isKeepingAspectRatio)
  80. {
  81. return;
  82. }
  83. AspectRatioHelper.SetAspectRatioForTextBox(
  84. PixelWidthTextBox, PixelHeightTextBox, sender == PixelWidthTextBox,
  85. _aspectRatio, DataContext as MainViewModel);
  86. ShowResetButton();
  87. }
  88. private void UpdateQualitySliderState()
  89. {
  90. if (DataContext is not MainViewModel vm)
  91. {
  92. return;
  93. }
  94. try
  95. {
  96. if (IsConversionToQualityFormat())
  97. {
  98. QualitySlider.IsEnabled = true;
  99. QualitySlider.Value = 75;
  100. }
  101. else if (IsOriginalFileQualityFormat(vm.PicViewer.FileInfo.Extension))
  102. {
  103. QualitySlider.IsEnabled = true;
  104. QualitySlider.Value = ImageAnalyzer.GetCompressionQuality(vm.PicViewer.FileInfo.FullName);
  105. }
  106. else
  107. {
  108. QualitySlider.IsEnabled = false;
  109. }
  110. }
  111. catch (Exception e)
  112. {
  113. #if DEBUG
  114. Console.WriteLine(e);
  115. #endif
  116. }
  117. }
  118. private bool IsConversionToQualityFormat()
  119. => JpgItem.IsSelected || PngItem.IsSelected;
  120. private static bool IsOriginalFileQualityFormat(string ext)
  121. => ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase)
  122. || ext.Equals(".jpeg", StringComparison.OrdinalIgnoreCase)
  123. || ext.Equals(".png", StringComparison.OrdinalIgnoreCase);
  124. private async Task SaveImageOnEnter(KeyEventArgs e, MainViewModel vm)
  125. {
  126. if (e.Key == Key.Enter)
  127. {
  128. await SaveImage(vm).ConfigureAwait(false);
  129. }
  130. }
  131. private async Task SaveImageAs(MainViewModel vm)
  132. {
  133. if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop
  134. || desktop.MainWindow?.StorageProvider is not { } provider)
  135. {
  136. return;
  137. }
  138. var fileInfoFullName = vm.PicViewer.FileInfo.FullName;
  139. var ext = GetSelectedFileExtension(vm, ref fileInfoFullName);
  140. var file = await FilePicker.PickFileForSavingAsync(vm.PicViewer.FileInfo?.FullName, ext);
  141. if (file is null)
  142. {
  143. return;
  144. }
  145. await DoSaveImage(vm, file).ConfigureAwait(false);
  146. }
  147. private async Task SaveImage(MainViewModel vm)
  148. {
  149. await DoSaveImage(vm, vm.PicViewer.FileInfo.FullName).ConfigureAwait(false);
  150. }
  151. private async Task DoSaveImage(MainViewModel vm, string destination)
  152. {
  153. if (!uint.TryParse(PixelWidthTextBox.Text, out var width) ||
  154. !uint.TryParse(PixelHeightTextBox.Text, out var height))
  155. {
  156. return;
  157. }
  158. await Dispatcher.UIThread.InvokeAsync(() => SetLoadingState(true));
  159. const int rotationAngle = 0; // TODO: Add rotation control
  160. var file = vm.PicViewer.FileInfo.FullName;
  161. var ext = GetSelectedFileExtension(vm, ref destination);
  162. destination = Path.ChangeExtension(destination, ext);
  163. var sameFile = file.Equals(destination, StringComparison.OrdinalIgnoreCase);
  164. var quality = GetQualityValue(ext, destination);
  165. var success = await SaveImageFileHelper.SaveImageAsync(
  166. null, file, sameFile ? null : destination, width, height, quality,
  167. ext, rotationAngle, null, _isKeepingAspectRatio).ConfigureAwait(false);
  168. await Dispatcher.UIThread.InvokeAsync(() => SetLoadingState(false));
  169. if (!success)
  170. {
  171. await TooltipHelper.ShowTooltipMessageAsync(TranslationManager.Translation.SavingFileFailed);
  172. return;
  173. }
  174. await HandlePostSaveActions(vm, file, destination);
  175. if (Path.GetExtension(file) != ext)
  176. {
  177. await vm.PlatformService.DeleteFile(file, true);
  178. }
  179. }
  180. private void SetLoadingState(bool isLoading)
  181. {
  182. ParentContainer.Opacity = isLoading ? 0.1 : 1;
  183. ParentContainer.IsHitTestVisible = !isLoading;
  184. SpinWaiter.IsVisible = isLoading;
  185. }
  186. private string GetSelectedFileExtension(MainViewModel vm, ref string destination)
  187. {
  188. var ext = vm.PicViewer.FileInfo.Extension;
  189. if (NoConversion.IsSelected)
  190. {
  191. return ext;
  192. }
  193. ext = GetExtensionFromSelectedItem() ?? ext;
  194. destination = Path.ChangeExtension(destination, ext);
  195. return ext;
  196. }
  197. private string? GetExtensionFromSelectedItem()
  198. {
  199. if (PngItem.IsSelected)
  200. {
  201. return ".png";
  202. }
  203. if (JpgItem.IsSelected)
  204. {
  205. return ".jpg";
  206. }
  207. if (WebpItem.IsSelected)
  208. {
  209. return ".webp";
  210. }
  211. if (AvifItem.IsSelected)
  212. {
  213. return ".avif";
  214. }
  215. if (HeicItem.IsSelected)
  216. {
  217. return ".heic";
  218. }
  219. if (JxlItem.IsSelected)
  220. {
  221. return ".jxl";
  222. }
  223. return null;
  224. }
  225. private uint? GetQualityValue(string ext, string destination)
  226. {
  227. if (QualitySlider.IsEnabled && (
  228. ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase) ||
  229. Path.GetExtension(destination).Equals(".jpg", StringComparison.OrdinalIgnoreCase) ||
  230. Path.GetExtension(destination).Equals(".jpeg", StringComparison.OrdinalIgnoreCase)))
  231. {
  232. return (uint)QualitySlider.Value;
  233. }
  234. return null;
  235. }
  236. private static async Task HandlePostSaveActions(MainViewModel vm, string file, string destination)
  237. {
  238. if (destination == file)
  239. {
  240. await NavigationManager.QuickReload().ConfigureAwait(false);
  241. }
  242. else if (Path.GetDirectoryName(file) == Path.GetDirectoryName(destination))
  243. {
  244. await NavigationManager.LoadPicFromFile(destination, vm).ConfigureAwait(false);
  245. }
  246. }
  247. private void ResetSettings(MainViewModel vm)
  248. {
  249. PixelWidthTextBox.Text = vm.PicViewer.PixelWidth.ToString();
  250. PixelHeightTextBox.Text = vm.PicViewer.PixelHeight.ToString();
  251. if (IsOriginalFileQualityFormat(vm.PicViewer.FileInfo.Extension))
  252. {
  253. QualitySlider.IsEnabled = true;
  254. QualitySlider.Value = ImageAnalyzer.GetCompressionQuality(vm.PicViewer.FileInfo.FullName);
  255. }
  256. else
  257. {
  258. QualitySlider.IsEnabled = false;
  259. }
  260. ConversionComboBox.SelectedItem = NoConversion;
  261. _isKeepingAspectRatio = true;
  262. LinkChainImage.IsVisible = true;
  263. UnlinkChainImage.IsVisible = false;
  264. ShowCancelButton();
  265. }
  266. private void ToggleAspectRatio()
  267. {
  268. _isKeepingAspectRatio = !_isKeepingAspectRatio;
  269. LinkChainImage.IsVisible = _isKeepingAspectRatio;
  270. UnlinkChainImage.IsVisible = !_isKeepingAspectRatio;
  271. if (_isKeepingAspectRatio)
  272. {
  273. AdjustAspectRatio(PixelWidthTextBox);
  274. }
  275. if (!_isKeepingAspectRatio)
  276. {
  277. ShowResetButton();
  278. }
  279. }
  280. ~SingleImageResizeView()
  281. {
  282. _imageUpdateSubscription?.Dispose();
  283. }
  284. }