DocumentViewList.cs 16 KB

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