DataEntryList.xaml.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. namespace PRSDesktop;
  37. public static class PDFExtensions
  38. {
  39. public static IEnumerable<PdfPageBase> GetPages(this PdfDocumentBase doc)
  40. {
  41. if (doc is PdfLoadedDocument lDoc)
  42. return lDoc.Pages.Cast<PdfPageBase>();
  43. if (doc is PdfDocument pdfDoc)
  44. return pdfDoc.Pages.Cast<PdfPageBase>();
  45. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  46. }
  47. public static PdfPageBase GetPage(this PdfDocumentBase doc, int index)
  48. {
  49. if (doc is PdfLoadedDocument lDoc)
  50. return lDoc.Pages[index];
  51. if (doc is PdfDocument pdfDoc)
  52. return pdfDoc.Pages[index];
  53. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  54. }
  55. public static int PageCount(this PdfDocumentBase doc)
  56. {
  57. if (doc is PdfLoadedDocument lDoc)
  58. return lDoc.Pages.Count;
  59. if (doc is PdfDocument pdfDoc)
  60. return pdfDoc.Pages.Count;
  61. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  62. }
  63. public static PdfLoadedDocument AsLoadedDocument(this PdfDocumentBase doc)
  64. {
  65. if (doc is PdfLoadedDocument lDoc)
  66. return lDoc;
  67. if (doc is PdfDocument pdfDoc)
  68. {
  69. using var ms = new MemoryStream();
  70. pdfDoc.Save(ms);
  71. var array = ms.ToArray();
  72. return new PdfLoadedDocument(array);
  73. }
  74. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  75. }
  76. public static byte[] SaveToBytes(this PdfDocumentBase doc)
  77. {
  78. using var ms = new MemoryStream();
  79. doc.Save(ms);
  80. return ms.ToArray();
  81. }
  82. }
  83. /// <summary>
  84. /// Interaction logic for ScanPanel.xaml
  85. /// </summary>
  86. public partial class DataEntryList : UserControl, ICorePanel, IDockPanel
  87. {
  88. private List<DataEntryDocument> SelectedScans = new();
  89. public delegate void DateEntrySelectionHandler(String appliesTo, Guid entityID, bool allowprocess);
  90. public event DateEntrySelectionHandler? SelectionChanged;
  91. private readonly object _viewListLock = new object();
  92. public ObservableCollection<ImageSource> ViewList { get; init; } = new();
  93. private List<DataEntryDocumentWindow> OpenWindows = new();
  94. public DataEntryList()
  95. {
  96. BindingOperations.EnableCollectionSynchronization(ViewList, _viewListLock);
  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. CloseImageWindows();
  116. }
  117. #endregion
  118. #region View List
  119. private static List<byte[]> RenderTextFile(string textData)
  120. {
  121. var pdfDocument = new PdfDocument();
  122. var page = pdfDocument.Pages.Add();
  123. var font = new PdfStandardFont(PdfFontFamily.Courier, 14);
  124. var textElement = new PdfTextElement(textData, font);
  125. var layoutFormat = new PdfLayoutFormat
  126. {
  127. Layout = PdfLayoutType.Paginate,
  128. Break = PdfLayoutBreakType.FitPage
  129. };
  130. textElement.Draw(page, new RectangleF(0, 0, page.GetClientSize().Width, page.GetClientSize().Height), layoutFormat);
  131. using var docStream = new MemoryStream();
  132. pdfDocument.Save(docStream);
  133. var loadeddoc = new PdfLoadedDocument(docStream.ToArray());
  134. Bitmap[] bmpImages = loadeddoc.ExportAsImage(0, loadeddoc.Pages.Count - 1);
  135. var jpgEncoder = ImageUtils.GetEncoder(ImageFormat.Jpeg)!;
  136. var quality = Encoder.Quality;
  137. var encodeParams = new EncoderParameters(1);
  138. encodeParams.Param[0] = new EncoderParameter(quality, 100L);
  139. var images = new List<byte[]>();
  140. if (bmpImages != null)
  141. foreach (var image in bmpImages)
  142. {
  143. using var data = new MemoryStream();
  144. image.Save(data, jpgEncoder, encodeParams);
  145. images.Add(data.ToArray());
  146. }
  147. return images;
  148. }
  149. private void UpdateViewList()
  150. {
  151. var selected = _dataEntryGrid.SelectedRows.Select(x => x.ToObject<DataEntryDocument>()).ToList();
  152. if (selected.Count == SelectedScans.Count && !selected.Any(x => SelectedScans.All(y => x.ID != y.ID)))
  153. return;
  154. SelectedScans = selected;
  155. ViewList.Clear();
  156. Task.Run(() =>
  157. {
  158. var docs = DataEntryCache.Cache.LoadDocuments(SelectedScans.Select(x => x.Document.ID).Distinct(), checkTimestamp: true);
  159. LoadDocuments(docs);
  160. }).ContinueWith((task) =>
  161. {
  162. if(task.Exception is not null)
  163. {
  164. MessageWindow.ShowError("An error occurred while loading the documents", task.Exception);
  165. }
  166. }, TaskScheduler.FromCurrentSynchronizationContext());
  167. }
  168. private void LoadDocuments(IEnumerable<Document> documents)
  169. {
  170. var bitmaps = new Dictionary<Guid, List<ImageSource>>();
  171. foreach (var document in documents)
  172. {
  173. List<byte[]> images;
  174. var bitmapImages = new List<ImageSource>();
  175. var extension = Path.GetExtension(document.FileName).ToLower();
  176. if (extension == ".pdf")
  177. {
  178. images = new List<byte[]>();
  179. try
  180. {
  181. bitmapImages = ImageUtils.RenderPDFToImageSources(document.Data);
  182. }
  183. catch (Exception e)
  184. {
  185. MessageBox.Show($"Cannot load document '{document.FileName}': {e.Message}");
  186. }
  187. }
  188. else if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
  189. {
  190. images = new List<byte[]> { document.Data };
  191. }
  192. else
  193. {
  194. images = ImageUtils.RenderTextFileToImages(Encoding.UTF8.GetString(document.Data));
  195. }
  196. bitmapImages.AddRange(images.Select(x =>
  197. {
  198. try
  199. {
  200. return ImageUtils.LoadImage(x);
  201. }
  202. catch (Exception e)
  203. {
  204. Dispatcher.BeginInvoke(() =>
  205. {
  206. MessageWindow.ShowError($"Cannot load document '{document.FileName}", e);
  207. });
  208. }
  209. return null;
  210. }).Where(x => x != null).Cast<ImageSource>());
  211. foreach (var image in bitmapImages)
  212. {
  213. if (!bitmaps.TryGetValue(document.ID, out var list))
  214. {
  215. list = new List<ImageSource>();
  216. bitmaps[document.ID] = list;
  217. }
  218. list.Add(image);
  219. }
  220. }
  221. lock (_viewListLock)
  222. {
  223. ViewList.Clear();
  224. foreach (var scan in SelectedScans)
  225. {
  226. if (bitmaps.TryGetValue(scan.Document.ID, out var list))
  227. {
  228. foreach (var bitmap in list)
  229. {
  230. ViewList.Add(bitmap);
  231. }
  232. }
  233. }
  234. }
  235. }
  236. #endregion
  237. #region Uploading
  238. private static byte[] RenderData(ref string filename, byte[] data)
  239. {
  240. var extension = Path.GetExtension(filename).ToLower();
  241. if ((extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp") && ImageUtils.TryGetImageType(data, out var format))
  242. {
  243. return data;
  244. }
  245. else if (extension == ".pdf")
  246. {
  247. return data;
  248. }
  249. else
  250. {
  251. using var stream = new MemoryStream(data);
  252. filename = Path.ChangeExtension(filename, "pdf");
  253. return DataEntryReGroupWindow.RenderToPDF(filename, stream).SaveToBytes();
  254. }
  255. throw new Exception("Could not render file to PDF");
  256. }
  257. private void DynamicTabItem_Drop(object sender, DragEventArgs e)
  258. {
  259. Task.Run(() =>
  260. {
  261. Dispatcher.Invoke(() =>
  262. {
  263. Progress.Show("Uploading documents");
  264. try
  265. {
  266. var result = DocumentUtils.HandleFileDrop(e);
  267. if (result is not null)
  268. {
  269. foreach (var (filename, stream) in result)
  270. {
  271. var newFilename = filename;
  272. byte[] data;
  273. if (stream is null)
  274. {
  275. data = File.ReadAllBytes(newFilename);
  276. }
  277. else
  278. {
  279. using var memStream = new MemoryStream();
  280. stream.CopyTo(memStream);
  281. data = memStream.ToArray();
  282. }
  283. data = RenderData(ref newFilename, data);
  284. _dataEntryGrid.UploadDocument(newFilename, data, Guid.Empty);
  285. }
  286. }
  287. Progress.Close();
  288. }
  289. catch (Exception e)
  290. {
  291. Progress.Close();
  292. MessageWindow.ShowError("Could not upload documents.", e);
  293. }
  294. });
  295. });
  296. }
  297. private void DynamicTabItem_DragOver(object sender, DragEventArgs e)
  298. {
  299. if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent("FileGroupDescriptor"))
  300. {
  301. e.Effects = DragDropEffects.Copy;
  302. }
  303. else
  304. {
  305. e.Effects = DragDropEffects.None;
  306. }
  307. e.Handled = true;
  308. }
  309. #endregion
  310. private void _documents_OnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  311. {
  312. UpdateViewList();
  313. DoSelect(e.Rows);
  314. }
  315. private void DoSelect(CoreRow[] rows)
  316. {
  317. var appliesTo = rows?.Length == 1
  318. ? rows[0].Get<DataEntryDocument, string>(x => x.Tag.AppliesTo)
  319. : "";
  320. var entityid = rows?.Length == 1
  321. ? rows[0].Get<DataEntryDocument, Guid>(x => x.EntityID)
  322. : Guid.Empty;
  323. var archived = rows?.Length == 1
  324. ? rows[0].Get<DataEntryDocument, DateTime>(x => x.Archived)
  325. : DateTime.MinValue;
  326. SelectionChanged?.Invoke(appliesTo, entityid, archived.IsEmpty());
  327. CloseImageWindows();
  328. }
  329. private void _historyGrid_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  330. {
  331. DoSelect(e.Rows);
  332. }
  333. private void CloseImageWindows()
  334. {
  335. while (OpenWindows.Count > 0)
  336. {
  337. var win = OpenWindows.Last();
  338. OpenWindows.RemoveAt(OpenWindows.Count - 1);
  339. win.Close();
  340. }
  341. }
  342. private void OpenImageWindow(ImageSource image)
  343. {
  344. var window = OpenWindows.FirstOrDefault(x => x.Images.Contains(image));
  345. if (window is not null)
  346. {
  347. window.Activate();
  348. }
  349. else
  350. {
  351. window = new DataEntryDocumentWindow();
  352. window.Topmost = true;
  353. window.Images.Add(image);
  354. OpenWindows.Add(window);
  355. window.Closed += OpenWindow_Closed;
  356. window.Show();
  357. }
  358. }
  359. private void Image_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  360. {
  361. if (sender is not Image image) return;
  362. if(e.ClickCount >= 2)
  363. {
  364. OpenImageWindow(image.Source);
  365. e.Handled = true;
  366. }
  367. }
  368. private void OpenWindow_Closed(object? sender, EventArgs e)
  369. {
  370. if (sender is not DataEntryDocumentWindow window) return;
  371. OpenWindows.Remove(window);
  372. }
  373. private void _Explode_OnClick(object sender, RoutedEventArgs e)
  374. {
  375. _dataEntryGrid.DoExplode();
  376. }
  377. private List<DataEntryTag>? _tags;
  378. private void _uploadMenu_OnOpened(object sender, RoutedEventArgs e)
  379. {
  380. if (Clipboard.ContainsText())
  381. {
  382. _pasteItem.Header = "Paste Text from Clipboard";
  383. _pasteItem.Visibility = Visibility.Visible;
  384. }
  385. else if (Clipboard.ContainsImage())
  386. {
  387. _pasteItem.Header = "Paste Image from Clipboard";
  388. _pasteItem.Visibility = Visibility.Visible;
  389. }
  390. else if (Clipboard.ContainsFileDropList())
  391. {
  392. int count = CheckAllowableFiles();
  393. if (count > 0)
  394. {
  395. _pasteItem.Header = $@"Paste {count} File{(count > 1 ? "s" : "")} from Clipboard";
  396. _pasteItem.Visibility = Visibility.Visible;
  397. }
  398. }
  399. else
  400. _pasteItem.Visibility = Visibility.Collapsed;
  401. _archive.Visibility = _dataEntryGrid.SelectedRows.Any() && Security.CanEdit<DataEntryDocument>()
  402. ? Visibility.Visible
  403. : Visibility.Collapsed;
  404. _archiveseparator.Visibility = _archive.Visibility;
  405. _tags ??= DataEntryGrid.GetVisibleTagList();
  406. _changeTag.Items.Clear();
  407. foreach (var tag in _tags)
  408. _changeTag.Items.Add(new MenuItem()
  409. {
  410. Header = tag.Name,
  411. Command = new Command((_) => ChangeTag(tag)) { }
  412. });
  413. _changeTag.Items.Add(new Separator());
  414. _changeTag.Items.Add(new MenuItem()
  415. {
  416. Header= "Clear Tags",
  417. Command = new Command((_) => ChangeTag(new DataEntryTag()))
  418. });
  419. _changeTag.Visibility = _dataEntryGrid.SelectedRows.Any() && _tags.Any() && (Security.CanEdit<DataEntryDocument>() || Security.IsAllowed<CanSetupDataEntryTags>())
  420. ? Visibility.Visible
  421. : Visibility.Collapsed;
  422. _changetagseparator.Visibility = _archive.Visibility;
  423. }
  424. private void ChangeTag(object obj)
  425. {
  426. if (obj is DataEntryTag tag)
  427. _dataEntryGrid.DoChangeTags(tag.ID);
  428. }
  429. private void _addItem_OnClick(object sender, RoutedEventArgs e)
  430. {
  431. var ofd = new OpenFileDialog()
  432. {
  433. Filter = @"All Files (*.pdf, *.bmp, *.png, *.jpg, *.jpeg)|*.pdf;*.bmp;*.png;*.jpg;*.jpeg",
  434. Multiselect = true,
  435. Title = @"Select Files to Upload",
  436. InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  437. };
  438. if (ofd.ShowDialog() == DialogResult.OK)
  439. {
  440. foreach (var file in ofd.FileNames)
  441. Upload(
  442. Path.GetFileName(file),
  443. new FileStream(file,FileMode.Open));
  444. }
  445. }
  446. private void _pasteItem_OnClick(object sender, RoutedEventArgs e)
  447. {
  448. if (Clipboard.ContainsText())
  449. {
  450. Upload(
  451. $"Pasted Text {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.txt",
  452. new MemoryStream(new UTF8Encoding().GetBytes(Clipboard.GetText()))
  453. );
  454. }
  455. else if (Clipboard.ContainsImage())
  456. {
  457. var img = Clipboard.GetImage();
  458. if (img != null)
  459. {
  460. var bmp = ImageUtils.BitmapSourceToBitmap(img);
  461. using (var ms = new MemoryStream())
  462. {
  463. bmp.Save(ms, ImageFormat.Png);
  464. Upload(
  465. $"Pasted Image {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.png",
  466. ms
  467. );
  468. }
  469. }
  470. }
  471. else if (CheckAllowableFiles() > 0)
  472. {
  473. var files = Clipboard.GetFileDropList().OfType<String>().ToArray();
  474. foreach (var file in files)
  475. {
  476. Upload(
  477. Path.GetFileName(file),
  478. new FileStream(file,FileMode.Open)
  479. );
  480. }
  481. }
  482. }
  483. private void Upload(string filename, Stream data)
  484. {
  485. var doc = DataEntryReGroupWindow.RenderToPDF(filename, data);
  486. _dataEntryGrid.UploadDocument(Path.ChangeExtension(filename,"pdf"), doc.SaveToBytes(), Guid.Empty);
  487. }
  488. private static int CheckAllowableFiles()
  489. {
  490. var extensions = Clipboard.GetFileDropList().OfType<String>().Select(x => Path.GetExtension(x.ToUpper())).ToArray();
  491. return extensions.Count(x =>
  492. String.Equals(x, "PDF")
  493. || String.Equals(x, "PNG")
  494. || String.Equals(x, "JPG")
  495. || String.Equals(x, "JPEG")
  496. || String.Equals(x, "BMP")
  497. || String.Equals(x, "TXT")
  498. );
  499. }
  500. private void _pages_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  501. {
  502. if (_pages.SelectedIndex == 0)
  503. _dataEntryGrid.Refresh(false,true);
  504. else if (_pages.SelectedIndex == 1)
  505. _historyGrid.Refresh(false,true);
  506. }
  507. private void _remove_OnClick(object sender, RoutedEventArgs e)
  508. {
  509. _dataEntryGrid.DoRemove();
  510. }
  511. private void _reopen_OnClick(object sender, RoutedEventArgs e)
  512. {
  513. _historyGrid.DoReopen();
  514. }
  515. private void _dataEntryGrid_OnContextMenuOpening(object sender, ContextMenuEventArgs e)
  516. {
  517. }
  518. private void _ShowImage_Click(object sender, RoutedEventArgs e)
  519. {
  520. if (sender is not MenuItem item || item.Tag is not ImageSource image) return;
  521. OpenImageWindow(image);
  522. }
  523. }