Exemple #1
0
        private static void DoPostUpgrade()
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            // Make sure the data directories exist...
            Directory.CreateDirectory(ConfigurationManager.Instance.BaseDirectoryForUser);
        }
Exemple #2
0
        public static MemoryStream RenderPDFPage(string pdf_filename, int page_number, int dpi, int height, int width, string password, ProcessPriorityClass priority_class)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            render_count++;

            string process_parameters = String.Format(
                $"draw -q -w {width} -h {height} -r {dpi} -o -"
                + " " + (String.IsNullOrEmpty(password) ? "" : "-p " + password)
                + " " + '"' + pdf_filename + '"'
                + " " + page_number
                );

            string exe = Path.GetFullPath(Path.Combine(UnitTestDetector.StartupDirectoryForQiqqa, @"MuPDF/mutool.exe"));

            if (!File.Exists(exe))
            {
                throw new Exception($"PDF Page Rendering: missing modern MuPDF 'mudraw.exe': it does not exist in the expected path: '{exe}'");
            }
            if (!File.Exists(pdf_filename))
            {
                throw new Exception($"PDF Page Rendering: INTERNAL ERROR: missing PDF: it does not exist in the expected path: '{pdf_filename}'");
            }

            ExecResultAggregate rv = ReadEntireStandardOutput(exe, process_parameters, binary_output: true, priority_class);

            if (rv.error != null)
            {
                rv.stdoutStream?.Close();
                throw rv.error;
            }
            return(rv.stdoutStream);
        }
Exemple #3
0
        internal static void BuildReport(WebLibraryDetail web_library_detail, List <PDFDocument> pdf_documents)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            FeatureTrackingManager.Instance.UseFeature(Features.Library_JSONAnnotationReport);

            AnnotationReportOptions annotation_report_options = new AnnotationReportOptions();

            List <AnnotationWorkGenerator.AnnotationWork> annotation_works = AnnotationWorkGenerator.GenerateAnnotationWorks(web_library_detail, pdf_documents, annotation_report_options);

            IEnumerable <AnnotationJSON> annotation_jsons = annotation_works.Select(annotation_work =>
                                                                                    new AnnotationJSON
            {
                fingerprint = annotation_work.pdf_document.Fingerprint,
                title       = annotation_work.pdf_document.TitleCombined,
                page        = annotation_work.pdf_annotation.Page,
                left        = annotation_work.pdf_annotation.Left,
                top         = annotation_work.pdf_annotation.Top,
                width       = annotation_work.pdf_annotation.Width,
                height      = annotation_work.pdf_annotation.Height,
                tags        = annotation_work.pdf_annotation.Tags,
                text        = annotation_work.pdf_annotation.Text,
            }
                                                                                    );

            string json     = JsonConvert.SerializeObject(annotation_jsons, Formatting.Indented);
            string filename = Path.GetTempFileName() + ".json.txt";

            File.WriteAllText(filename, json);
            Process.Start(filename);
        }
