DocumentViewList.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. using Comal.Classes;
  2. using InABox.Clients;
  3. using InABox.Core;
  4. using InABox.Wpf;
  5. using InABox.WPF;
  6. using PRSDesktop.Panels.DataEntry;
  7. using Syncfusion.Pdf;
  8. using Syncfusion.Pdf.Parsing;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Collections.ObjectModel;
  12. using System.ComponentModel;
  13. using System.Drawing;
  14. using System.Drawing.Imaging;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Runtime.CompilerServices;
  18. using System.Text;
  19. using System.Threading.Tasks;
  20. using System.Windows;
  21. using System.Windows.Controls;
  22. using System.Windows.Data;
  23. using System.Windows.Input;
  24. using System.Windows.Media;
  25. using Image = System.Windows.Controls.Image;
  26. namespace PRSDesktop;
  27. /// <summary>
  28. /// Control that allows to view a list of documents, within a zoom control, and providing methods to rotate/explode data.
  29. /// </summary>
  30. /// <remarks>
  31. /// This is originally from the Data entry panel, and this implementation is a <i>little bit</i> scuffed. Basically, because the <see cref="DataEntryDocument"/>
  32. /// is not an <see cref="EntityDocument{T}"/>, there is no good shared interface, so I made this abstract, with a type argument. Then to get the "EntityDocument"
  33. /// ID or the Document ID, there are abstract functions.
  34. /// <b/>
  35. /// Note one needs also to provide <see cref="UpdateDocument"/>. This is a function used by the "Rotate Image" button, and its implementation needs
  36. /// to update the THumbnail of the Entity Document, and save it, along with refreshing the view list.
  37. /// </remarks>
  38. /// <typeparam name="TDocument"></typeparam>
  39. public abstract class DocumentViewList<TDocument> : UserControl, INotifyPropertyChanged
  40. {
  41. public static readonly DependencyProperty CanRotateImageProperty = DependencyProperty.Register(nameof(CanRotateImage), typeof(bool), typeof(DocumentViewList<TDocument>), new PropertyMetadata(true, CanRotateImage_Changed));
  42. private static void CanRotateImage_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
  43. {
  44. if (d is not DocumentViewList<TDocument> list) return;
  45. list.DoPropertyChanged(e.Property.Name);
  46. }
  47. private IList<TDocument> _documents = [];
  48. public IList<TDocument> Documents
  49. {
  50. get => _documents;
  51. set
  52. {
  53. UpdateViewList(value);
  54. }
  55. }
  56. private readonly object _viewListLock = new object();
  57. private class ViewDocument
  58. {
  59. public ImageSource Image { get; set; }
  60. public TDocument Document { get; set; }
  61. public int PageNumber { get; set; }
  62. public ViewDocument(ImageSource image, TDocument document, int page)
  63. {
  64. Image = image;
  65. Document = document;
  66. PageNumber = page;
  67. }
  68. }
  69. private List<ViewDocument> ViewDocuments { get; } = new();
  70. public ObservableCollection<ImageSource> ViewList { get; init; } = new();
  71. private ZoomPanel ZoomPanel;
  72. private bool _canExplode;
  73. public bool CanExplode
  74. {
  75. get => _canExplode;
  76. set
  77. {
  78. _canExplode = value;
  79. DoPropertyChanged();
  80. }
  81. }
  82. public event Action? Explode;
  83. public event Action? ExplodeAll;
  84. public event Action<TDocument, Document>? UpdateDocument;
  85. public bool CanRotateImage
  86. {
  87. get => (bool)GetValue(CanRotateImageProperty);
  88. set => SetValue(CanRotateImageProperty, value);
  89. }
  90. public DocumentViewList()
  91. {
  92. var border = new Border();
  93. border.BorderBrush = Colors.Gray.ToBrush();
  94. border.Background = Colors.DimGray.ToBrush();
  95. ZoomPanel = new ZoomPanel();
  96. var itemsControl = new ItemsControl();
  97. itemsControl.Margin = new Thickness(10);
  98. itemsControl.ItemsSource = ViewList;
  99. var factory = new FrameworkElementFactory(typeof(StackPanel));
  100. factory.SetValue(StackPanel.OrientationProperty, Orientation.Vertical);
  101. itemsControl.ItemsPanel = new ItemsPanelTemplate(factory);
  102. itemsControl.ContextMenu = new ContextMenu();
  103. var explode = itemsControl.ContextMenu.AddItem("Regroup Pages", null, Explode_Click);
  104. explode.Bind(VisibilityProperty, this, x => x.CanExplode, new InABox.WPF.BooleanToVisibilityConverter(Visibility.Visible, Visibility.Collapsed));
  105. var explodeAll = itemsControl.ContextMenu.AddItem("Explode All Pages", null, ExplodeAll_Click);
  106. explodeAll.Bind(VisibilityProperty, this, x => x.CanExplode, new InABox.WPF.BooleanToVisibilityConverter(Visibility.Visible, Visibility.Collapsed));
  107. var viewImage = new MenuItem()
  108. {
  109. Header = "View Image"
  110. };
  111. viewImage.ToolTip = "Show this image in a separate window.";
  112. viewImage.Bind<ImageSource, ImageSource>(MenuItem.TagProperty, x => x);
  113. viewImage.Click += ViewImage_Click;
  114. itemsControl.ContextMenu.Items.Add(viewImage);
  115. var rotateImage = new MenuItem()
  116. {
  117. Header = "Rotate Document"
  118. };
  119. rotateImage.ToolTip = "Rotate this document 90° clockwise";
  120. rotateImage.Bind<ImageSource, ImageSource>(MenuItem.TagProperty, x => x);
  121. rotateImage.SetBinding(MenuItem.IsEnabledProperty, new Binding("CanRotateImage") { Source = this });
  122. rotateImage.Click += RotateImage_Click;
  123. itemsControl.ContextMenu.Items.Add(rotateImage);
  124. itemsControl.ItemTemplate = TemplateGenerator.CreateDataTemplate(() =>
  125. {
  126. var img = new Image();
  127. img.Bind<ImageSource, ImageSource>(Image.SourceProperty, x => x);
  128. img.ContextMenu = itemsControl.ContextMenu;
  129. img.MouseLeftButtonDown += Img_MouseLeftButtonDown;
  130. return img;
  131. });
  132. ZoomPanel.Content = itemsControl;
  133. border.Child = ZoomPanel;
  134. Content = border;
  135. BindingOperations.EnableCollectionSynchronization(ViewList, _viewListLock);
  136. }
  137. protected abstract Guid GetID(TDocument document);
  138. protected abstract Guid GetDocumentID(TDocument document);
  139. protected abstract IEnumerable<Document> LoadDocuments(IEnumerable<Guid> ids);
  140. public void UpdateViewList(IList<TDocument> documents, bool force = false)
  141. {
  142. if (!force && documents.Count == _documents.Count && !documents.Any(x => _documents.All(y => GetID(x) != GetID(y))))
  143. return;
  144. _documents = documents;
  145. ViewList.Clear();
  146. ViewDocuments.Clear();
  147. if(_documents.Count == 0)
  148. {
  149. return;
  150. }
  151. Task.Run(() =>
  152. {
  153. var docs = LoadDocuments(Documents.Select(GetDocumentID).Distinct());
  154. LoadDocuments(docs);
  155. }).ContinueWith((task) =>
  156. {
  157. if(task.Exception is not null)
  158. {
  159. MessageWindow.ShowError("An error occurred while loading the documents", task.Exception);
  160. }
  161. }, TaskScheduler.FromCurrentSynchronizationContext());
  162. }
  163. private void LoadDocuments(IEnumerable<Document> documents)
  164. {
  165. var bitmaps = new Dictionary<Guid, List<ImageSource>>();
  166. foreach (var document in documents.Where(x=>x.Data?.Any() == true))
  167. {
  168. List<byte[]> images;
  169. var bitmapImages = new List<ImageSource>();
  170. var extension = Path.GetExtension(document.FileName).ToLower();
  171. if (extension == ".pdf")
  172. {
  173. images = new List<byte[]>();
  174. try
  175. {
  176. bitmapImages = ImageUtils.RenderPDFToImageSources(document.Data);
  177. }
  178. catch (Exception e)
  179. {
  180. MessageBox.Show($"Cannot load document '{document.FileName}': {e.Message}");
  181. }
  182. }
  183. else if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
  184. {
  185. images = new List<byte[]> { document.Data };
  186. }
  187. else
  188. {
  189. images = ImageUtils.RenderTextFileToImages(Encoding.UTF8.GetString(document.Data));
  190. }
  191. bitmapImages.AddRange(images.Select(x =>
  192. {
  193. try
  194. {
  195. return ImageUtils.LoadImage(x);
  196. }
  197. catch (Exception e)
  198. {
  199. Dispatcher.BeginInvoke(() =>
  200. {
  201. MessageWindow.ShowError($"Cannot load document '{document.FileName}", e);
  202. });
  203. }
  204. return null;
  205. }).Where(x => x != null).Cast<ImageSource>());
  206. foreach (var image in bitmapImages)
  207. {
  208. if (!bitmaps.TryGetValue(document.ID, out var list))
  209. {
  210. list = new List<ImageSource>();
  211. bitmaps[document.ID] = list;
  212. }
  213. list.Add(image);
  214. }
  215. }
  216. ViewDocuments.Clear();
  217. var maxWidth = 0.0;
  218. foreach (var scan in Documents)
  219. {
  220. if (bitmaps.TryGetValue(GetDocumentID(scan), out var list))
  221. {
  222. int page = 1;
  223. foreach (var bitmap in list)
  224. {
  225. maxWidth = Math.Max(maxWidth, bitmap.Width);
  226. ViewDocuments.Add(new(bitmap, scan, page));
  227. page++;
  228. }
  229. }
  230. }
  231. lock (_viewListLock)
  232. {
  233. ViewList.Clear();
  234. foreach(var doc in ViewDocuments)
  235. {
  236. ViewList.Add(doc.Image);
  237. }
  238. if(maxWidth != 0.0)
  239. {
  240. ZoomPanel.Scale = ZoomPanel.ActualWidth / (maxWidth * 1.1);
  241. ZoomPanel.MinScale = ZoomPanel.Scale / 2;
  242. }
  243. }
  244. }
  245. private void RotateDocument(Document doc, int pageNumber)
  246. {
  247. var extension = Path.GetExtension(doc.FileName).ToLower();
  248. if (extension == ".pdf")
  249. {
  250. var loadeddoc = new PdfLoadedDocument(doc.Data);
  251. bool allPages = loadeddoc.PageCount() > 1;
  252. if (allPages)
  253. {
  254. allPages = MessageWindow.New()
  255. .Message("Do you want to rotate all pages in this PDF?")
  256. .Title("Rotate all?")
  257. .AddYesButton("All pages")
  258. .AddNoButton("Just this page")
  259. .Display().Result == MessageWindowResult.Yes;
  260. }
  261. if(allPages)
  262. {
  263. foreach (var page in loadeddoc.GetPages())
  264. {
  265. var rotation = (int)page.Rotation;
  266. rotation = (rotation + 1) % 4;
  267. page.Rotation = (PdfPageRotateAngle)rotation;
  268. }
  269. }
  270. else if(pageNumber <= loadeddoc.PageCount())
  271. {
  272. var page = loadeddoc.GetPage(pageNumber - 1);
  273. var rotation = (int)page.Rotation;
  274. rotation = (rotation + 1) % 4;
  275. page.Rotation = (PdfPageRotateAngle)rotation;
  276. }
  277. doc.Data = loadeddoc.SaveToBytes();
  278. }
  279. else if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
  280. {
  281. using var stream = new MemoryStream(doc.Data);
  282. var bitmap = Bitmap.FromStream(stream);
  283. bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
  284. using var outStream = new MemoryStream();
  285. bitmap.Save(outStream, extension switch
  286. {
  287. ".jpg" or ".jpeg" => ImageFormat.Jpeg,
  288. ".png" => ImageFormat.Png,
  289. _ => ImageFormat.Bmp
  290. });
  291. doc.Data = outStream.ToArray();
  292. }
  293. else
  294. {
  295. using var stream = new MemoryStream(doc.Data);
  296. var loadeddoc = DataEntryReGroupWindow.RenderToPDF(doc.FileName, stream);
  297. foreach (var page in loadeddoc.GetPages())
  298. {
  299. var rotation = (int)page.Rotation;
  300. rotation = (rotation + 1) % 4;
  301. page.Rotation = (PdfPageRotateAngle)rotation;
  302. }
  303. doc.Data = loadeddoc.SaveToBytes();
  304. }
  305. }
  306. private void RotateImage_Click(object sender, RoutedEventArgs e)
  307. {
  308. if (sender is not MenuItem item || item.Tag is not ImageSource image) return;
  309. var document = ViewDocuments.FirstOrDefault(x => x.Image == image);
  310. if (document is null)
  311. {
  312. MessageWindow.ShowError("An error occurred", "Document does not exist in ViewDocuments list");
  313. return;
  314. }
  315. var doc = LoadDocuments(CoreUtils.One(GetDocumentID(document.Document))).First();
  316. try
  317. {
  318. RotateDocument(doc, document.PageNumber);
  319. }
  320. catch(Exception err)
  321. {
  322. MessageWindow.ShowError("Something went wrong while trying to rotate this document.", err);
  323. return;
  324. }
  325. Client.Save(doc, "Rotated by user.");
  326. UpdateDocument?.Invoke(document.Document, doc);
  327. }
  328. private void ViewImage_Click(object sender, RoutedEventArgs e)
  329. {
  330. if (sender is not MenuItem item || item.Tag is not ImageSource image) return;
  331. OpenImageWindow(image);
  332. }
  333. private void ExplodeAll_Click()
  334. {
  335. ExplodeAll?.Invoke();
  336. }
  337. private void Explode_Click()
  338. {
  339. Explode?.Invoke();
  340. }
  341. #region Image Window
  342. private List<DataEntryDocumentWindow> OpenWindows = new();
  343. public void CloseImageWindows()
  344. {
  345. while (OpenWindows.Count > 0)
  346. {
  347. var win = OpenWindows.Last();
  348. OpenWindows.RemoveAt(OpenWindows.Count - 1);
  349. win.Close();
  350. }
  351. }
  352. private void OpenImageWindow(ImageSource image)
  353. {
  354. var window = OpenWindows.FirstOrDefault(x => x.Images.Contains(image));
  355. if (window is not null)
  356. {
  357. window.Activate();
  358. }
  359. else
  360. {
  361. window = new DataEntryDocumentWindow();
  362. window.Topmost = true;
  363. window.Images.Add(image);
  364. OpenWindows.Add(window);
  365. window.Closed += OpenWindow_Closed;
  366. window.Show();
  367. }
  368. }
  369. private void OpenWindow_Closed(object? sender, EventArgs e)
  370. {
  371. if (sender is not DataEntryDocumentWindow window) return;
  372. OpenWindows.Remove(window);
  373. }
  374. private void Img_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  375. {
  376. if (sender is not Image image) return;
  377. if(e.ClickCount >= 2)
  378. {
  379. OpenImageWindow(image.Source);
  380. e.Handled = true;
  381. }
  382. }
  383. #endregion
  384. public event PropertyChangedEventHandler? PropertyChanged;
  385. protected void DoPropertyChanged([CallerMemberName] string propertyName = "")
  386. {
  387. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  388. }
  389. }
  390. public class DataEntryViewList : DocumentViewList<DataEntryDocument>
  391. {
  392. protected override IEnumerable<Document> LoadDocuments(IEnumerable<Guid> ids)
  393. {
  394. return DataEntryCache.Cache.LoadDocuments(ids, checkTimestamp: true);
  395. }
  396. protected override Guid GetID(DataEntryDocument document)
  397. {
  398. return document.ID;
  399. }
  400. protected override Guid GetDocumentID(DataEntryDocument document)
  401. {
  402. return document.Document.ID;
  403. }
  404. }