DataEntryList.xaml.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. using System.Collections.ObjectModel;
  34. using System.Windows.Data;
  35. using PRSDesktop.Panels.DataEntry;
  36. using InABox.Wpf.Editors;
  37. namespace PRSDesktop;
  38. public static class PDFExtensions
  39. {
  40. public static IEnumerable<PdfPageBase> GetPages(this PdfDocumentBase doc)
  41. {
  42. if (doc is PdfLoadedDocument lDoc)
  43. return lDoc.Pages.Cast<PdfPageBase>();
  44. if (doc is PdfDocument pdfDoc)
  45. return pdfDoc.Pages.Cast<PdfPageBase>();
  46. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  47. }
  48. public static PdfPageBase GetPage(this PdfDocumentBase doc, int index)
  49. {
  50. if (doc is PdfLoadedDocument lDoc)
  51. return lDoc.Pages[index];
  52. if (doc is PdfDocument pdfDoc)
  53. return pdfDoc.Pages[index];
  54. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  55. }
  56. public static int PageCount(this PdfDocumentBase doc)
  57. {
  58. if (doc is PdfLoadedDocument lDoc)
  59. return lDoc.Pages.Count;
  60. if (doc is PdfDocument pdfDoc)
  61. return pdfDoc.Pages.Count;
  62. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  63. }
  64. public static PdfLoadedDocument AsLoadedDocument(this PdfDocumentBase doc)
  65. {
  66. if (doc is PdfLoadedDocument lDoc)
  67. return lDoc;
  68. if (doc is PdfDocument pdfDoc)
  69. {
  70. using var ms = new MemoryStream();
  71. pdfDoc.Save(ms);
  72. var array = ms.ToArray();
  73. return new PdfLoadedDocument(array);
  74. }
  75. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  76. }
  77. public static byte[] SaveToBytes(this PdfDocumentBase doc)
  78. {
  79. using var ms = new MemoryStream();
  80. doc.Save(ms);
  81. return ms.ToArray();
  82. }
  83. }
  84. /// <summary>
  85. /// Interaction logic for ScanPanel.xaml
  86. /// </summary>
  87. public partial class DataEntryList : UserControl, ICorePanel, IDockPanel
  88. {
  89. private List<DataEntryDocument> SelectedScans = new();
  90. public delegate void DateEntrySelectionHandler(String appliesTo, Guid entityID, bool allowprocess);
  91. public event DateEntrySelectionHandler? SelectionChanged;
  92. private readonly object _viewListLock = new object();
  93. public ObservableCollection<ImageSource> ViewList { get; init; } = new();
  94. private List<DataEntryDocumentWindow> OpenWindows = new();
  95. public DataEntryList()
  96. {
  97. BindingOperations.EnableCollectionSynchronization(ViewList, _viewListLock);
  98. InitializeComponent();
  99. }
  100. #region Panel
  101. public void Setup()
  102. {
  103. _dataEntryGrid.HiddenColumns.Add(x => x.Document.ID);
  104. _dataEntryGrid.Refresh(true, false);
  105. _historyGrid.Refresh(true, false);
  106. }
  107. public void Refresh()
  108. {
  109. if (_pages.SelectedIndex == 0)
  110. _dataEntryGrid.Refresh(false, true);
  111. else if (_pages.SelectedIndex == 1)
  112. _historyGrid.Refresh(false,true);
  113. }
  114. public void Shutdown(CancelEventArgs? cancel)
  115. {
  116. CloseImageWindows();
  117. }
  118. #endregion
  119. #region View List
  120. private static List<byte[]> RenderTextFile(string textData)
  121. {
  122. var pdfDocument = new PdfDocument();
  123. var page = pdfDocument.Pages.Add();
  124. var font = new PdfStandardFont(PdfFontFamily.Courier, 14);
  125. var textElement = new PdfTextElement(textData, font);
  126. var layoutFormat = new PdfLayoutFormat
  127. {
  128. Layout = PdfLayoutType.Paginate,
  129. Break = PdfLayoutBreakType.FitPage
  130. };
  131. textElement.Draw(page, new RectangleF(0, 0, page.GetClientSize().Width, page.GetClientSize().Height), layoutFormat);
  132. using var docStream = new MemoryStream();
  133. pdfDocument.Save(docStream);
  134. var loadeddoc = new PdfLoadedDocument(docStream.ToArray());
  135. Bitmap[] bmpImages = loadeddoc.ExportAsImage(0, loadeddoc.Pages.Count - 1);
  136. var jpgEncoder = ImageUtils.GetEncoder(ImageFormat.Jpeg)!;
  137. var quality = Encoder.Quality;
  138. var encodeParams = new EncoderParameters(1);
  139. encodeParams.Param[0] = new EncoderParameter(quality, 100L);
  140. var images = new List<byte[]>();
  141. if (bmpImages != null)
  142. foreach (var image in bmpImages)
  143. {
  144. using var data = new MemoryStream();
  145. image.Save(data, jpgEncoder, encodeParams);
  146. images.Add(data.ToArray());
  147. }
  148. return images;
  149. }
  150. private void UpdateViewList()
  151. {
  152. var selected = _dataEntryGrid.SelectedRows.Select(x => x.ToObject<DataEntryDocument>()).ToList();
  153. if (selected.Count == SelectedScans.Count && !selected.Any(x => SelectedScans.All(y => x.ID != y.ID)))
  154. return;
  155. SelectedScans = selected;
  156. ViewList.Clear();
  157. Task.Run(() =>
  158. {
  159. var docs = DataEntryCache.Cache.LoadDocuments(SelectedScans.Select(x => x.Document.ID).Distinct(), checkTimestamp: true);
  160. LoadDocuments(docs);
  161. }).ContinueWith((task) =>
  162. {
  163. if(task.Exception is not null)
  164. {
  165. MessageWindow.ShowError("An error occurred while loading the documents", task.Exception);
  166. }
  167. }, TaskScheduler.FromCurrentSynchronizationContext());
  168. }
  169. private void LoadDocuments(IEnumerable<Document> documents)
  170. {
  171. var bitmaps = new Dictionary<Guid, List<ImageSource>>();
  172. foreach (var document in documents)
  173. {
  174. List<byte[]> images;
  175. var bitmapImages = new List<ImageSource>();
  176. var extension = Path.GetExtension(document.FileName).ToLower();
  177. if (extension == ".pdf")
  178. {
  179. images = new List<byte[]>();
  180. try
  181. {
  182. bitmapImages = ImageUtils.RenderPDFToImageSources(document.Data);
  183. }
  184. catch (Exception e)
  185. {
  186. MessageBox.Show($"Cannot load document '{document.FileName}': {e.Message}");
  187. }
  188. }
  189. else if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
  190. {
  191. images = new List<byte[]> { document.Data };
  192. }
  193. else
  194. {
  195. images = ImageUtils.RenderTextFileToImages(Encoding.UTF8.GetString(document.Data));
  196. }
  197. bitmapImages.AddRange(images.Select(x =>
  198. {
  199. try
  200. {
  201. return ImageUtils.LoadImage(x);
  202. }
  203. catch (Exception e)
  204. {
  205. Dispatcher.BeginInvoke(() =>
  206. {
  207. MessageWindow.ShowError($"Cannot load document '{document.FileName}", e);
  208. });
  209. }
  210. return null;
  211. }).Where(x => x != null).Cast<ImageSource>());
  212. foreach (var image in bitmapImages)
  213. {
  214. if (!bitmaps.TryGetValue(document.ID, out var list))
  215. {
  216. list = new List<ImageSource>();
  217. bitmaps[document.ID] = list;
  218. }
  219. list.Add(image);
  220. }
  221. }
  222. lock (_viewListLock)
  223. {
  224. ViewList.Clear();
  225. foreach (var scan in SelectedScans)
  226. {
  227. if (bitmaps.TryGetValue(scan.Document.ID, out var list))
  228. {
  229. foreach (var bitmap in list)
  230. {
  231. ViewList.Add(bitmap);
  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. CloseImageWindows();
  329. }
  330. private void _historyGrid_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  331. {
  332. DoSelect(e.Rows);
  333. }
  334. private void CloseImageWindows()
  335. {
  336. while (OpenWindows.Count > 0)
  337. {
  338. var win = OpenWindows.Last();
  339. OpenWindows.RemoveAt(OpenWindows.Count - 1);
  340. win.Close();
  341. }
  342. }
  343. private void OpenImageWindow(ImageSource image)
  344. {
  345. var window = OpenWindows.FirstOrDefault(x => x.Images.Contains(image));
  346. if (window is not null)
  347. {
  348. window.Activate();
  349. }
  350. else
  351. {
  352. window = new DataEntryDocumentWindow();
  353. window.Topmost = true;
  354. window.Images.Add(image);
  355. OpenWindows.Add(window);
  356. window.Closed += OpenWindow_Closed;
  357. window.Show();
  358. }
  359. }
  360. private void Image_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  361. {
  362. if (sender is not Image image) return;
  363. if(e.ClickCount >= 2)
  364. {
  365. OpenImageWindow(image.Source);
  366. e.Handled = true;
  367. }
  368. }
  369. private void OpenWindow_Closed(object? sender, EventArgs e)
  370. {
  371. if (sender is not DataEntryDocumentWindow window) return;
  372. OpenWindows.Remove(window);
  373. }
  374. private void _Explode_OnClick(object sender, RoutedEventArgs e)
  375. {
  376. _dataEntryGrid.DoExplode();
  377. }
  378. private List<DataEntryTag>? _tags;
  379. private void _uploadMenu_OnOpened(object sender, RoutedEventArgs e)
  380. {
  381. if (Clipboard.ContainsText())
  382. {
  383. _pasteItem.Header = "Paste Text from Clipboard";
  384. _pasteItem.Visibility = Visibility.Visible;
  385. }
  386. else if (Clipboard.ContainsImage())
  387. {
  388. _pasteItem.Header = "Paste Image from Clipboard";
  389. _pasteItem.Visibility = Visibility.Visible;
  390. }
  391. else if (Clipboard.ContainsFileDropList())
  392. {
  393. int count = CheckAllowableFiles();
  394. if (count > 0)
  395. {
  396. _pasteItem.Header = $@"Paste {count} File{(count > 1 ? "s" : "")} from Clipboard";
  397. _pasteItem.Visibility = Visibility.Visible;
  398. }
  399. }
  400. else
  401. _pasteItem.Visibility = Visibility.Collapsed;
  402. _archive.Visibility = _dataEntryGrid.SelectedRows.Any() && Security.CanEdit<DataEntryDocument>()
  403. ? Visibility.Visible
  404. : Visibility.Collapsed;
  405. _archiveseparator.Visibility = _archive.Visibility;
  406. _tags ??= DataEntryGrid.GetVisibleTagList();
  407. _changeTag.Items.Clear();
  408. foreach (var tag in _tags)
  409. _changeTag.Items.Add(new MenuItem()
  410. {
  411. Header = tag.Name,
  412. Command = new Command((_) => ChangeTag(tag)) { }
  413. });
  414. _changeTag.Items.Add(new Separator());
  415. _changeTag.Items.Add(new MenuItem()
  416. {
  417. Header= "Clear Tags",
  418. Command = new Command((_) => ChangeTag(new DataEntryTag()))
  419. });
  420. _changeTag.Visibility = _dataEntryGrid.SelectedRows.Any() && _tags.Any() && (Security.CanEdit<DataEntryDocument>() || Security.IsAllowed<CanSetupDataEntryTags>())
  421. ? Visibility.Visible
  422. : Visibility.Collapsed;
  423. _changeNote.Visibility = _dataEntryGrid.SelectedRows.Any() && Security.CanEdit<DataEntryDocument>()
  424. ? Visibility.Visible
  425. : Visibility.Collapsed;
  426. _changetagseparator.Visibility = _archive.Visibility;
  427. }
  428. private void ChangeTag(object obj)
  429. {
  430. if (obj is DataEntryTag tag)
  431. _dataEntryGrid.DoChangeTags(tag.ID);
  432. }
  433. private void _addItem_OnClick(object sender, RoutedEventArgs e)
  434. {
  435. var ofd = new OpenFileDialog()
  436. {
  437. Filter = @"All Files (*.pdf, *.bmp, *.png, *.jpg, *.jpeg)|*.pdf;*.bmp;*.png;*.jpg;*.jpeg",
  438. Multiselect = true,
  439. Title = @"Select Files to Upload",
  440. InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  441. };
  442. if (ofd.ShowDialog() == DialogResult.OK)
  443. {
  444. foreach (var file in ofd.FileNames)
  445. Upload(
  446. Path.GetFileName(file),
  447. new FileStream(file,FileMode.Open));
  448. }
  449. }
  450. private void _pasteItem_OnClick(object sender, RoutedEventArgs e)
  451. {
  452. if (Clipboard.ContainsText())
  453. {
  454. Upload(
  455. $"Pasted Text {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.txt",
  456. new MemoryStream(new UTF8Encoding().GetBytes(Clipboard.GetText()))
  457. );
  458. }
  459. else if (Clipboard.ContainsImage())
  460. {
  461. var img = Clipboard.GetImage();
  462. if (img != null)
  463. {
  464. var bmp = ImageUtils.BitmapSourceToBitmap(img);
  465. using (var ms = new MemoryStream())
  466. {
  467. bmp.Save(ms, ImageFormat.Png);
  468. Upload(
  469. $"Pasted Image {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.png",
  470. ms
  471. );
  472. }
  473. }
  474. }
  475. else if (CheckAllowableFiles() > 0)
  476. {
  477. var files = Clipboard.GetFileDropList().OfType<String>().ToArray();
  478. foreach (var file in files)
  479. {
  480. Upload(
  481. Path.GetFileName(file),
  482. new FileStream(file,FileMode.Open)
  483. );
  484. }
  485. }
  486. }
  487. private void Upload(string filename, Stream data)
  488. {
  489. var doc = DataEntryReGroupWindow.RenderToPDF(filename, data);
  490. _dataEntryGrid.UploadDocument(Path.ChangeExtension(filename,"pdf"), doc.SaveToBytes(), Guid.Empty);
  491. }
  492. private static int CheckAllowableFiles()
  493. {
  494. var extensions = Clipboard.GetFileDropList().OfType<String>().Select(x => Path.GetExtension(x.ToUpper())).ToArray();
  495. return extensions.Count(x =>
  496. String.Equals(x, "PDF")
  497. || String.Equals(x, "PNG")
  498. || String.Equals(x, "JPG")
  499. || String.Equals(x, "JPEG")
  500. || String.Equals(x, "BMP")
  501. || String.Equals(x, "TXT")
  502. );
  503. }
  504. private void _pages_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  505. {
  506. if (_pages.SelectedIndex == 0)
  507. _dataEntryGrid.Refresh(false,true);
  508. else if (_pages.SelectedIndex == 1)
  509. _historyGrid.Refresh(false,true);
  510. }
  511. private void _remove_OnClick(object sender, RoutedEventArgs e)
  512. {
  513. _dataEntryGrid.DoRemove();
  514. }
  515. private void _reopen_OnClick(object sender, RoutedEventArgs e)
  516. {
  517. _historyGrid.DoReopen();
  518. }
  519. private void _changeNote_Click(object sender, RoutedEventArgs e)
  520. {
  521. var notes = _dataEntryGrid.SelectedRows.ToObjects<DataEntryDocument>().Select(x => x.Note).Distinct().ToArray();
  522. var note = notes.Length == 1 ? notes[0] : "";
  523. if(TextEdit.Execute("Enter note:", ref note))
  524. {
  525. _dataEntryGrid.DoChangeNote(note);
  526. }
  527. }
  528. private void _dataEntryGrid_OnContextMenuOpening(object sender, ContextMenuEventArgs e)
  529. {
  530. }
  531. private void _ShowImage_Click(object sender, RoutedEventArgs e)
  532. {
  533. if (sender is not MenuItem item || item.Tag is not ImageSource image) return;
  534. OpenImageWindow(image);
  535. }
  536. }