Exemple #4
0
        private static void ExpandAuthors(PDFDocument doc, NodeControl node_control)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();
            ASSERT.Test(doc != null);

            FeatureTrackingManager.Instance.UseFeature(Features.Brainstorm_ExploreLibrary_Document_Authors);

            if (doc != null)
            {
                string authors = doc.AuthorsCombined;
                if (String.IsNullOrEmpty(authors) || Constants.UNKNOWN_AUTHORS == authors)
                {
                    return;
                }

                WPFDoEvents.InvokeInUIThread(() =>
                {
                    WPFDoEvents.AssertThisCodeIsRunningInTheUIThread();

                    List <NameTools.Name> names = new List <NameTools.Name>();
                    string[] authors_split      = NameTools.SplitAuthors_LEGACY(authors);
                    foreach (string author_split in authors_split)
                    {
                        string first_names, last_name;
                        NameTools.SplitName_LEGACY(author_split, out first_names, out last_name);
                        string initial = String.IsNullOrEmpty(first_names) ? null : first_names.Substring(0, 1);
                        PDFAuthorNodeContent pdf_author = new PDFAuthorNodeContent(doc.LibraryRef.Id, last_name, initial);
                        NodeControlAddingByKeyboard.AddChildToNodeControl(node_control, pdf_author, false);
                    }
                });
            }
        }
        private static LibrarySyncDetail.LocalLibrarySyncDetail GetLocalLibrarySyncDetail(Library library)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            LibrarySyncDetail.LocalLibrarySyncDetail local_library_sync_detail = new LibrarySyncDetail.LocalLibrarySyncDetail();

            List <PDFDocument> pdf_documents = library.PDFDocuments_IncludingDeleted;

            foreach (PDFDocument pdf_document in pdf_documents)
            {
                try
                {
                    ++local_library_sync_detail.total_files_in_library;

                    // Don't tally the deleted documents
                    bool deleted = pdf_document.Deleted;
                    if (deleted)
                    {
                        ++local_library_sync_detail.total_files_in_library_deleted;
                        continue;
                    }

                    // We can only really tally up the documents that exist locally
                    local_library_sync_detail.total_library_size += pdf_document.DocumentSizeInBytes;
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "There was an error tallying up the local library sync detail for '{0}'.", pdf_document.Fingerprint);
                }
            }

            return(local_library_sync_detail);
        }
        private static List <Word> GetSnappedWords(DocPageInfo page_info, Point mouse_up_point, Point mouse_down_point)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            double left   = Math.Min(mouse_up_point.X, mouse_down_point.X) / page_info.ActualWidth;
            double top    = Math.Min(mouse_up_point.Y, mouse_down_point.Y) / page_info.ActualHeight;
            double width  = Math.Abs(mouse_up_point.X - mouse_down_point.X) / page_info.ActualWidth;
            double height = Math.Abs(mouse_up_point.Y - mouse_down_point.Y) / page_info.ActualHeight;

            List <Word> words_in_selection = new List <Word>();

            WordList word_list = page_info.pdf_document.GetOCRText(page_info.page);

            if (null != word_list)
            {
                foreach (var word in word_list)
                {
                    if (word.IsContained(left, top, width, height))
                    {
                        words_in_selection.Add(word);
                    }
                }
            }

            return(words_in_selection);
        }
        private void SaveKnownWebLibraries(string filename = null)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            if (null == filename)
            {
                filename = KNOWN_WEB_LIBRARIES_FILENAME;
            }

            Logging.Info("+Saving known Web Libraries to {0}", filename);

            try
            {
                // do NOT save to disk when ANY of the DEV/TEST settings tweak the default Qiqqa behaviour:
                ConfigurationManager.ThrowWhenActionIsNotEnabled(nameof(SaveKnownWebLibraries));
                ConfigurationManager.ThrowWhenActionIsNotEnabled(nameof(LoadKnownWebLibraries));
                ConfigurationManager.ThrowWhenActionIsNotEnabled(nameof(AddLegacyWebLibrariesThatCanBeFoundOnDisk));

                KnownWebLibrariesFile known_web_libraries_file = new KnownWebLibrariesFile();
                known_web_libraries_file.web_library_details = new List <WebLibraryDetail>();
                foreach (WebLibraryDetail web_library_detail in web_library_details.Values)
                {
                    known_web_libraries_file.web_library_details.Add(web_library_detail);
                }
                SerializeFile.ProtoSave <KnownWebLibrariesFile>(filename, known_web_libraries_file);
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "There was a problem saving the known web libraries to file {0}", filename);
            }

            Logging.Info("-Saving known Web Libraries to {0}", filename);
        }
Exemple #8
0
        public static void RenderHighlights(Image image, PDFDocument pdf_document, int page)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            using (Bitmap scratch = RenderHighlights(image.Width, image.Height, pdf_document, page))
            {
                // Then render scratch onto target in transparent
                var color_matrix = new ColorMatrix();
                color_matrix.Matrix33 = (float)ConfigurationManager.Instance.ConfigurationRecord.GUI_AnnotationPrintTransparency;
                using (var image_attributes = new ImageAttributes())
                {
                    image_attributes.SetColorMatrix(color_matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                    using (Graphics graphics = Graphics.FromImage(image))
                    {
                        graphics.SmoothingMode = SmoothingMode.AntiAlias;
                        graphics.DrawImage(
                            scratch,
                            new Rectangle(0, 0, scratch.Width, scratch.Height),
                            0,
                            0,
                            scratch.Width,
                            scratch.Height,
                            GraphicsUnit.Pixel,
                            image_attributes
                            );
                    }
                }
            }
        }
