using Comal.Classes; using InABox.Clients; using InABox.Core; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf; using System; using System.Collections.Generic; using System.Drawing.Imaging; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using InABox.DynamicGrid; using InABox.WPF; using InABox.Wpf; using Encoder = System.Drawing.Imaging.Encoder; using Path = System.IO.Path; using Image = System.Windows.Controls.Image; using System.ComponentModel; using System.Windows.Controls; using Clipboard = System.Windows.Clipboard; using DataFormats = System.Windows.DataFormats; using DragDropEffects = System.Windows.DragDropEffects; using DragEventArgs = System.Windows.DragEventArgs; using MessageBox = System.Windows.MessageBox; using UserControl = System.Windows.Controls.UserControl; using InABox.Wpf; using System.Collections.ObjectModel; using System.Windows.Data; using PRSDesktop.Panels.DataEntry; using InABox.Wpf.Editors; using System.Timers; using Microsoft.Win32; using javax.xml.crypto; namespace PRSDesktop; public static class PDFExtensions { public static IEnumerable GetPages(this PdfDocumentBase doc) { if (doc is PdfLoadedDocument lDoc) return lDoc.Pages.Cast(); if (doc is PdfDocument pdfDoc) return pdfDoc.Pages.Cast(); throw new Exception($"Unsupported PDF Document type {doc.GetType()}"); } public static PdfPageBase GetPage(this PdfDocumentBase doc, int index) { if (doc is PdfLoadedDocument lDoc) return lDoc.Pages[index]; if (doc is PdfDocument pdfDoc) return pdfDoc.Pages[index]; throw new Exception($"Unsupported PDF Document type {doc.GetType()}"); } public static int PageCount(this PdfDocumentBase doc) { if (doc is PdfLoadedDocument lDoc) return lDoc.Pages.Count; if (doc is PdfDocument pdfDoc) return pdfDoc.Pages.Count; throw new Exception($"Unsupported PDF Document type {doc.GetType()}"); } public static PdfLoadedDocument AsLoadedDocument(this PdfDocumentBase doc) { if (doc is PdfLoadedDocument lDoc) return lDoc; if (doc is PdfDocument pdfDoc) { using var ms = new MemoryStream(); pdfDoc.Save(ms); var array = ms.ToArray(); return new PdfLoadedDocument(array); } throw new Exception($"Unsupported PDF Document type {doc.GetType()}"); } public static byte[] SaveToBytes(this PdfDocumentBase doc) { using var ms = new MemoryStream(); doc.Save(ms); return ms.ToArray(); } } /// /// Interaction logic for ScanPanel.xaml /// public partial class DataEntryList : UserControl, ICorePanel, IDockPanel { private List SelectedScans = new(); public delegate void DateEntrySelectionHandler(String appliesTo, Guid entityID, bool allowprocess); public event DateEntrySelectionHandler? SelectionChanged; public DataEntryList() { InitializeComponent(); } #region Panel public void Setup() { _dataEntryGrid.HiddenColumns.Add(x => x.Document.ID); _dataEntryGrid.Refresh(true, false); _historyGrid.Refresh(true, false); } public void Refresh() { if (_pages.SelectedIndex == 0) _dataEntryGrid.Refresh(false, true); else if (_pages.SelectedIndex == 1) _historyGrid.Refresh(false,true); } public void Shutdown(CancelEventArgs? cancel) { ViewList.CloseImageWindows(); } #endregion #region Uploading private static byte[] RenderData(ref string filename, byte[] data) { var extension = Path.GetExtension(filename).ToLower(); if ((extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp") && ImageUtils.TryGetImageType(data, out var format)) { return data; } else if (extension == ".pdf") { return data; } else { using var stream = new MemoryStream(data); filename = Path.ChangeExtension(filename, "pdf"); return DataEntryReGroupWindow.RenderToPDF(filename, stream).SaveToBytes(); } throw new Exception("Could not render file to PDF"); } private void DynamicTabItem_Drop(object sender, DragEventArgs e) { Task.Run(() => { Dispatcher.Invoke(() => { Progress.Show("Uploading documents"); try { var result = DocumentUtils.HandleFileDrop(e); if (result is not null) { foreach (var (filename, stream) in result) { var newFilename = filename; byte[] data; if (stream is null) { data = File.ReadAllBytes(newFilename); } else { using var memStream = new MemoryStream(); stream.CopyTo(memStream); data = memStream.ToArray(); } data = RenderData(ref newFilename, data); _dataEntryGrid.UploadDocument(newFilename, data, Guid.Empty); } } Progress.Close(); } catch (Exception e) { Progress.Close(); MessageWindow.ShowError("Could not upload documents.", e); } }); }); } private void DynamicTabItem_DragOver(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent("FileGroupDescriptor")) { e.Effects = DragDropEffects.Copy; } else { e.Effects = DragDropEffects.None; } e.Handled = true; } #endregion private void _documents_OnSelectItem(object sender, DynamicGridSelectionEventArgs e) { ViewList.Documents = _dataEntryGrid.SelectedRows.ToArray(x => x.ToObject()); DoSelect(e.Rows); } private void DoSelect(CoreRow[]? rows) { var appliesTo = rows?.Length == 1 ? rows[0].Get(x => x.Tag.AppliesTo) : ""; var entityid = rows?.Length == 1 ? rows[0].Get(x => x.EntityID) : Guid.Empty; var archived = rows?.Length == 1 ? rows[0].Get(x => x.Archived) : DateTime.MinValue; SelectionChanged?.Invoke(appliesTo, entityid, archived.IsEmpty()); ViewList.CloseImageWindows(); } private void _historyGrid_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e) { DoSelect(e.Rows); } private List? _tags; private void _uploadMenu_OnOpened(object sender, RoutedEventArgs e) { _uploadMenu.Items.Clear(); _uploadMenu.AddItem("Load from File", null, _addItem_OnClick); if (Clipboard.ContainsText()) { _uploadMenu.AddItem("Paste Text from Clipboard", null, _pasteItem_OnClick); } else if (Clipboard.ContainsImage()) { _uploadMenu.AddItem("Paste Image from Clipboard", null, _pasteItem_OnClick); } else if (Clipboard.ContainsFileDropList()) { int count = CheckAllowableFiles(); if (count > 0) { _uploadMenu.AddItem($@"Paste {count} File{(count > 1 ? "s" : "")} from Clipboard", null, _pasteItem_OnClick); } } _uploadMenu.AddSeparatorIfNeeded(); if(_dataEntryGrid.SelectedRows.Length > 0) { if (Security.CanEdit()) { if (Security.IsAllowed()) { _tags ??= DataEntryGrid.GetVisibleTagList(); if(_tags.Count > 0) { var changeTag = _uploadMenu.AddItem("Set Tag", null, null); foreach(var tag in _tags) { changeTag.AddItem(tag.Name, null, tag, ChangeTag); } changeTag.AddSeparatorIfNeeded(); changeTag.AddItem("Clear Tags", null, null, ChangeTag); } } _uploadMenu.AddItem("Set Note", null, _dataEntryGrid.SelectedRows, _changeNote_Click); _uploadMenu.AddSeparator(); _uploadMenu.AddItem("Archive", null, _remove_OnClick); _uploadMenu.AddItem("Edit", null, _dataEntryGrid.SelectedRows, EditItem_Click); } if (Security.CanDelete()) { _uploadMenu.AddItem("Delete", null, _dataEntryGrid.SelectedRows, DeleteItem_Click); } } _uploadMenu.RemoveUnnecessarySeparators(); } private void DeleteItem_Click(CoreRow[] obj) { _dataEntryGrid.DeleteItems(obj); _dataEntryGrid.Refresh(false, true); } private void EditItem_Click(CoreRow[] rows) { var items = _dataEntryGrid.LoadItems(rows); if (_dataEntryGrid.EditItems(items)) { _dataEntryGrid.Refresh(false, true); } } private void ChangeTag(DataEntryTag? obj) { _dataEntryGrid.DoChangeTags(obj?.ID ?? Guid.Empty); } private void _addItem_OnClick() { var ofd = new OpenFileDialog() { Filter = @"All Files (*.pdf, *.bmp, *.png, *.jpg, *.jpeg)|*.pdf;*.bmp;*.png;*.jpg;*.jpeg", Multiselect = true, Title = @"Select Files to Upload", InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) }; if (ofd.ShowDialog() == true) { foreach (var file in ofd.FileNames) Upload( Path.GetFileName(file), new FileStream(file,FileMode.Open)); } } private void _pasteItem_OnClick() { if (Clipboard.ContainsText()) { Upload( $"Pasted Text {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.txt", new MemoryStream(new UTF8Encoding().GetBytes(Clipboard.GetText())) ); } else if (Clipboard.ContainsImage()) { var img = Clipboard.GetImage(); if (img != null) { var bmp = ImageUtils.BitmapSourceToBitmap(img); using (var ms = new MemoryStream()) { bmp.Save(ms, ImageFormat.Png); Upload( $"Pasted Image {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.png", ms ); } } } else if (CheckAllowableFiles() > 0) { var files = Clipboard.GetFileDropList().OfType().ToArray(); foreach (var file in files) { Upload( Path.GetFileName(file), new FileStream(file,FileMode.Open) ); } } } private void Upload(string filename, Stream data) { var doc = DataEntryReGroupWindow.RenderToPDF(filename, data); _dataEntryGrid.UploadDocument(Path.ChangeExtension(filename,"pdf"), doc.SaveToBytes(), Guid.Empty); } private static int CheckAllowableFiles() { var extensions = Clipboard.GetFileDropList().OfType().Select(x => Path.GetExtension(x.ToUpper())).ToArray(); return extensions.Count(x => String.Equals(x, "PDF") || String.Equals(x, "PNG") || String.Equals(x, "JPG") || String.Equals(x, "JPEG") || String.Equals(x, "BMP") || String.Equals(x, "TXT") ); } private void _pages_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if (_pages.SelectedIndex == 0) _dataEntryGrid.Refresh(false,true); else if (_pages.SelectedIndex == 1) _historyGrid.Refresh(false,true); } private void _remove_OnClick() { _dataEntryGrid.DoRemove(); } private void _reopen_OnClick(object sender, RoutedEventArgs e) { _historyGrid.DoReopen(); } private void _changeNote_Click(CoreRow[] rows) { var notes = rows.ToObjects().Select(x => x.Note).Distinct().ToArray(); var note = notes.Length == 1 ? notes[0] : ""; if(TextBoxDialog.Execute("Enter note:", ref note)) { _dataEntryGrid.DoChangeNote(note); } } private void _dataEntryGrid_OnContextMenuOpening(object sender, ContextMenuEventArgs e) { } private void ViewList_Explode() { _dataEntryGrid.DoExplode(); } private void ViewList_ExplodeAll() { _dataEntryGrid.DoExplodeAll(); } private void ViewList_UpdateDocument(DataEntryDocument document, Document doc) { if (Path.GetExtension(doc.FileName) == ".pdf") { document.Thumbnail = ImageUtils.GetPDFThumbnail(doc.Data, 256, 256); } Client.Save(document, ""); DataEntryCache.Cache.Add(new DocumentCachedDocument(doc)); ViewList.UpdateViewList(_dataEntryGrid.SelectedRows.ToArray(x => x.ToObject()), true); } }