DataEntryList.xaml.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. namespace PRSDesktop
  33. {
  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. CoreUtils.LogException(ClientFactory.UserID, e);
  158. MessageBox.Show("An error occurred while loading the documents");
  159. }
  160. });
  161. }
  162. private void LoadDocuments(IEnumerable<Document> documents)
  163. {
  164. var bitmaps = new Dictionary<Guid, List<ImageSource>>();
  165. foreach (var document in documents)
  166. {
  167. List<byte[]> images;
  168. var bitmapImages = new List<ImageSource>();
  169. var extension = Path.GetExtension(document.FileName).ToLower();
  170. if (extension == ".pdf")
  171. {
  172. images = new List<byte[]>();
  173. try
  174. {
  175. bitmapImages = ImageUtils.RenderPDFToImageSources(document.Data);
  176. }
  177. catch (Exception e)
  178. {
  179. MessageBox.Show($"Cannot load document '{document.FileName}': {e.Message}");
  180. }
  181. }
  182. else if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
  183. {
  184. images = new List<byte[]> { document.Data };
  185. }
  186. else
  187. {
  188. images = ImageUtils.RenderTextFileToImages(Encoding.UTF8.GetString(document.Data));
  189. }
  190. bitmapImages.AddRange(images.Select(x =>
  191. {
  192. try
  193. {
  194. return ImageUtils.LoadImage(x);
  195. }
  196. catch (Exception e)
  197. {
  198. MessageBox.Show($"Cannot load document '{document.FileName}': {e.Message}");
  199. }
  200. return null;
  201. }).Where(x => x != null).Cast<ImageSource>());
  202. foreach (var image in bitmapImages)
  203. {
  204. if (!bitmaps.TryGetValue(document.ID, out var list))
  205. {
  206. list = new List<ImageSource>();
  207. bitmaps[document.ID] = list;
  208. }
  209. list.Add(image);
  210. }
  211. }
  212. Dispatcher.Invoke(() =>
  213. {
  214. foreach (var scan in SelectedScans)
  215. {
  216. if (bitmaps.TryGetValue(scan.Document.ID, out var list))
  217. {
  218. foreach (var bitmap in list)
  219. {
  220. var image = new Image
  221. {
  222. Source = bitmap,
  223. Margin = new Thickness(0, 0, 0, 20),
  224. ContextMenu = ViewListPanel.ContextMenu
  225. };
  226. ViewListPanel.Children.Add(image);
  227. }
  228. }
  229. }
  230. });
  231. }
  232. #endregion
  233. #region Uploading
  234. private void DynamicTabItem_Drop(object sender, DragEventArgs e)
  235. {
  236. Task.Run(() =>
  237. {
  238. var docs = DataEntryReGroupWindow.HandleFileDrop(e);
  239. if (docs is not null)
  240. {
  241. foreach(var (filename, doc) in docs)
  242. {
  243. _dataEntryGrid.UploadDocument(Path.ChangeExtension(filename, ".pdf"), doc.SaveToBytes(), Guid.Empty);
  244. }
  245. /*Dispatcher.Invoke(() =>
  246. {
  247. ScanGrid.ShowDocumentWindow(pages, filename);
  248. });*/
  249. }
  250. });
  251. }
  252. private void DynamicTabItem_DragOver(object sender, DragEventArgs e)
  253. {
  254. if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent("FileGroupDescriptor"))
  255. {
  256. e.Effects = DragDropEffects.Copy;
  257. }
  258. else
  259. {
  260. e.Effects = DragDropEffects.None;
  261. }
  262. e.Handled = true;
  263. }
  264. #endregion
  265. private void _documents_OnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  266. {
  267. UpdateViewList();
  268. DoSelect(e.Rows);
  269. }
  270. private void DoSelect(CoreRow[] rows)
  271. {
  272. var appliesTo = rows?.Length == 1
  273. ? rows[0].Get<DataEntryDocument, string>(x => x.Tag.AppliesTo)
  274. : "";
  275. var entityid = rows?.Length == 1
  276. ? rows[0].Get<DataEntryDocument, Guid>(x => x.EntityID)
  277. : Guid.Empty;
  278. var archived = rows?.Length == 1
  279. ? rows[0].Get<DataEntryDocument, DateTime>(x => x.Archived)
  280. : DateTime.MinValue;
  281. SelectionChanged?.Invoke(appliesTo, entityid, archived.IsEmpty());
  282. }
  283. private void _historyGrid_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  284. {
  285. DoSelect(e.Rows);
  286. }
  287. private void _Explode_OnClick(object sender, RoutedEventArgs e)
  288. {
  289. _dataEntryGrid.DoExplode();
  290. }
  291. private List<DataEntryTag>? _tags;
  292. private void _uploadMenu_OnOpened(object sender, RoutedEventArgs e)
  293. {
  294. if (Clipboard.ContainsText())
  295. {
  296. _pasteItem.Header = "Paste Text from Clipboard";
  297. _pasteItem.Visibility = Visibility.Visible;
  298. }
  299. else if (Clipboard.ContainsImage())
  300. {
  301. _pasteItem.Header = "Paste Image from Clipboard";
  302. _pasteItem.Visibility = Visibility.Visible;
  303. }
  304. else if (Clipboard.ContainsFileDropList())
  305. {
  306. int count = CheckAllowableFiles();
  307. if (count > 0)
  308. {
  309. _pasteItem.Header = $@"Paste {count} File{(count > 1 ? "s" : "")} from Clipboard";
  310. _pasteItem.Visibility = Visibility.Visible;
  311. }
  312. }
  313. else
  314. _pasteItem.Visibility = Visibility.Collapsed;
  315. _archive.Visibility = _dataEntryGrid.SelectedRows.Any() && Security.CanEdit<DataEntryDocument>()
  316. ? Visibility.Visible
  317. : Visibility.Collapsed;
  318. _archiveseparator.Visibility = _archive.Visibility;
  319. _tags ??= DataEntryGrid.GetVisibleTagList();
  320. _changeTag.Items.Clear();
  321. foreach (var tag in _tags)
  322. _changeTag.Items.Add(new MenuItem()
  323. {
  324. Header = tag.Name,
  325. Command = new Command((_) => ChangeTag(tag)) { }
  326. });
  327. _changeTag.Items.Add(new Separator());
  328. _changeTag.Items.Add(new MenuItem()
  329. {
  330. Header= "Clear Tags",
  331. Command = new Command((_) => ChangeTag(new DataEntryTag()))
  332. });
  333. _changeTag.Visibility = _dataEntryGrid.SelectedRows.Any() && _tags.Any() && (Security.CanEdit<DataEntryDocument>() || Security.IsAllowed<CanSetupDataEntryTags>())
  334. ? Visibility.Visible
  335. : Visibility.Collapsed;
  336. _changetagseparator.Visibility = _archive.Visibility;
  337. }
  338. private void ChangeTag(object obj)
  339. {
  340. if (obj is DataEntryTag tag)
  341. _dataEntryGrid.DoChangeTags(tag.ID);
  342. }
  343. private void _addItem_OnClick(object sender, RoutedEventArgs e)
  344. {
  345. var ofd = new OpenFileDialog()
  346. {
  347. Filter = @"All Files (*.pdf, *.bmp, *.png, *.jpg, *.jpeg)|*.pdf;*.bmp;*.png;*.jpg;*.jpeg",
  348. Multiselect = true,
  349. Title = @"Select Files to Upload",
  350. InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  351. };
  352. if (ofd.ShowDialog() == DialogResult.OK)
  353. {
  354. foreach (var file in ofd.FileNames)
  355. Upload(
  356. Path.GetFileName(file),
  357. new FileStream(file,FileMode.Open));
  358. }
  359. }
  360. private void _pasteItem_OnClick(object sender, RoutedEventArgs e)
  361. {
  362. if (Clipboard.ContainsText())
  363. {
  364. Upload(
  365. $"Pasted Text {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.txt",
  366. new MemoryStream(new UTF8Encoding().GetBytes(Clipboard.GetText()))
  367. );
  368. }
  369. else if (Clipboard.ContainsImage())
  370. {
  371. var img = Clipboard.GetImage();
  372. if (img != null)
  373. {
  374. var bmp = ImageUtils.BitmapSourceToBitmap(img);
  375. using (var ms = new MemoryStream())
  376. {
  377. bmp.Save(ms, ImageFormat.Png);
  378. Upload(
  379. $"Pasted Image {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.png",
  380. ms
  381. );
  382. }
  383. }
  384. }
  385. else if (CheckAllowableFiles() > 0)
  386. {
  387. var files = Clipboard.GetFileDropList().OfType<String>().ToArray();
  388. foreach (var file in files)
  389. {
  390. Upload(
  391. Path.GetFileName(file),
  392. new FileStream(file,FileMode.Open)
  393. );
  394. }
  395. }
  396. }
  397. private void Upload(string filename, Stream data)
  398. {
  399. var doc = DataEntryReGroupWindow.RenderToPDF(filename, data);
  400. _dataEntryGrid.UploadDocument(Path.ChangeExtension(filename,"pdf"), doc.SaveToBytes(), Guid.Empty);
  401. }
  402. private static int CheckAllowableFiles()
  403. {
  404. var extensions = Clipboard.GetFileDropList().OfType<String>().Select(x => Path.GetExtension(x.ToUpper())).ToArray();
  405. return extensions.Count(x =>
  406. String.Equals(x, "PDF")
  407. || String.Equals(x, "PNG")
  408. || String.Equals(x, "JPG")
  409. || String.Equals(x, "JPEG")
  410. || String.Equals(x, "BMP")
  411. || String.Equals(x, "TXT")
  412. );
  413. }
  414. private void _pages_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  415. {
  416. if (_pages.SelectedIndex == 0)
  417. _dataEntryGrid.Refresh(false,true);
  418. else if (_pages.SelectedIndex == 1)
  419. _historyGrid.Refresh(false,true);
  420. }
  421. private void _remove_OnClick(object sender, RoutedEventArgs e)
  422. {
  423. _dataEntryGrid.DoRemove();
  424. }
  425. private void _reopen_OnClick(object sender, RoutedEventArgs e)
  426. {
  427. _historyGrid.DoReopen();
  428. }
  429. private void _dataEntryGrid_OnContextMenuOpening(object sender, ContextMenuEventArgs e)
  430. {
  431. }
  432. }
  433. }