Exemple #9
0
        public static MultiMapSet <string, string> GenerateAxisMap(string axis_name, WebLibraryDetail web_library_detail, HashSet <string> parent_fingerprints)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            switch (axis_name)
            {
            case "Tag": return(TagExplorerControl.GetNodeItems(web_library_detail, parent_fingerprints));

            case "Ratings": return(RatingExplorerControl.GetNodeItems(web_library_detail, parent_fingerprints));

            case "ReadingStage": return(ReadingStageExplorerControl.GetNodeItems(web_library_detail, parent_fingerprints));

            case "Author": return(AuthorExplorerControl.GetNodeItems(web_library_detail, parent_fingerprints));

            case "Year": return(YearExplorerControl.GetNodeItems(web_library_detail, parent_fingerprints));

            case "AutoTag": return(AITagExplorerControl.GetNodeItems(web_library_detail, parent_fingerprints));

            case "Publication": return(PublicationExplorerControl.GetNodeItems(web_library_detail, parent_fingerprints));

            case "Theme": return(ThemeExplorerControl.GetNodeItems(web_library_detail, parent_fingerprints));

            case "Type": return(TypeExplorerControl.GetNodeItems(web_library_detail, parent_fingerprints));

            default:
                Logging.Warn("Unknown pivot axis {0}", axis_name);
                return(GenerateMap_None(web_library_detail, parent_fingerprints));
            }
        }
Exemple #10
0
        private WebLibraryManager()
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            // Look for any web libraries that we know about
            LoadKnownWebLibraries(KNOWN_WEB_LIBRARIES_FILENAME, only_load_those_libraries_which_are_actually_present: false);

            // *************************************************************************************************************
            // *** MIGRATION TO OPEN SOURCE CODE ***************************************************************************
            // *************************************************************************************************************
            AddLegacyWebLibrariesThatCanBeFoundOnDisk();
            // *************************************************************************************************************

            AddLocalGuestLibraryIfMissing();

            InitAllLoadedLibraries();

            ImportManualsIntoLocalGuestLibraryIfMissing();

            SaveKnownWebLibraries();

            StatusManager.Instance.ClearStatus("LibraryInitialLoad");

            FireWebLibrariesChanged();
        }
Exemple #11
0
        // *************************************************************************************************************

        private void AddLocalGuestLibraryIfMissing()
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            // Check if we have an existing Guest library
            foreach (var pair in web_library_details)
            {
                if (pair.Value.IsLocalGuestLibrary)
                {
                    guest_web_library_detail = pair.Value;
                    break;
                }
            }

            // If we did not have a guest library, create one...
            if (null == guest_web_library_detail)
            {
                WebLibraryDetail new_web_library_detail = new WebLibraryDetail();
                new_web_library_detail.Id                  = "Guest";
                new_web_library_detail.Title               = "Local Guest Library";
                new_web_library_detail.Description         = "This is the library that comes with your Qiqqa guest account.";
                new_web_library_detail.Deleted             = false;
                new_web_library_detail.IsReadOnly          = false;
                new_web_library_detail.IsLocalGuestLibrary = true;

                UpdateKnownWebLibrary(new_web_library_detail);

                // Store this reference to guest
                guest_web_library_detail = new_web_library_detail;
            }
        }
