DataEntryList.xaml.cs 19 KB

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