DocumentViewList.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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.Margin = new(0, 0, 0, 5);
  129. img.ContextMenu = itemsControl.ContextMenu;
  130. img.MouseLeftButtonDown += Img_MouseLeftButtonDown;
  131. return img;
  132. });
  133. ZoomPanel.Content = itemsControl;
  134. border.Child = ZoomPanel;
  135. Content = border;
  136. BindingOperations.EnableCollectionSynchronization(ViewList, _viewListLock);
  137. }
  138. protected abstract Guid GetID(TDocument document);
  139. protected abstract Guid GetDocumentID(TDocument document);
  140. protected abstract IEnumerable<Document> LoadDocuments(IEnumerable<Guid> ids);
  141. public void UpdateViewList(IList<TDocument> documents, bool force = false)
  142. {
  143. if (!force && documents.Count == _documents.Count && !documents.Any(x => _documents.All(y => GetID(x) != GetID(y))))
  144. return;
  145. _documents = documents;
  146. ViewList.Clear();
  147. ViewDocuments.Clear();
  148. if(_documents.Count == 0)
  149. {
  150. return;
  151. }
  152. Task.Run(() =>
  153. {
  154. var docs = LoadDocuments(Documents.Select(GetDocumentID).Distinct());
  155. LoadDocuments(docs);
  156. }).ContinueWith((task) =>
  157. {
  158. if(task.Exception is not null)
  159. {
  160. MessageWindow.ShowError("An error occurred while loading the documents", task.Exception);
  161. }
  162. }, TaskScheduler.FromCurrentSynchronizationContext());
  163. }
  164. private void LoadDocuments(IEnumerable<Document> documents)
  165. {
  166. var bitmaps = new Dictionary<Guid, List<ImageSource>>();
  167. foreach (var document in documents.Where(x=>x.Data?.Any() == true))
  168. {
  169. List<byte[]> images;
  170. var bitmapImages = new List<ImageSource>();
  171. var extension = Path.GetExtension(document.FileName).ToLower();
  172. if (extension == ".pdf")
  173. {
  174. images = new List<byte[]>();
  175. try
  176. {
  177. bitmapImages = ImageUtils.RenderPDFToImageSources(document.Data);
  178. }
  179. catch (Exception e)
  180. {
  181. MessageBox.Show($"Cannot load document '{document.FileName}': {e.Message}");
  182. }
  183. }
  184. else if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
  185. {
  186. images = new List<byte[]> { document.Data };
  187. }
  188. else
  189. {
  190. images = ImageUtils.RenderTextFileToImages(Encoding.UTF8.GetString(document.Data));
  191. }
  192. bitmapImages.AddRange(images.Select(x =>
  193. {
  194. try
  195. {
  196. return ImageUtils.LoadImage(x);
  197. }
  198. catch (Exception e)
  199. {
  200. Dispatcher.BeginInvoke(() =>
  201. {
  202. MessageWindow.ShowError($"Cannot load document '{document.FileName}", e);
  203. });
  204. }
  205. return null;
  206. }).Where(x => x != null).Cast<ImageSource>());
  207. foreach (var image in bitmapImages)
  208. {
  209. if (!bitmaps.TryGetValue(document.ID, out var list))
  210. {
  211. list = new List<ImageSource>();
  212. bitmaps[document.ID] = list;
  213. }
  214. list.Add(image);
  215. }
  216. }
  217. ViewDocuments.Clear();
  218. var maxWidth = 0.0;
  219. foreach (var scan in Documents)
  220. {
  221. if (bitmaps.TryGetValue(GetDocumentID(scan), out var list))
  222. {
  223. int page = 1;
  224. foreach (var bitmap in list)
  225. {
  226. maxWidth = Math.Max(maxWidth, bitmap.Width);
  227. ViewDocuments.Add(new(bitmap, scan, page));
  228. page++;
  229. }
  230. }
  231. }
  232. lock (_viewListLock)
  233. {
  234. ViewList.Clear();
  235. foreach(var doc in ViewDocuments)
  236. {
  237. ViewList.Add(doc.Image);
  238. }
  239. if(maxWidth != 0.0)
  240. {
  241. ZoomPanel.Scale = ZoomPanel.ActualWidth / (maxWidth * 1.1);
  242. ZoomPanel.MinScale = ZoomPanel.Scale / 2;
  243. }
  244. }
  245. }
  246. private void RotateDocument(Document doc, int pageNumber)
  247. {
  248. var extension = Path.GetExtension(doc.FileName).ToLower();
  249. if (extension == ".pdf")
  250. {
  251. var loadeddoc = new PdfLoadedDocument(doc.Data);
  252. bool allPages = loadeddoc.PageCount() > 1;
  253. if (allPages)
  254. {
  255. allPages = MessageWindow.New()
  256. .Message("Do you want to rotate all pages in this PDF?")
  257. .Title("Rotate all?")
  258. .AddYesButton("All pages")
  259. .AddNoButton("Just this page")
  260. .Display().Result == MessageWindowResult.Yes;
  261. }
  262. if(allPages)
  263. {
  264. foreach (var page in loadeddoc.GetPages())
  265. {
  266. var rotation = (int)page.Rotation;
  267. rotation = (rotation + 1) % 4;
  268. page.Rotation = (PdfPageRotateAngle)rotation;
  269. }
  270. }
  271. else if(pageNumber <= loadeddoc.PageCount())
  272. {
  273. var page = loadeddoc.GetPage(pageNumber - 1);
  274. var rotation = (int)page.Rotation;
  275. rotation = (rotation + 1) % 4;
  276. page.Rotation = (PdfPageRotateAngle)rotation;
  277. }
  278. doc.Data = loadeddoc.SaveToBytes();
  279. }
  280. else if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
  281. {
  282. using var stream = new MemoryStream(doc.Data);
  283. var bitmap = Bitmap.FromStream(stream);
  284. bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
  285. using var outStream = new MemoryStream();
  286. bitmap.Save(outStream, extension switch
  287. {
  288. ".jpg" or ".jpeg" => ImageFormat.Jpeg,
  289. ".png" => ImageFormat.Png,
  290. _ => ImageFormat.Bmp
  291. });
  292. doc.Data = outStream.ToArray();
  293. }
  294. else
  295. {
  296. using var stream = new MemoryStream(doc.Data);
  297. var loadeddoc = DataEntryReGroupWindow.RenderToPDF(doc.FileName, stream);
  298. foreach (var page in loadeddoc.GetPages())
  299. {
  300. var rotation = (int)page.Rotation;
  301. rotation = (rotation + 1) % 4;
  302. page.Rotation = (PdfPageRotateAngle)rotation;
  303. }
  304. doc.Data = loadeddoc.SaveToBytes();
  305. }
  306. }
  307. private void RotateImage_Click(object sender, RoutedEventArgs e)
  308. {
  309. if (sender is not MenuItem item || item.Tag is not ImageSource image) return;
  310. var document = ViewDocuments.FirstOrDefault(x => x.Image == image);
  311. if (document is null)
  312. {
  313. MessageWindow.ShowError("An error occurred", "Document does not exist in ViewDocuments list");
  314. return;
  315. }
  316. var doc = LoadDocuments(CoreUtils.One(GetDocumentID(document.Document))).First();
  317. try
  318. {
  319. RotateDocument(doc, document.PageNumber);
  320. }
  321. catch(Exception err)
  322. {
  323. MessageWindow.ShowError("Something went wrong while trying to rotate this document.", err);
  324. return;
  325. }
  326. Client.Save(doc, "Rotated by user.");
  327. UpdateDocument?.Invoke(document.Document, doc);
  328. }
  329. private void ViewImage_Click(object sender, RoutedEventArgs e)
  330. {
  331. if (sender is not MenuItem item || item.Tag is not ImageSource image) return;
  332. OpenImageWindow(image);
  333. }
  334. private void ExplodeAll_Click()
  335. {
  336. ExplodeAll?.Invoke();
  337. }
  338. private void Explode_Click()
  339. {
  340. Explode?.Invoke();
  341. }
  342. #region Image Window
  343. private List<DataEntryDocumentWindow> OpenWindows = new();
  344. public void CloseImageWindows()
  345. {
  346. while (OpenWindows.Count > 0)
  347. {
  348. var win = OpenWindows.Last();
  349. OpenWindows.RemoveAt(OpenWindows.Count - 1);
  350. win.Close();
  351. }
  352. }
  353. private void OpenImageWindow(ImageSource image)
  354. {
  355. var window = OpenWindows.FirstOrDefault(x => x.Images.Contains(image));
  356. if (window is not null)
  357. {
  358. window.Activate();
  359. }
  360. else
  361. {
  362. var docID = GetDocumentID(ViewDocuments.First(x => x.Image == image).Document);
  363. var docs = ViewDocuments.Where(x => GetDocumentID(x.Document) == docID);
  364. window = new DataEntryDocumentWindow();
  365. window.Topmost = true;
  366. foreach(var doc in docs)
  367. {
  368. window.Images.Add(doc.Image);
  369. }
  370. OpenWindows.Add(window);
  371. window.Closed += OpenWindow_Closed;
  372. window.Show();
  373. }
  374. }
  375. private void OpenWindow_Closed(object? sender, EventArgs e)
  376. {
  377. if (sender is not DataEntryDocumentWindow window) return;
  378. OpenWindows.Remove(window);
  379. }
  380. private void Img_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  381. {
  382. if (sender is not Image image) return;
  383. if(e.ClickCount >= 2)
  384. {
  385. OpenImageWindow(image.Source);
  386. e.Handled = true;
  387. }
  388. }
  389. #endregion
  390. public event PropertyChangedEventHandler? PropertyChanged;
  391. protected void DoPropertyChanged([CallerMemberName] string propertyName = "")
  392. {
  393. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  394. }
  395. }
  396. public class DataEntryViewList : DocumentViewList<DataEntryDocument>
  397. {
  398. protected override IEnumerable<Document> LoadDocuments(IEnumerable<Guid> ids)
  399. {
  400. return DataEntryCache.Cache.LoadDocuments(ids, checkTimestamp: true);
  401. }
  402. protected override Guid GetID(DataEntryDocument document)
  403. {
  404. return document.ID;
  405. }
  406. protected override Guid GetDocumentID(DataEntryDocument document)
  407. {
  408. return document.Document.ID;
  409. }
  410. }