Exemple #12
0
        internal static void AddDocumentsSimilarToDistribution(NodeControl node_control_, WebLibraryDetail web_library_detail, ExpeditionDataSource eds, float[] tags_distribution)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();
            ASSERT.Test(eds != null);

            // Get the most similar PDFDocuments
            int[] doc_ids = LDAAnalysisTools.GetDocumentsSimilarToDistribution(eds.LDAAnalysis, tags_distribution);

            WPFDoEvents.InvokeInUIThread(() =>
            {
                WPFDoEvents.AssertThisCodeIsRunningInTheUIThread();

                for (int i = 0; i < 10 && i < doc_ids.Length; ++i)
                {
                    int doc_id         = doc_ids[i];
                    string fingerprint = eds.docs[doc_id];

                    PDFDocument pdf_document = web_library_detail.Xlibrary.GetDocumentByFingerprint(fingerprint);
                    if (null == pdf_document)
                    {
                        Logging.Warn("Couldn't find similar document with fingerprint {0}", fingerprint);
                    }
                    else
                    {
                        PDFDocumentNodeContent content = new PDFDocumentNodeContent(pdf_document.Fingerprint, pdf_document.LibraryRef.Id);
                        NodeControlAddingByKeyboard.AddChildToNodeControl(node_control_, content, false);
                    }
                }
            });
        }
        private static List <Citation> ReadFromDisk(PDFDocument pdf_document)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            List <Citation> citations = new List <Citation>();

            List <LibraryDB.LibraryItem> library_items = pdf_document.Library.LibraryDB.GetLibraryItems(pdf_document.Fingerprint, PDFDocumentFileLocations.CITATIONS);

            if (0 < library_items.Count)
            {
                LibraryDB.LibraryItem library_item = library_items[0];

                string      lines_all = Encoding.UTF8.GetString(library_item.data);
                StringArray lines     = StringTools.splitAtNewline(lines_all);
                foreach (string line in lines)
                {
                    string[] chunks = line.Split(',');

                    Citation citation = new Citation();
                    citation.fingerprint_outbound = chunks[0];
                    citation.fingerprint_inbound  = chunks[1];
                    citation.type = (Citation.Type)Convert.ToInt32(chunks[2]);

                    citations.Add(citation);
                }
            }

            return(citations);
        }
        internal static void ReadFromDisk(PDFDocument pdf_document, PDFInkList inks)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            try
            {
                byte[] inks_data = null;
                List <LibraryDB.LibraryItem> library_items = pdf_document.LibraryRef.Xlibrary.LibraryDB.GetLibraryItems(PDFDocumentFileLocations.INKS, new List <string>()
                {
                    pdf_document.Fingerprint
                });
                ASSERT.Test(library_items.Count < 2);
                if (0 < library_items.Count)
                {
                    inks_data = library_items[0].data;
                }

                if (null != inks_data)
                {
                    Dictionary <int, byte[]> page_ink_blobs = SerializeFile.ProtoLoadFromByteArray <Dictionary <int, byte[]> >(inks_data);

                    if (null != page_ink_blobs)
                    {
                        foreach (var pair in page_ink_blobs)
                        {
                            pdf_document.AddPageInkBlob(pair.Key, pair.Value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "There was a problem loading the Inks for document {0}", pdf_document.Fingerprint);
            }
        }
        internal static void Install(BundleLibraryManifest manifest, string library_bundle_filename)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            WebLibraryDetail web_library_detail = WebLibraryManager.Instance.GetLibrary(manifest.Id);

            if (null != web_library_detail)
            {
                MessageBoxes.Info("You already have a version of this Bundle Library.  Please ensure you close all windows that use this library after the latest has been downloaded.");
            }

            string library_directory = WebLibraryDetail.GetLibraryBasePathForId(manifest.Id);

            Directory.CreateDirectory(library_directory);

            // Unzip the bundle
            string parameters = String.Format("-y x \"{0}\" -o\"{1}\"", library_bundle_filename, library_directory);

            using (Process process = ProcessSpawning.SpawnChildProcess(ConfigurationManager.Instance.Program7ZIP, parameters))
            {
                using (ProcessOutputReader process_output_reader = new ProcessOutputReader(process))
                {
                    process.WaitForExit();

                    Logging.Info("7ZIP Log Bundle Install progress:\n{0}", process_output_reader.GetOutputsDumpStrings());
                }
            }

            // Reflect this new bundle
            WebLibraryDetail new_web_library_detail = WebLibraryManager.Instance.UpdateKnownWebLibraryFromBundleLibraryManifest(manifest, suppress_flush_to_disk: false);

            WPFDoEvents.InvokeInUIThread(() => {
                MainWindowServiceDispatcher.Instance.OpenLibrary(new_web_library_detail);
            });
        }
Exemple #16
0
        private static void ExpandCitationsInbound(PDFDocument doc, NodeControl node_control)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();
            ASSERT.Test(doc != null);

            FeatureTrackingManager.Instance.UseFeature(Features.Brainstorm_ExploreLibrary_Document_CitationsInbound);

            if (doc != null)
            {
                List <Citation> citations = doc.PDFDocumentCitationManager.GetInboundCitations();

                WPFDoEvents.InvokeInUIThread(() =>
                {
                    WPFDoEvents.AssertThisCodeIsRunningInTheUIThread();

                    foreach (var citation in citations)
                    {
                        PDFDocumentNodeContent content = new PDFDocumentNodeContent(citation.fingerprint_outbound, doc.LibraryRef.Id);
                        if (!content.PDFDocument.Deleted)
                        {
                            NodeControlAddingByKeyboard.AddChildToNodeControl(node_control, content, false);
                        }
                    }
                });
            }
        }
        private static void DoPostUpgrade()
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            // NB NB NB NB: You CANT USE ANYTHING IN THE USER CONFIG AT THIS POINT - it is not yet decided until LOGIN has completed...

            WPFDoEvents.InvokeInUIThread(() =>
            {
                StatusManager.Instance.UpdateStatus("AppStart", "Loading themes");
                Theme.Initialize();
                DualTabbedLayout.GetWindowOverride = delegate() { return(new StandardWindow()); };

                // Force tooltips to stay open
                ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(DependencyObject), new FrameworkPropertyMetadata(3600000));
            });

            // Make sure the data directories exist...
            if (!Directory.Exists(ConfigurationManager.Instance.BaseDirectoryForUser))
            {
                Directory.CreateDirectory(ConfigurationManager.Instance.BaseDirectoryForUser);
            }

            // and kick off the Login Dialog to start the application proper:
            WPFDoEvents.InvokeAsyncInUIThread(() => ShowLoginDialog());

            // NB NB NB NB: You CANT USE ANYTHING IN THE USER CONFIG AT THIS POINT - it is not yet decided until LOGIN has completed...
        }
