DataEntryList.xaml.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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.Imaging;
  17. using InABox.DynamicGrid;
  18. using InABox.WPF;
  19. using Encoder = System.Drawing.Imaging.Encoder;
  20. using Path = System.IO.Path;
  21. using Image = System.Windows.Controls.Image;
  22. using System.ComponentModel;
  23. using System.Windows.Controls;
  24. using System.Windows.Forms;
  25. using Clipboard = System.Windows.Clipboard;
  26. using DataFormats = System.Windows.DataFormats;
  27. using DragDropEffects = System.Windows.DragDropEffects;
  28. using DragEventArgs = System.Windows.DragEventArgs;
  29. using MessageBox = System.Windows.MessageBox;
  30. using UserControl = System.Windows.Controls.UserControl;
  31. namespace PRSDesktop
  32. {
  33. public static class PDFExtensions
  34. {
  35. public static IEnumerable<PdfPageBase> GetPages(this PdfDocumentBase doc)
  36. {
  37. if (doc is PdfLoadedDocument lDoc)
  38. return lDoc.Pages.Cast<PdfPageBase>();
  39. if (doc is PdfDocument pdfDoc)
  40. return pdfDoc.Pages.Cast<PdfPageBase>();
  41. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  42. }
  43. public static PdfPageBase GetPage(this PdfDocumentBase doc, int index)
  44. {
  45. if (doc is PdfLoadedDocument lDoc)
  46. return lDoc.Pages[index];
  47. if (doc is PdfDocument pdfDoc)
  48. return pdfDoc.Pages[index];
  49. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  50. }
  51. public static int PageCount(this PdfDocumentBase doc)
  52. {
  53. if (doc is PdfLoadedDocument lDoc)
  54. return lDoc.Pages.Count;
  55. if (doc is PdfDocument pdfDoc)
  56. return pdfDoc.Pages.Count;
  57. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  58. }
  59. public static PdfLoadedDocument AsLoadedDocument(this PdfDocumentBase doc)
  60. {
  61. if (doc is PdfLoadedDocument lDoc)
  62. return lDoc;
  63. if (doc is PdfDocument pdfDoc)
  64. {
  65. using var ms = new MemoryStream();
  66. pdfDoc.Save(ms);
  67. var array = ms.ToArray();
  68. return new PdfLoadedDocument(array);
  69. }
  70. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  71. }
  72. public static byte[] SaveToBytes(this PdfDocumentBase doc)
  73. {
  74. using var ms = new MemoryStream();
  75. doc.Save(ms);
  76. return ms.ToArray();
  77. }
  78. }
  79. /// <summary>
  80. /// Interaction logic for ScanPanel.xaml
  81. /// </summary>
  82. public partial class DataEntryList : UserControl, ICorePanel, IDockPanel
  83. {
  84. private List<DataEntryDocument> SelectedScans = new();
  85. public delegate void DateEntrySelectionHandler(String appliesTo, Guid entityID, bool allowprocess);
  86. public event DateEntrySelectionHandler? SelectionChanged;
  87. public DataEntryList()
  88. {
  89. InitializeComponent();
  90. }
  91. #region Panel
  92. public void Setup()
  93. {
  94. _dataEntryGrid.HiddenColumns.Add(x => x.Document.ID);
  95. _dataEntryGrid.Refresh(true, false);
  96. _historyGrid.Refresh(true, false);
  97. }
  98. public void Refresh()
  99. {
  100. if (_pages.SelectedIndex == 0)
  101. _dataEntryGrid.Refresh(false, true);
  102. else if (_pages.SelectedIndex == 1)
  103. _historyGrid.Refresh(false,true);
  104. }
  105. public void Shutdown(CancelEventArgs? cancel)
  106. {
  107. }
  108. #endregion
  109. #region View List
  110. private static List<byte[]> RenderTextFile(string textData)
  111. {
  112. var pdfDocument = new PdfDocument();
  113. var page = pdfDocument.Pages.Add();
  114. var font = new PdfStandardFont(PdfFontFamily.Courier, 14);
  115. var textElement = new PdfTextElement(textData, font);
  116. var layoutFormat = new PdfLayoutFormat
  117. {
  118. Layout = PdfLayoutType.Paginate,
  119. Break = PdfLayoutBreakType.FitPage
  120. };
  121. textElement.Draw(page, new RectangleF(0, 0, page.GetClientSize().Width, page.GetClientSize().Height), layoutFormat);
  122. using var docStream = new MemoryStream();
  123. pdfDocument.Save(docStream);
  124. var loadeddoc = new PdfLoadedDocument(docStream.ToArray());
  125. Bitmap[] bmpImages = loadeddoc.ExportAsImage(0, loadeddoc.Pages.Count - 1);
  126. var jpgEncoder = ImageUtils.GetEncoder(ImageFormat.Jpeg)!;
  127. var quality = Encoder.Quality;
  128. var encodeParams = new EncoderParameters(1);
  129. encodeParams.Param[0] = new EncoderParameter(quality, 100L);
  130. var images = new List<byte[]>();
  131. if (bmpImages != null)
  132. foreach (var image in bmpImages)
  133. {
  134. using var data = new MemoryStream();
  135. image.Save(data, jpgEncoder, encodeParams);
  136. images.Add(data.ToArray());
  137. }
  138. return images;
  139. }
  140. private void UpdateViewList()
  141. {
  142. var selected = _dataEntryGrid.SelectedRows.Select(x => x.ToObject<DataEntryDocument>()).ToList();
  143. if (selected.Count == SelectedScans.Count && !selected.Any(x => SelectedScans.All(y => x.ID != y.ID)))
  144. return;
  145. SelectedScans = selected;
  146. ViewListPanel.Children.Clear();
  147. var docIDs = SelectedScans.Select(x => x.Document.ID).Distinct().ToArray();
  148. new Client<Document>()
  149. .Query(
  150. new Filter<Document>(x => x.ID).InList(docIDs),
  151. new Columns<Document>(x => x.ID).Add(x => x.Data).Add(x => x.FileName),
  152. null,(o,e) => Dispatcher.BeginInvoke(() => LoadDocuments(o)));
  153. }
  154. private void LoadDocuments(CoreTable? data)
  155. {
  156. var documents = data?.ToObjects<Document>() ?? Array.Empty<Document>();
  157. var bitmaps = new Dictionary<Guid, List<BitmapImage>>();
  158. foreach (var document in documents)
  159. {
  160. List<byte[]> images;
  161. var extension = Path.GetExtension(document.FileName).ToLower();
  162. if (extension == ".pdf")
  163. {
  164. try
  165. {
  166. images = ImageUtils.RenderPDFToImages(document.Data);
  167. }
  168. catch (Exception e)
  169. {
  170. MessageBox.Show($"Cannot load document '{document.FileName}': {e.Message}");
  171. images = new List<byte[]>();
  172. }
  173. }
  174. else if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
  175. {
  176. images = new List<byte[]> { document.Data };
  177. }
  178. else
  179. {
  180. images = ImageUtils.RenderTextFileToImages(Encoding.UTF8.GetString(document.Data));
  181. }
  182. foreach (var imageData in images)
  183. {
  184. try
  185. {
  186. if (!bitmaps.TryGetValue(document.ID, out var list))
  187. {
  188. list = new List<BitmapImage>();
  189. bitmaps[document.ID] = list;
  190. }
  191. list.Add(ImageUtils.LoadImage(imageData));
  192. }
  193. catch (Exception e)
  194. {
  195. MessageBox.Show($"Cannot load document '{document.FileName}': {e.Message}");
  196. }
  197. }
  198. }
  199. foreach(var scan in SelectedScans)
  200. {
  201. if(bitmaps.TryGetValue(scan.Document.ID, out var list))
  202. {
  203. foreach(var bitmap in list)
  204. {
  205. var image = new Image
  206. {
  207. Source = bitmap,
  208. Margin = new Thickness(0, 0, 0, 20),
  209. ContextMenu = ViewListPanel.ContextMenu
  210. };
  211. ViewListPanel.Children.Add(image);
  212. }
  213. }
  214. }
  215. }
  216. #endregion
  217. #region Uploading
  218. private void DynamicTabItem_Drop(object sender, DragEventArgs e)
  219. {
  220. Task.Run(() =>
  221. {
  222. var docs = DataEntryReGroupWindow.HandleFileDrop(e);
  223. if (docs is not null)
  224. {
  225. foreach(var (filename, doc) in docs)
  226. {
  227. _dataEntryGrid.UploadDocument(Path.ChangeExtension(filename, ".pdf"), doc.SaveToBytes(), Guid.Empty);
  228. }
  229. /*Dispatcher.Invoke(() =>
  230. {
  231. ScanGrid.ShowDocumentWindow(pages, filename);
  232. });*/
  233. }
  234. });
  235. }
  236. private void DynamicTabItem_DragOver(object sender, DragEventArgs e)
  237. {
  238. if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent("FileGroupDescriptor"))
  239. {
  240. e.Effects = DragDropEffects.Copy;
  241. }
  242. else
  243. {
  244. e.Effects = DragDropEffects.None;
  245. }
  246. e.Handled = true;
  247. }
  248. #endregion
  249. private void _documents_OnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  250. {
  251. UpdateViewList();
  252. DoSelect(e.Rows);
  253. }
  254. private void DoSelect(CoreRow[] rows)
  255. {
  256. var appliesTo = rows?.Length == 1
  257. ? rows[0].Get<DataEntryDocument, string>(x => x.Tag.AppliesTo)
  258. : "";
  259. var entityid = rows?.Length == 1
  260. ? rows[0].Get<DataEntryDocument, Guid>(x => x.EntityID)
  261. : Guid.Empty;
  262. var archived = rows?.Length == 1
  263. ? rows[0].Get<DataEntryDocument, DateTime>(x => x.Archived)
  264. : DateTime.MinValue;
  265. SelectionChanged?.Invoke(appliesTo, entityid, archived.IsEmpty());
  266. }
  267. private void _historyGrid_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  268. {
  269. DoSelect(e.Rows);
  270. }
  271. private void _Explode_OnClick(object sender, RoutedEventArgs e)
  272. {
  273. _dataEntryGrid.DoExplode();
  274. }
  275. private List<DataEntryTag>? _tags;
  276. private void _uploadMenu_OnOpened(object sender, RoutedEventArgs e)
  277. {
  278. if (Clipboard.ContainsText())
  279. {
  280. _pasteItem.Header = "Paste Text from Clipboard";
  281. _pasteItem.Visibility = Visibility.Visible;
  282. }
  283. else if (Clipboard.ContainsImage())
  284. {
  285. _pasteItem.Header = "Paste Image from Clipboard";
  286. _pasteItem.Visibility = Visibility.Visible;
  287. }
  288. else if (Clipboard.ContainsFileDropList())
  289. {
  290. int count = CheckAllowableFiles();
  291. if (count > 0)
  292. {
  293. _pasteItem.Header = $@"Paste {count} File{(count > 1 ? "s" : "")} from Clipboard";
  294. _pasteItem.Visibility = Visibility.Visible;
  295. }
  296. }
  297. else
  298. _pasteItem.Visibility = Visibility.Collapsed;
  299. _archive.Visibility = _dataEntryGrid.SelectedRows.Any() && Security.CanEdit<DataEntryDocument>()
  300. ? Visibility.Visible
  301. : Visibility.Collapsed;
  302. _archiveseparator.Visibility = _archive.Visibility;
  303. _tags ??= DataEntryGrid.GetVisibleTagList();
  304. _changeTag.Items.Clear();
  305. foreach (var tag in _tags)
  306. _changeTag.Items.Add(new MenuItem()
  307. {
  308. Header = tag.Name,
  309. Command = new Command((_) => ChangeTag(tag)) { }
  310. });
  311. _changeTag.Items.Add(new Separator());
  312. _changeTag.Items.Add(new MenuItem()
  313. {
  314. Header= "Clear Tags",
  315. Command = new Command((_) => ChangeTag(new DataEntryTag()))
  316. });
  317. _changeTag.Visibility = _dataEntryGrid.SelectedRows.Any() && _tags.Any() && (Security.CanEdit<DataEntryDocument>() || Security.IsAllowed<CanSetupDataEntryTags>())
  318. ? Visibility.Visible
  319. : Visibility.Collapsed;
  320. _changetagseparator.Visibility = _archive.Visibility;
  321. }
  322. private void ChangeTag(object obj)
  323. {
  324. if (obj is DataEntryTag tag)
  325. _dataEntryGrid.DoChangeTags(tag.ID);
  326. }
  327. private void _addItem_OnClick(object sender, RoutedEventArgs e)
  328. {
  329. var ofd = new OpenFileDialog()
  330. {
  331. Filter = @"All Files (*.pdf, *.bmp, *.png, *.jpg, *.jpeg)|*.pdf;*.bmp;*.png;*.jpg;*.jpeg",
  332. Multiselect = true,
  333. Title = @"Select Files to Upload",
  334. InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  335. };
  336. if (ofd.ShowDialog() == DialogResult.OK)
  337. {
  338. foreach (var file in ofd.FileNames)
  339. Upload(
  340. Path.GetFileName(file),
  341. new FileStream(file,FileMode.Open));
  342. }
  343. }
  344. private void _pasteItem_OnClick(object sender, RoutedEventArgs e)
  345. {
  346. if (Clipboard.ContainsText())
  347. {
  348. Upload(
  349. $"Pasted Text {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.txt",
  350. new MemoryStream(new UTF8Encoding().GetBytes(Clipboard.GetText()))
  351. );
  352. }
  353. else if (Clipboard.ContainsImage())
  354. {
  355. var img = Clipboard.GetImage();
  356. if (img != null)
  357. {
  358. var bmp = ImageUtils.BitmapSourceToBitmap(img);
  359. using (var ms = new MemoryStream())
  360. {
  361. bmp.Save(ms, ImageFormat.Png);
  362. Upload(
  363. $"Pasted Image {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.png",
  364. ms
  365. );
  366. }
  367. }
  368. }
  369. else if (CheckAllowableFiles() > 0)
  370. {
  371. var files = Clipboard.GetFileDropList().OfType<String>().ToArray();
  372. foreach (var file in files)
  373. {
  374. Upload(
  375. Path.GetFileName(file),
  376. new FileStream(file,FileMode.Open)
  377. );
  378. }
  379. }
  380. }
  381. private void Upload(string filename, Stream data)
  382. {
  383. var doc = DataEntryReGroupWindow.RenderToPDF(filename, data);
  384. _dataEntryGrid.UploadDocument(Path.ChangeExtension(filename,"pdf"), doc.SaveToBytes(), Guid.Empty);
  385. }
  386. private static int CheckAllowableFiles()
  387. {
  388. var extensions = Clipboard.GetFileDropList().OfType<String>().Select(x => Path.GetExtension(x.ToUpper())).ToArray();
  389. return extensions.Count(x =>
  390. String.Equals(x, "PDF")
  391. || String.Equals(x, "PNG")
  392. || String.Equals(x, "JPG")
  393. || String.Equals(x, "JPEG")
  394. || String.Equals(x, "BMP")
  395. || String.Equals(x, "TXT")
  396. );
  397. }
  398. private void _pages_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  399. {
  400. if (_pages.SelectedIndex == 0)
  401. _dataEntryGrid.Refresh(false,true);
  402. else if (_pages.SelectedIndex == 1)
  403. _historyGrid.Refresh(false,true);
  404. }
  405. private void _remove_OnClick(object sender, RoutedEventArgs e)
  406. {
  407. _dataEntryGrid.DoRemove();
  408. }
  409. private void _reopen_OnClick(object sender, RoutedEventArgs e)
  410. {
  411. _historyGrid.DoReopen();
  412. }
  413. private void _dataEntryGrid_OnContextMenuOpening(object sender, ContextMenuEventArgs e)
  414. {
  415. }
  416. }
  417. }