DataEntryList.xaml.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. using Comal.Classes;
  2. using InABox.Clients;
  3. using InABox.Core;
  4. using Syncfusion.Pdf.Graphics;
  5. using Syncfusion.Pdf.Parsing;
  6. using Syncfusion.Pdf;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Drawing.Imaging;
  10. using System.Drawing;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading.Tasks;
  15. using System.Windows;
  16. using System.Windows.Media;
  17. using System.Windows.Media.Imaging;
  18. using InABox.DynamicGrid;
  19. using InABox.WPF;
  20. using Encoder = System.Drawing.Imaging.Encoder;
  21. using Path = System.IO.Path;
  22. using Image = System.Windows.Controls.Image;
  23. using System.ComponentModel;
  24. using System.Windows.Controls;
  25. using System.Windows.Forms;
  26. using Clipboard = System.Windows.Clipboard;
  27. using DataFormats = System.Windows.DataFormats;
  28. using DragDropEffects = System.Windows.DragDropEffects;
  29. using DragEventArgs = System.Windows.DragEventArgs;
  30. using MessageBox = System.Windows.MessageBox;
  31. using UserControl = System.Windows.Controls.UserControl;
  32. using InABox.Wpf;
  33. namespace PRSDesktop;
  34. public static class PDFExtensions
  35. {
  36. public static IEnumerable<PdfPageBase> GetPages(this PdfDocumentBase doc)
  37. {
  38. if (doc is PdfLoadedDocument lDoc)
  39. return lDoc.Pages.Cast<PdfPageBase>();
  40. if (doc is PdfDocument pdfDoc)
  41. return pdfDoc.Pages.Cast<PdfPageBase>();
  42. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  43. }
  44. public static PdfPageBase GetPage(this PdfDocumentBase doc, int index)
  45. {
  46. if (doc is PdfLoadedDocument lDoc)
  47. return lDoc.Pages[index];
  48. if (doc is PdfDocument pdfDoc)
  49. return pdfDoc.Pages[index];
  50. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  51. }
  52. public static int PageCount(this PdfDocumentBase doc)
  53. {
  54. if (doc is PdfLoadedDocument lDoc)
  55. return lDoc.Pages.Count;
  56. if (doc is PdfDocument pdfDoc)
  57. return pdfDoc.Pages.Count;
  58. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  59. }
  60. public static PdfLoadedDocument AsLoadedDocument(this PdfDocumentBase doc)
  61. {
  62. if (doc is PdfLoadedDocument lDoc)
  63. return lDoc;
  64. if (doc is PdfDocument pdfDoc)
  65. {
  66. using var ms = new MemoryStream();
  67. pdfDoc.Save(ms);
  68. var array = ms.ToArray();
  69. return new PdfLoadedDocument(array);
  70. }
  71. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  72. }
  73. public static byte[] SaveToBytes(this PdfDocumentBase doc)
  74. {
  75. using var ms = new MemoryStream();
  76. doc.Save(ms);
  77. return ms.ToArray();
  78. }
  79. }
  80. /// <summary>
  81. /// Interaction logic for ScanPanel.xaml
  82. /// </summary>
  83. public partial class DataEntryList : UserControl, ICorePanel, IDockPanel
  84. {
  85. private List<DataEntryDocument> SelectedScans = new();
  86. public delegate void DateEntrySelectionHandler(String appliesTo, Guid entityID, bool allowprocess);
  87. public event DateEntrySelectionHandler? SelectionChanged;
  88. public DataEntryList()
  89. {
  90. InitializeComponent();
  91. }
  92. #region Panel
  93. public void Setup()
  94. {
  95. _dataEntryGrid.HiddenColumns.Add(x => x.Document.ID);
  96. _dataEntryGrid.Refresh(true, false);
  97. _historyGrid.Refresh(true, false);
  98. }
  99. public void Refresh()
  100. {
  101. if (_pages.SelectedIndex == 0)
  102. _dataEntryGrid.Refresh(false, true);
  103. else if (_pages.SelectedIndex == 1)
  104. _historyGrid.Refresh(false,true);
  105. }
  106. public void Shutdown(CancelEventArgs? cancel)
  107. {
  108. }
  109. #endregion
  110. #region View List
  111. private static List<byte[]> RenderTextFile(string textData)
  112. {
  113. var pdfDocument = new PdfDocument();
  114. var page = pdfDocument.Pages.Add();
  115. var font = new PdfStandardFont(PdfFontFamily.Courier, 14);
  116. var textElement = new PdfTextElement(textData, font);
  117. var layoutFormat = new PdfLayoutFormat
  118. {
  119. Layout = PdfLayoutType.Paginate,
  120. Break = PdfLayoutBreakType.FitPage
  121. };
  122. textElement.Draw(page, new RectangleF(0, 0, page.GetClientSize().Width, page.GetClientSize().Height), layoutFormat);
  123. using var docStream = new MemoryStream();
  124. pdfDocument.Save(docStream);
  125. var loadeddoc = new PdfLoadedDocument(docStream.ToArray());
  126. Bitmap[] bmpImages = loadeddoc.ExportAsImage(0, loadeddoc.Pages.Count - 1);
  127. var jpgEncoder = ImageUtils.GetEncoder(ImageFormat.Jpeg)!;
  128. var quality = Encoder.Quality;
  129. var encodeParams = new EncoderParameters(1);
  130. encodeParams.Param[0] = new EncoderParameter(quality, 100L);
  131. var images = new List<byte[]>();
  132. if (bmpImages != null)
  133. foreach (var image in bmpImages)
  134. {
  135. using var data = new MemoryStream();
  136. image.Save(data, jpgEncoder, encodeParams);
  137. images.Add(data.ToArray());
  138. }
  139. return images;
  140. }
  141. private void UpdateViewList()
  142. {
  143. var selected = _dataEntryGrid.SelectedRows.Select(x => x.ToObject<DataEntryDocument>()).ToList();
  144. if (selected.Count == SelectedScans.Count && !selected.Any(x => SelectedScans.All(y => x.ID != y.ID)))
  145. return;
  146. SelectedScans = selected;
  147. ViewListPanel.Children.Clear();
  148. Task.Run(() =>
  149. {
  150. try
  151. {
  152. var docs = DataEntryCache.Cache.LoadDocuments(SelectedScans.Select(x => x.Document.ID).Distinct(), checkTimestamp: true);
  153. LoadDocuments(docs);
  154. }
  155. catch (Exception e)
  156. {
  157. Dispatcher.BeginInvoke(() =>
  158. {
  159. MessageWindow.ShowError("An error occurred while loading the documents", e);
  160. });
  161. }
  162. });
  163. }
  164. private void LoadDocuments(IEnumerable<Document> documents)
  165. {
  166. var bitmaps = new Dictionary<Guid, List<ImageSource>>();
  167. foreach (var document in documents)
  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. Dispatcher.Invoke(() =>
  218. {
  219. foreach (var scan in SelectedScans)
  220. {
  221. if (bitmaps.TryGetValue(scan.Document.ID, out var list))
  222. {
  223. foreach (var bitmap in list)
  224. {
  225. var image = new Image
  226. {
  227. Source = bitmap,
  228. Margin = new Thickness(0, 0, 0, 20),
  229. ContextMenu = ViewListPanel.ContextMenu
  230. };
  231. ViewListPanel.Children.Add(image);
  232. }
  233. }
  234. }
  235. });
  236. }
  237. #endregion
  238. #region Uploading
  239. private static byte[] RenderData(ref string filename, byte[] data)
  240. {
  241. var extension = Path.GetExtension(filename).ToLower();
  242. if ((extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp") && ImageUtils.TryGetImageType(data, out var format))
  243. {
  244. return data;
  245. }
  246. else if (extension == ".pdf")
  247. {
  248. return data;
  249. }
  250. else
  251. {
  252. using var stream = new MemoryStream(data);
  253. filename = Path.ChangeExtension(filename, "pdf");
  254. return DataEntryReGroupWindow.RenderToPDF(filename, stream).SaveToBytes();
  255. }
  256. throw new Exception("Could not render file to PDF");
  257. }
  258. private void DynamicTabItem_Drop(object sender, DragEventArgs e)
  259. {
  260. Task.Run(() =>
  261. {
  262. Dispatcher.Invoke(() =>
  263. {
  264. Progress.Show("Uploading documents");
  265. try
  266. {
  267. var result = DocumentUtils.HandleFileDrop(e);
  268. if (result is not null)
  269. {
  270. foreach (var (filename, stream) in result)
  271. {
  272. var newFilename = filename;
  273. byte[] data;
  274. if (stream is null)
  275. {
  276. data = File.ReadAllBytes(newFilename);
  277. }
  278. else
  279. {
  280. using var memStream = new MemoryStream();
  281. stream.CopyTo(memStream);
  282. data = memStream.ToArray();
  283. }
  284. data = RenderData(ref newFilename, data);
  285. _dataEntryGrid.UploadDocument(newFilename, data, Guid.Empty);
  286. }
  287. }
  288. Progress.Close();
  289. }
  290. catch (Exception e)
  291. {
  292. Progress.Close();
  293. MessageWindow.ShowError("Could not upload documents.", e);
  294. }
  295. });
  296. });
  297. }
  298. private void DynamicTabItem_DragOver(object sender, DragEventArgs e)
  299. {
  300. if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent("FileGroupDescriptor"))
  301. {
  302. e.Effects = DragDropEffects.Copy;
  303. }
  304. else
  305. {
  306. e.Effects = DragDropEffects.None;
  307. }
  308. e.Handled = true;
  309. }
  310. #endregion
  311. private void _documents_OnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  312. {
  313. UpdateViewList();
  314. DoSelect(e.Rows);
  315. }
  316. private void DoSelect(CoreRow[] rows)
  317. {
  318. var appliesTo = rows?.Length == 1
  319. ? rows[0].Get<DataEntryDocument, string>(x => x.Tag.AppliesTo)
  320. : "";
  321. var entityid = rows?.Length == 1
  322. ? rows[0].Get<DataEntryDocument, Guid>(x => x.EntityID)
  323. : Guid.Empty;
  324. var archived = rows?.Length == 1
  325. ? rows[0].Get<DataEntryDocument, DateTime>(x => x.Archived)
  326. : DateTime.MinValue;
  327. SelectionChanged?.Invoke(appliesTo, entityid, archived.IsEmpty());
  328. }
  329. private void _historyGrid_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  330. {
  331. DoSelect(e.Rows);
  332. }
  333. private void _Explode_OnClick(object sender, RoutedEventArgs e)
  334. {
  335. _dataEntryGrid.DoExplode();
  336. }
  337. private List<DataEntryTag>? _tags;
  338. private void _uploadMenu_OnOpened(object sender, RoutedEventArgs e)
  339. {
  340. if (Clipboard.ContainsText())
  341. {
  342. _pasteItem.Header = "Paste Text from Clipboard";
  343. _pasteItem.Visibility = Visibility.Visible;
  344. }
  345. else if (Clipboard.ContainsImage())
  346. {
  347. _pasteItem.Header = "Paste Image from Clipboard";
  348. _pasteItem.Visibility = Visibility.Visible;
  349. }
  350. else if (Clipboard.ContainsFileDropList())
  351. {
  352. int count = CheckAllowableFiles();
  353. if (count > 0)
  354. {
  355. _pasteItem.Header = $@"Paste {count} File{(count > 1 ? "s" : "")} from Clipboard";
  356. _pasteItem.Visibility = Visibility.Visible;
  357. }
  358. }
  359. else
  360. _pasteItem.Visibility = Visibility.Collapsed;
  361. _archive.Visibility = _dataEntryGrid.SelectedRows.Any() && Security.CanEdit<DataEntryDocument>()
  362. ? Visibility.Visible
  363. : Visibility.Collapsed;
  364. _archiveseparator.Visibility = _archive.Visibility;
  365. _tags ??= DataEntryGrid.GetVisibleTagList();
  366. _changeTag.Items.Clear();
  367. foreach (var tag in _tags)
  368. _changeTag.Items.Add(new MenuItem()
  369. {
  370. Header = tag.Name,
  371. Command = new Command((_) => ChangeTag(tag)) { }
  372. });
  373. _changeTag.Items.Add(new Separator());
  374. _changeTag.Items.Add(new MenuItem()
  375. {
  376. Header= "Clear Tags",
  377. Command = new Command((_) => ChangeTag(new DataEntryTag()))
  378. });
  379. _changeTag.Visibility = _dataEntryGrid.SelectedRows.Any() && _tags.Any() && (Security.CanEdit<DataEntryDocument>() || Security.IsAllowed<CanSetupDataEntryTags>())
  380. ? Visibility.Visible
  381. : Visibility.Collapsed;
  382. _changetagseparator.Visibility = _archive.Visibility;
  383. }
  384. private void ChangeTag(object obj)
  385. {
  386. if (obj is DataEntryTag tag)
  387. _dataEntryGrid.DoChangeTags(tag.ID);
  388. }
  389. private void _addItem_OnClick(object sender, RoutedEventArgs e)
  390. {
  391. var ofd = new OpenFileDialog()
  392. {
  393. Filter = @"All Files (*.pdf, *.bmp, *.png, *.jpg, *.jpeg)|*.pdf;*.bmp;*.png;*.jpg;*.jpeg",
  394. Multiselect = true,
  395. Title = @"Select Files to Upload",
  396. InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  397. };
  398. if (ofd.ShowDialog() == DialogResult.OK)
  399. {
  400. foreach (var file in ofd.FileNames)
  401. Upload(
  402. Path.GetFileName(file),
  403. new FileStream(file,FileMode.Open));
  404. }
  405. }
  406. private void _pasteItem_OnClick(object sender, RoutedEventArgs e)
  407. {
  408. if (Clipboard.ContainsText())
  409. {
  410. Upload(
  411. $"Pasted Text {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.txt",
  412. new MemoryStream(new UTF8Encoding().GetBytes(Clipboard.GetText()))
  413. );
  414. }
  415. else if (Clipboard.ContainsImage())
  416. {
  417. var img = Clipboard.GetImage();
  418. if (img != null)
  419. {
  420. var bmp = ImageUtils.BitmapSourceToBitmap(img);
  421. using (var ms = new MemoryStream())
  422. {
  423. bmp.Save(ms, ImageFormat.Png);
  424. Upload(
  425. $"Pasted Image {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.png",
  426. ms
  427. );
  428. }
  429. }
  430. }
  431. else if (CheckAllowableFiles() > 0)
  432. {
  433. var files = Clipboard.GetFileDropList().OfType<String>().ToArray();
  434. foreach (var file in files)
  435. {
  436. Upload(
  437. Path.GetFileName(file),
  438. new FileStream(file,FileMode.Open)
  439. );
  440. }
  441. }
  442. }
  443. private void Upload(string filename, Stream data)
  444. {
  445. var doc = DataEntryReGroupWindow.RenderToPDF(filename, data);
  446. _dataEntryGrid.UploadDocument(Path.ChangeExtension(filename,"pdf"), doc.SaveToBytes(), Guid.Empty);
  447. }
  448. private static int CheckAllowableFiles()
  449. {
  450. var extensions = Clipboard.GetFileDropList().OfType<String>().Select(x => Path.GetExtension(x.ToUpper())).ToArray();
  451. return extensions.Count(x =>
  452. String.Equals(x, "PDF")
  453. || String.Equals(x, "PNG")
  454. || String.Equals(x, "JPG")
  455. || String.Equals(x, "JPEG")
  456. || String.Equals(x, "BMP")
  457. || String.Equals(x, "TXT")
  458. );
  459. }
  460. private void _pages_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  461. {
  462. if (_pages.SelectedIndex == 0)
  463. _dataEntryGrid.Refresh(false,true);
  464. else if (_pages.SelectedIndex == 1)
  465. _historyGrid.Refresh(false,true);
  466. }
  467. private void _remove_OnClick(object sender, RoutedEventArgs e)
  468. {
  469. _dataEntryGrid.DoRemove();
  470. }
  471. private void _reopen_OnClick(object sender, RoutedEventArgs e)
  472. {
  473. _historyGrid.DoReopen();
  474. }
  475. private void _dataEntryGrid_OnContextMenuOpening(object sender, ContextMenuEventArgs e)
  476. {
  477. }
  478. }