Exemple #18
0
        private static void ExpandAnnotations(PDFDocument doc, NodeControl node_control)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();
            ASSERT.Test(doc != null);

            FeatureTrackingManager.Instance.UseFeature(Features.Brainstorm_ExploreLibrary_Document_Annotations);

            if (doc != null)
            {
                var annotations = doc.GetAnnotations();

                WPFDoEvents.InvokeInUIThread(() =>
                {
                    WPFDoEvents.AssertThisCodeIsRunningInTheUIThread();

                    foreach (var annotation in annotations)
                    {
                        if (!annotation.Deleted)
                        {
                            PDFAnnotationNodeContent content = new PDFAnnotationNodeContent(doc.LibraryRef.Id, doc.Fingerprint, annotation.Guid.Value);
                            NodeControlAddingByKeyboard.AddChildToNodeControl(node_control, content, false);
                        }
                    }
                });
            }
        }
        // *************************************************************************************************************

        public void InitAllLoadedLibraries()
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            foreach (var pair in web_library_details)
            {
                WebLibraryDetail web_lib = pair.Value;
                Library          library = web_lib.Xlibrary;
                // only set up a Library instance when there isn't already one.
                // `library` may already have been set up in a previous call to this API
                // at application start; *this* call therefor MUST be due to the user
                // CREATING or JOINING another Intranet Library then!
                if (library == null)
                {
                    if (ShutdownableManager.Instance.IsShuttingDown)
                    {
                        Logging.Info("InitAllLoadedLibraries: Breaking out of library loading loop due to application termination");
                        break;
                    }

                    library = web_lib.Xlibrary = new Library(web_lib);
                }
                else
                {
                    Logging.Info($"InitAllLoadedLibraries: Initializing the local library for library Id: '{web_lib.Id}', Title: '{web_lib.Title}'");
                }
                library.BuildFromDocumentRepository(web_lib);
            }
        }
        public void RebuildExpedition(int num_topics, bool add_autotags, bool add_tags, RebuiltExpeditionCompleteDelegate rebuiltexpeditioncompletedelegate)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            StatusManager.Instance.UpdateStatus("Expedition", "Rebuilding Expedition");

            try
            {
                Library.IsBusyRegeneratingTags = true;

                ExpeditionDataSource eds = ExpeditionBuilder.BuildExpeditionDataSource(LibraryRef, num_topics, add_autotags, add_tags, ExpeditionBuilderProgressUpdate);
                if (eds != null)
                {
                    SerializeFile.SaveSafely(Filename_Store, eds);
                    expedition_data_source = eds;
                }
            }
            finally
            {
                Library.IsBusyRegeneratingTags = false;

                StatusManager.Instance.ClearCancelled("Expedition");
            }
            Logging.Info("-Rebuilding Expedition");

            if (null != rebuiltexpeditioncompletedelegate)
            {
                Logging.Info("+Notifying of rebuilt Expedition");
                rebuiltexpeditioncompletedelegate();
                Logging.Info("-Notifying of rebuilt Expedition");
            }
        }
