DataEntryList.xaml.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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 InABox.Wpf;
  21. using Encoder = System.Drawing.Imaging.Encoder;
  22. using Path = System.IO.Path;
  23. using Image = System.Windows.Controls.Image;
  24. using System.ComponentModel;
  25. using System.Windows.Controls;
  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. using System.Collections.ObjectModel;
  34. using System.Windows.Data;
  35. using PRSDesktop.Panels.DataEntry;
  36. using InABox.Wpf.Editors;
  37. using System.Timers;
  38. using Microsoft.Win32;
  39. using javax.xml.crypto;
  40. namespace PRSDesktop;
  41. public static class PDFExtensions
  42. {
  43. public static IEnumerable<PdfPageBase> GetPages(this PdfDocumentBase doc)
  44. {
  45. if (doc is PdfLoadedDocument lDoc)
  46. return lDoc.Pages.Cast<PdfPageBase>();
  47. if (doc is PdfDocument pdfDoc)
  48. return pdfDoc.Pages.Cast<PdfPageBase>();
  49. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  50. }
  51. public static PdfPageBase GetPage(this PdfDocumentBase doc, int index)
  52. {
  53. if (doc is PdfLoadedDocument lDoc)
  54. return lDoc.Pages[index];
  55. if (doc is PdfDocument pdfDoc)
  56. return pdfDoc.Pages[index];
  57. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  58. }
  59. public static int PageCount(this PdfDocumentBase doc)
  60. {
  61. if (doc is PdfLoadedDocument lDoc)
  62. return lDoc.Pages.Count;
  63. if (doc is PdfDocument pdfDoc)
  64. return pdfDoc.Pages.Count;
  65. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  66. }
  67. public static PdfLoadedDocument AsLoadedDocument(this PdfDocumentBase doc)
  68. {
  69. if (doc is PdfLoadedDocument lDoc)
  70. return lDoc;
  71. if (doc is PdfDocument pdfDoc)
  72. {
  73. using var ms = new MemoryStream();
  74. pdfDoc.Save(ms);
  75. var array = ms.ToArray();
  76. return new PdfLoadedDocument(array);
  77. }
  78. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  79. }
  80. public static byte[] SaveToBytes(this PdfDocumentBase doc)
  81. {
  82. using var ms = new MemoryStream();
  83. doc.Save(ms);
  84. return ms.ToArray();
  85. }
  86. }
  87. /// <summary>
  88. /// Interaction logic for ScanPanel.xaml
  89. /// </summary>
  90. public partial class DataEntryList : UserControl, ICorePanel, IDockPanel
  91. {
  92. private List<DataEntryDocument> SelectedScans = new();
  93. public delegate void DateEntrySelectionHandler(String appliesTo, Guid entityID, bool allowprocess);
  94. public event DateEntrySelectionHandler? SelectionChanged;
  95. public DataEntryList()
  96. {
  97. InitializeComponent();
  98. }
  99. #region Panel
  100. public void Setup()
  101. {
  102. _dataEntryGrid.HiddenColumns.Add(x => x.Document.ID);
  103. _dataEntryGrid.Refresh(true, false);
  104. _historyGrid.Refresh(true, false);
  105. }
  106. public void Refresh()
  107. {
  108. if (_pages.SelectedIndex == 0)
  109. _dataEntryGrid.Refresh(false, true);
  110. else if (_pages.SelectedIndex == 1)
  111. _historyGrid.Refresh(false,true);
  112. }
  113. public void Shutdown(CancelEventArgs? cancel)
  114. {
  115. ViewList.CloseImageWindows();
  116. }
  117. #endregion
  118. #region Uploading
  119. private static byte[] RenderData(ref string filename, byte[] data)
  120. {
  121. var extension = Path.GetExtension(filename).ToLower();
  122. if ((extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp") && ImageUtils.TryGetImageType(data, out var format))
  123. {
  124. return data;
  125. }
  126. else if (extension == ".pdf")
  127. {
  128. return data;
  129. }
  130. else
  131. {
  132. using var stream = new MemoryStream(data);
  133. filename = Path.ChangeExtension(filename, "pdf");
  134. return DataEntryReGroupWindow.RenderToPDF(filename, stream).SaveToBytes();
  135. }
  136. throw new Exception("Could not render file to PDF");
  137. }
  138. private void DynamicTabItem_Drop(object sender, DragEventArgs e)
  139. {
  140. Task.Run(() =>
  141. {
  142. Dispatcher.Invoke(() =>
  143. {
  144. Progress.Show("Uploading documents");
  145. try
  146. {
  147. var result = DocumentUtils.HandleFileDrop(e);
  148. if (result is not null)
  149. {
  150. foreach (var (filename, stream) in result)
  151. {
  152. var newFilename = filename;
  153. byte[] data;
  154. if (stream is null)
  155. {
  156. data = File.ReadAllBytes(newFilename);
  157. }
  158. else
  159. {
  160. using var memStream = new MemoryStream();
  161. stream.CopyTo(memStream);
  162. data = memStream.ToArray();
  163. }
  164. data = RenderData(ref newFilename, data);
  165. _dataEntryGrid.UploadDocument(newFilename, data, Guid.Empty);
  166. }
  167. }
  168. Progress.Close();
  169. }
  170. catch (Exception e)
  171. {
  172. Progress.Close();
  173. MessageWindow.ShowError("Could not upload documents.", e);
  174. }
  175. });
  176. });
  177. }
  178. private void DynamicTabItem_DragOver(object sender, DragEventArgs e)
  179. {
  180. if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent("FileGroupDescriptor"))
  181. {
  182. e.Effects = DragDropEffects.Copy;
  183. }
  184. else
  185. {
  186. e.Effects = DragDropEffects.None;
  187. }
  188. e.Handled = true;
  189. }
  190. #endregion
  191. private void _documents_OnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  192. {
  193. ViewList.Documents = _dataEntryGrid.SelectedRows.ToArray(x => x.ToObject<DataEntryDocument>());
  194. DoSelect(e.Rows);
  195. }
  196. private void DoSelect(CoreRow[]? rows)
  197. {
  198. var appliesTo = rows?.Length == 1
  199. ? rows[0].Get<DataEntryDocument, string>(x => x.Tag.AppliesTo)
  200. : "";
  201. var entityid = rows?.Length == 1
  202. ? rows[0].Get<DataEntryDocument, Guid>(x => x.EntityID)
  203. : Guid.Empty;
  204. var archived = rows?.Length == 1
  205. ? rows[0].Get<DataEntryDocument, DateTime>(x => x.Archived)
  206. : DateTime.MinValue;
  207. SelectionChanged?.Invoke(appliesTo, entityid, archived.IsEmpty());
  208. ViewList.CloseImageWindows();
  209. }
  210. private void _historyGrid_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  211. {
  212. DoSelect(e.Rows);
  213. }
  214. private List<DataEntryTag>? _tags;
  215. private void _uploadMenu_OnOpened(object sender, RoutedEventArgs e)
  216. {
  217. _uploadMenu.Items.Clear();
  218. _uploadMenu.AddItem("Load from File", null, _addItem_OnClick);
  219. if (Clipboard.ContainsText())
  220. {
  221. _uploadMenu.AddItem("Paste Text from Clipboard", null, _pasteItem_OnClick);
  222. }
  223. else if (Clipboard.ContainsImage())
  224. {
  225. _uploadMenu.AddItem("Paste Image from Clipboard", null, _pasteItem_OnClick);
  226. }
  227. else if (Clipboard.ContainsFileDropList())
  228. {
  229. int count = CheckAllowableFiles();
  230. if (count > 0)
  231. {
  232. _uploadMenu.AddItem($@"Paste {count} File{(count > 1 ? "s" : "")} from Clipboard", null, _pasteItem_OnClick);
  233. }
  234. }
  235. _uploadMenu.AddSeparatorIfNeeded();
  236. if(_dataEntryGrid.SelectedRows.Length > 0)
  237. {
  238. if (Security.CanEdit<DataEntryDocument>())
  239. {
  240. if (Security.IsAllowed<CanSetupDataEntryTags>())
  241. {
  242. _tags ??= DataEntryGrid.GetVisibleTagList();
  243. if(_tags.Count > 0)
  244. {
  245. var changeTag = _uploadMenu.AddItem("Set Tag", null, null);
  246. foreach(var tag in _tags)
  247. {
  248. changeTag.AddItem(tag.Name, null, tag, ChangeTag);
  249. }
  250. changeTag.AddSeparatorIfNeeded();
  251. changeTag.AddItem<DataEntryTag?>("Clear Tags", null, null, ChangeTag);
  252. }
  253. }
  254. _uploadMenu.AddItem("Set Note", null, _dataEntryGrid.SelectedRows, _changeNote_Click);
  255. _uploadMenu.AddSeparator();
  256. _uploadMenu.AddItem("Archive", null, _remove_OnClick);
  257. _uploadMenu.AddItem("Edit", null, _dataEntryGrid.SelectedRows, EditItem_Click);
  258. }
  259. if (Security.CanDelete<DataEntryDocument>())
  260. {
  261. _uploadMenu.AddItem("Delete", null, _dataEntryGrid.SelectedRows, DeleteItem_Click);
  262. }
  263. }
  264. _uploadMenu.RemoveUnnecessarySeparators();
  265. }
  266. private void DeleteItem_Click(CoreRow[] obj)
  267. {
  268. _dataEntryGrid.DeleteItems(obj);
  269. _dataEntryGrid.Refresh(false, true);
  270. }
  271. private void EditItem_Click(CoreRow[] rows)
  272. {
  273. var items = _dataEntryGrid.LoadItems(rows);
  274. if (_dataEntryGrid.EditItems(items))
  275. {
  276. _dataEntryGrid.Refresh(false, true);
  277. }
  278. }
  279. private void ChangeTag(DataEntryTag? obj)
  280. {
  281. _dataEntryGrid.DoChangeTags(obj?.ID ?? Guid.Empty);
  282. }
  283. private void _addItem_OnClick()
  284. {
  285. var ofd = new OpenFileDialog()
  286. {
  287. Filter = @"All Files (*.pdf, *.bmp, *.png, *.jpg, *.jpeg)|*.pdf;*.bmp;*.png;*.jpg;*.jpeg",
  288. Multiselect = true,
  289. Title = @"Select Files to Upload",
  290. InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  291. };
  292. if (ofd.ShowDialog() == true)
  293. {
  294. foreach (var file in ofd.FileNames)
  295. Upload(
  296. Path.GetFileName(file),
  297. new FileStream(file,FileMode.Open));
  298. }
  299. }
  300. private void _pasteItem_OnClick()
  301. {
  302. if (Clipboard.ContainsText())
  303. {
  304. Upload(
  305. $"Pasted Text {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.txt",
  306. new MemoryStream(new UTF8Encoding().GetBytes(Clipboard.GetText()))
  307. );
  308. }
  309. else if (Clipboard.ContainsImage())
  310. {
  311. var img = Clipboard.GetImage();
  312. if (img != null)
  313. {
  314. var bmp = ImageUtils.BitmapSourceToBitmap(img);
  315. using (var ms = new MemoryStream())
  316. {
  317. bmp.Save(ms, ImageFormat.Png);
  318. Upload(
  319. $"Pasted Image {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.png",
  320. ms
  321. );
  322. }
  323. }
  324. }
  325. else if (CheckAllowableFiles() > 0)
  326. {
  327. var files = Clipboard.GetFileDropList().OfType<String>().ToArray();
  328. foreach (var file in files)
  329. {
  330. Upload(
  331. Path.GetFileName(file),
  332. new FileStream(file,FileMode.Open)
  333. );
  334. }
  335. }
  336. }
  337. private void Upload(string filename, Stream data)
  338. {
  339. var doc = DataEntryReGroupWindow.RenderToPDF(filename, data);
  340. _dataEntryGrid.UploadDocument(Path.ChangeExtension(filename,"pdf"), doc.SaveToBytes(), Guid.Empty);
  341. }
  342. private static int CheckAllowableFiles()
  343. {
  344. var extensions = Clipboard.GetFileDropList().OfType<String>().Select(x => Path.GetExtension(x.ToUpper())).ToArray();
  345. return extensions.Count(x =>
  346. String.Equals(x, "PDF")
  347. || String.Equals(x, "PNG")
  348. || String.Equals(x, "JPG")
  349. || String.Equals(x, "JPEG")
  350. || String.Equals(x, "BMP")
  351. || String.Equals(x, "TXT")
  352. );
  353. }
  354. private void _pages_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  355. {
  356. if (_pages.SelectedIndex == 0)
  357. _dataEntryGrid.Refresh(false,true);
  358. else if (_pages.SelectedIndex == 1)
  359. _historyGrid.Refresh(false,true);
  360. }
  361. private void _remove_OnClick()
  362. {
  363. _dataEntryGrid.DoRemove();
  364. }
  365. private void _reopen_OnClick(object sender, RoutedEventArgs e)
  366. {
  367. _historyGrid.DoReopen();
  368. }
  369. private void _changeNote_Click(CoreRow[] rows)
  370. {
  371. var notes = rows.ToObjects<DataEntryDocument>().Select(x => x.Note).Distinct().ToArray();
  372. var note = notes.Length == 1 ? notes[0] : "";
  373. if(TextBoxDialog.Execute("Enter note:", ref note))
  374. {
  375. _dataEntryGrid.DoChangeNote(note);
  376. }
  377. }
  378. private void _dataEntryGrid_OnContextMenuOpening(object sender, ContextMenuEventArgs e)
  379. {
  380. }
  381. private void ViewList_Explode()
  382. {
  383. _dataEntryGrid.DoExplode();
  384. }
  385. private void ViewList_ExplodeAll()
  386. {
  387. _dataEntryGrid.DoExplodeAll();
  388. }
  389. private void ViewList_UpdateDocument(DataEntryDocument document, Document doc)
  390. {
  391. if (Path.GetExtension(doc.FileName) == ".pdf")
  392. {
  393. document.Thumbnail = ImageUtils.GetPDFThumbnail(doc.Data, 256, 256);
  394. }
  395. Client.Save(document, "");
  396. DataEntryCache.Cache.Add(new DocumentCachedDocument(doc));
  397. ViewList.UpdateViewList(_dataEntryGrid.SelectedRows.ToArray(x => x.ToObject<DataEntryDocument>()), true);
  398. }
  399. }