Exemple #21
0
        private void ManageDownload(BundleLibraryManifest manifest)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            string url = manifest.BaseUrl + @"/" + manifest.Id + Common.EXT_BUNDLE;

            using (UrlDownloader.DownloadAsyncTracker download_async_tracker = UrlDownloader.DownloadWithNonBlocking(url))
            {
                string STATUS_TOKEN = "BundleDownload-" + manifest.Version;

                StatusManager.Instance.ClearCancelled(STATUS_TOKEN);
                while (!download_async_tracker.DownloadComplete)
                {
                    if (ShutdownableManager.Instance.IsShuttingDown)
                    {
                        Logging.Error("Canceling download of Bundle Library due to signaled application shutdown");
                        StatusManager.Instance.SetCancelled(STATUS_TOKEN);
                    }

                    if (StatusManager.Instance.IsCancelled(STATUS_TOKEN))
                    {
                        download_async_tracker.Cancel();
                        break;
                    }

                    StatusManager.Instance.UpdateStatus(STATUS_TOKEN, "Downloading Bundle Library...", download_async_tracker.ProgressPercentage, 100, true);

                    ShutdownableManager.Sleep(3000);
                }

                // Check the reason for exiting
                if (download_async_tracker.DownloadDataCompletedEventArgs.Cancelled)
                {
                    StatusManager.Instance.UpdateStatus(STATUS_TOKEN, "Cancelled download of Bundle Library.");
                }
                else if (null != download_async_tracker.DownloadDataCompletedEventArgs.Error)
                {
                    MessageBoxes.Error(download_async_tracker.DownloadDataCompletedEventArgs.Error, "There was an error during the download of your Bundle Library.  Please try again later or contact {0} for more information.", manifest.SupportEmail);
                    StatusManager.Instance.UpdateStatus(STATUS_TOKEN, "Error during download of Bundle Library.");
                }
                else if (null == download_async_tracker.DownloadDataCompletedEventArgs.Result)
                {
                    MessageBoxes.Error(download_async_tracker.DownloadDataCompletedEventArgs.Error, "There was an error during the download of your Bundle Library.  Please try again later or contact {0} for more information.", manifest.SupportEmail);
                    StatusManager.Instance.UpdateStatus(STATUS_TOKEN, "Error during download of Bundle Library.");
                }
                else
                {
                    StatusManager.Instance.UpdateStatus(STATUS_TOKEN, "Completed download of Bundle Library.");
                    if (MessageBoxes.AskQuestion("The Bundle Library named '{0}' has been downloaded.  Do you want to install it now?", manifest.Title))
                    {
                        LibraryBundleInstaller.Install(manifest, download_async_tracker.DownloadDataCompletedEventArgs.Result);
                    }
                    else
                    {
                        MessageBoxes.Warn("Not installing Bundle Library.");
                    }
                }
            }
        }
        public void SetPDFDocument(PDFDocument doc)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            pdf_document = doc;

            RepopulatePanels();
        }
        internal static void Check(WebLibraryDetail web_library_detail)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            // We can operate only on bundle libs
            if (!web_library_detail.IsBundleLibrary)
            {
                return;
            }

            // Only check every hour
            if (DateTime.UtcNow.Subtract(web_library_detail.LastBundleManifestDownloadTimestampUTC ?? DateTime.MinValue).TotalMinutes < 60)
            {
                return;
            }

            // Flag that we are running this update check now
            web_library_detail.LastBundleManifestDownloadTimestampUTC = DateTime.UtcNow;
            WebLibraryManager.Instance.NotifyOfChangeToWebLibraryDetail();

            // Download the new manifest
            BundleLibraryManifest manifest_existing = BundleLibraryManifest.FromJSON(web_library_detail.BundleManifestJSON);
            string manifest_latest_url = manifest_existing.BaseUrl + @"/" + manifest_existing.Id + Common.EXT_BUNDLE_MANIFEST;

            using (MemoryStream ms = UrlDownloader.DownloadWithBlocking(manifest_latest_url))
            {
                string manifest_latest_json           = Encoding.UTF8.GetString(ms.ToArray());
                BundleLibraryManifest manifest_latest = BundleLibraryManifest.FromJSON(manifest_latest_json);

                // It is an old version or we have this version
                if (0 <= String.Compare(manifest_existing.Version, manifest_latest.Version))
                {
                    return;
                }

                // It is a version the user has chosen to ignore
                if (web_library_detail.LastBundleManifestIgnoreVersion == manifest_latest.Version)
                {
                    return;
                }

                BundleLibraryUpdateNotification blun = new BundleLibraryUpdateNotification(web_library_detail, manifest_latest);

                NotificationManager.Instance.AddPendingNotification(
                    new NotificationManager.Notification(
                        String.Format("An update is available for your Bundle Library '{0}', from version {1} to {2}.", manifest_latest.Title, manifest_existing.Version, manifest_latest.Version),
                        "Bundle Library update available!",
                        NotificationManager.NotificationType.Info,
                        Icons.LibraryTypeBundle,
                        "Download!",
                        blun.Download,
                        "No thanks!",
                        blun.NoThanks
                        )
                    );
            }
        }
Exemple #24
0
        public static byte[] GetPageByHeightAsImage(string pdf_filename, string pdf_user_password, int page, int height, int width)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            // TODO: check if we have a higher size image cached already: use that one instead of bothering the PDF renderer again
            byte[] bitmap = SoraxPDFRendererDLLWrapper.GetPageByHeightAsImage(pdf_filename, pdf_user_password, page, height, width);

            return(bitmap);
        }
Exemple #25
0
        private void LoadKnownWebLibraries(string filename, bool only_load_those_libraries_which_are_actually_present)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            Logging.Info("+Loading known Web Libraries");
            try
            {
                if (File.Exists(filename))
                {
                    ConfigurationManager.ThrowWhenActionIsNotEnabled(nameof(LoadKnownWebLibraries));

                    KnownWebLibrariesFile known_web_libraries_file = SerializeFile.ProtoLoad <KnownWebLibrariesFile>(filename);
                    if (null != known_web_libraries_file.web_library_details)
                    {
                        foreach (WebLibraryDetail new_web_library_detail in known_web_libraries_file.web_library_details)
                        {
                            Logging.Info("We have known details for library '{0}' ({1})", new_web_library_detail.Title, new_web_library_detail.Id);

                            if (!new_web_library_detail.IsPurged)
                            {
                                // Intranet libraries had their readonly flag set on the user's current premium status...
                                if (new_web_library_detail.IsIntranetLibrary ||
                                    new_web_library_detail.IsLocalGuestLibrary ||
                                    new_web_library_detail.IsWebLibrary ||
                                    new_web_library_detail.IsBundleLibrary)
                                {
                                    new_web_library_detail.IsReadOnly = false;
                                }

                                string libdir_path  = Library.GetLibraryBasePathForId(new_web_library_detail.Id);
                                string libfile_path = LibraryDB.GetLibraryDBPath(libdir_path);

                                if (File.Exists(libfile_path) || !only_load_those_libraries_which_are_actually_present)
                                {
                                    UpdateKnownWebLibrary(new_web_library_detail);
                                }
                                else
                                {
                                    Logging.Info("Not loading library {0} with Id {1} as it does not exist on disk.", new_web_library_detail.Title, new_web_library_detail.Id);
                                }
                            }
                            else
                            {
                                Logging.Info("Not loading purged library {0} with id {1}", new_web_library_detail.Title, new_web_library_detail.Id);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "There was a problem loading the known Web Libraries from config file {0}", filename);
            }
            Logging.Info("-Loading known Web Libraries");
        }
Exemple #26
0
        public static Bitmap RenderHighlights(int width, int height, PDFDocument pdf_document, int page)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            // Render onto a scratch image in solid
            Bitmap bitmap = new Bitmap(width, height);     // <--- must b Dispose()d by caller

            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                double   last_right        = Double.NegativeInfinity;
                double   last_top          = Double.NegativeInfinity;
                double   last_bottom       = Double.NegativeInfinity;
                PointF[] adjoinment_points = new PointF[4];

                // TODO: next call can be very costly; MUST run in background!
                var highlights = pdf_document.Highlights.GetHighlightsForPage(page);

                foreach (PDFHighlight highlight in highlights)
                {
                    using (Brush highlight_pen = new SolidBrush(StandardHighlightColours.GetColor_Drawing(highlight.Color)))
                    {
                        graphics.FillRectangle(highlight_pen, (float)(highlight.Left * width), (float)(highlight.Top * height), (float)(highlight.Width * width), (float)(highlight.Height * height));

                        // Do some adjoining
                        if (Math.Abs(last_right - highlight.Left) < highlight.Height * 0.75 && Math.Abs(last_top - highlight.Top) < highlight.Height * 0.75 && Math.Abs(last_bottom - highlight.Bottom) < highlight.Height * 0.75)
                        {
                            // 0 -- 1
                            // |    |
                            // 3 -- 2

                            adjoinment_points[0].X = (float)(last_right * width);
                            adjoinment_points[0].Y = (float)(last_top * height);

                            adjoinment_points[1].X = (float)(highlight.Left * width);
                            adjoinment_points[1].Y = (float)(highlight.Top * height);

                            adjoinment_points[2].X = (float)(highlight.Left * width);
                            adjoinment_points[2].Y = (float)(highlight.Bottom * height);

                            adjoinment_points[3].X = (float)(last_right * width);
                            adjoinment_points[3].Y = (float)(last_bottom * height);

                            graphics.FillPolygon(highlight_pen, adjoinment_points);
                        }

                        // Remember the last position for future potential adjoining
                        last_right  = highlight.Right;
                        last_top    = highlight.Top;
                        last_bottom = highlight.Bottom;
                    }
                }
            }

            return(bitmap);
        }
        public static void RestoreDesktop()
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            try
            {
                // Get the remembrances
                if (File.Exists(Filename))
                {
                    string[] restore_settings = File.ReadAllLines(Filename);
                    foreach (string restore_setting in restore_settings)
                    {
                        try
                        {
                            if (restore_setting.StartsWith("PDF_LIBRARY"))
                            {
                                string[] parts      = restore_setting.Split(',');
                                string   library_id = parts[1];

                                Library library = WebLibraryManager.Instance.GetLibrary(library_id);
                                WPFDoEvents.InvokeInUIThread(() => MainWindowServiceDispatcher.Instance.OpenLibrary(library));
                            }
                            else if (restore_setting.StartsWith("PDF_DOCUMENT"))
                            {
                                string[] parts                = restore_setting.Split(',');
                                string   library_id           = parts[1];
                                string   document_fingerprint = parts[2];

                                Library     library      = WebLibraryManager.Instance.GetLibrary(library_id);
                                PDFDocument pdf_document = library.GetDocumentByFingerprint(document_fingerprint);
                                if (null == pdf_document)
                                {
                                    Logging.Warn("RestoreDesktop: Cannot find document anymore for fingerprint {0}", document_fingerprint);
                                }
                                else
                                {
                                    WPFDoEvents.InvokeInUIThread(() => MainWindowServiceDispatcher.Instance.OpenDocument(pdf_document));
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.Warn(ex, "There was a problem restoring desktop with state {0}", restore_setting);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "There was a problem restoring the saved desktop state.");
            }

            Logging.Warn("Finished restoring desktop.");
        }
        private TopicProbability[][] CalculateDensityOfTopicsInDocsSorted(int max_topics_to_retain)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            try
            {
                TopicProbability[][] local_density_of_topics_in_docs_sorted = new TopicProbability[lda.NUM_DOCS][];

                // How many topics will we remember for each doc?
                int topics_to_retain = max_topics_to_retain;
                if (topics_to_retain <= 0)
                {
                    topics_to_retain = lda.NUM_TOPICS;
                }
                else if (topics_to_retain > lda.NUM_TOPICS)
                {
                    topics_to_retain = lda.NUM_TOPICS;
                }

                // Calculate the density
                float[,] densityoftopicsindocuments = DensityOfTopicsInDocuments;
                Parallel.For(0, lda.NUM_DOCS, (doc) =>
                             //for (int doc = 0; doc < lda.NUM_DOCS; ++doc)
                {
                    TopicProbability[] density_of_topics_in_doc = new TopicProbability[lda.NUM_TOPICS];

                    for (int topic = 0; topic < lda.NUM_TOPICS; ++topic)
                    {
                        density_of_topics_in_doc[topic] = new TopicProbability(densityoftopicsindocuments[doc, topic], topic);
                    }
                    Array.Sort(density_of_topics_in_doc);

                    // Copy the correct number of items to retain
                    if (topics_to_retain == lda.NUM_TOPICS)
                    {
                        local_density_of_topics_in_docs_sorted[doc] = density_of_topics_in_doc;
                    }
                    else
                    {
                        local_density_of_topics_in_docs_sorted[doc] = new TopicProbability[topics_to_retain];
                        Array.Copy(density_of_topics_in_doc, local_density_of_topics_in_docs_sorted[doc], topics_to_retain);
                    }
                });

                return(local_density_of_topics_in_docs_sorted);
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "Internal LDAAnalysis error.");

                // terminate app
                throw;
            }
        }
Exemple #29
0
        // *************************************************************************************************************

        public void InitAllLoadedLibraries()
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            foreach (var pair in web_library_details)
            {
                var web_lib = pair.Value;
                var library = web_lib.library;
                library.BuildFromDocumentRepository();
            }
        }
        internal static void ReadFromStream(PDFDocument pdf_document, PDFHightlightList highlights, Dictionary <string, byte[]> /* can be null */ library_items_highlights_cache)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            byte[] highlights_data = null;

            if (null != library_items_highlights_cache)
            {
                library_items_highlights_cache.TryGetValue(pdf_document.Fingerprint, out highlights_data);
            }
            else
            {
                List <LibraryDB.LibraryItem> library_items = pdf_document.LibraryRef.Xlibrary.LibraryDB.GetLibraryItems(PDFDocumentFileLocations.HIGHLIGHTS, new List <string>()
                {
                    pdf_document.Fingerprint
                });
                ASSERT.Test(library_items.Count < 2);
                if (0 < library_items.Count)
                {
                    highlights_data = library_items[0].data;
                }
            }

            if (null != highlights_data)
            {
                try
                {
                    List <PDFHighlight> highlights_list = null;

                    // First try normal
                    try
                    {
                        highlights_list = ReadFromStream_JSON(highlights_data);
                    }
                    catch (Exception)
                    {
                        highlights_list = ReadFromStream_PROTOBUF(highlights_data);
                        FeatureTrackingManager.Instance.UseFeature(Features.Legacy_Highlights_ProtoBuf);
                    }

                    if (null != highlights_list)
                    {
                        foreach (PDFHighlight highlight in highlights_list)
                        {
                            pdf_document.AddUpdatedHighlight(highlight);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "There was a problem loading the Highlights for document {0}", pdf_document.Fingerprint);
                }
            }
        }