private void ButtonMoreMenus_Click(object sender, RoutedEventArgs e)
        {
            PDFDocument pdf_document = GetPDFDocument();

            ASSERT.Test(pdf_document != null);

            if (pdf_document != null)
            {
                LibraryCatalogPopup popup = new LibraryCatalogPopup(new List <PDFDocument> {
                    pdf_document
                });
                popup.Open();
            }

            e.Handled = true;
        }
예제 #2
0
        private void OnDrop_PDFDocumentList(object drop_object, Point mouse_current_virtual)
        {
            List <PDFDocument> pdf_documents = (List <PDFDocument>)drop_object;

            ASSERT.Test(pdf_documents != null);

            List <object> node_contents = new List <object>();

            foreach (PDFDocument pdf_document in pdf_documents)
            {
                PDFDocumentNodeContent document_node_content = new PDFDocumentNodeContent(pdf_document.Fingerprint, pdf_document.LibraryRef.Id);
                node_contents.Add(document_node_content);
            }

            DragDropManager?.SceneRenderingControl?.AddNewNodeControls(node_contents, mouse_current_virtual.X, mouse_current_virtual.Y);
        }
예제 #3
0
        public void Test_PDF_metadata_extraction_via_multipurp_chunk0030(string filepath)
        {
            string pdf_filename = MiscTestHelpers.GetNormalizedPathToAnyTestDataTestFile($"fixtures/PDF/{ filepath.Replace("./", "") }");

            ASSERT.FileExists(pdf_filename);
            PDFDocumentMuPDFMetaInfo info = MuPDFRenderer.GetDocumentMetaInfo(pdf_filename, null, ProcessPriorityClass.Normal);

            string json_text = ProduceJSONtext4Comparison(info);

            // Perform comparison via ApprovalTests->BeyondCompare (that's what I use for *decades* now)
            //ApprovalTests.Approvals.VerifyJson(json_out);   --> becomes the code below:
            ApprovalTests.Approvals.Verify(
                new QiqqaApprover(json_text, pdf_filename),
                ApprovalTests.Approvals.GetReporter()
                );
        }
예제 #4
0
        public string GetDescriptionForTopic(int topic, bool include_topic_number = true, string separator = "; ", bool stop_at_word_probability_jump = true)
        {
            StringBuilder sb = new StringBuilder();

            if (include_topic_number)
            {
                sb.Append(String.Format("{0}. ", topic + 1));
            }

            LDAAnalysis lda = LDAAnalysis;

            WordProbability[] lda_wordprobs = lda.DensityOfWordsInTopicsSorted[topic];
            ASSERT.Test(lda_wordprobs != null);

            double last_term_prob = 0;

            for (int t = 0; t < 5 && t < lda.NUM_WORDS; ++t)
            {
                WordProbability lda_node = lda_wordprobs[t];
                ASSERT.Test(lda_node != null);

                if (last_term_prob / lda_node.prob > 10)
                {
                    if (stop_at_word_probability_jump)
                    {
                        break;
                    }
                    else
                    {
                        sb.Append(" // ");
                    }
                }
                last_term_prob = lda_node.prob;

                sb.Append(String.Format("{0}", words[lda_node.word]));
                sb.Append(separator);
            }

            string description = sb.ToString();

            if (description.EndsWith(separator))
            {
                description = description.Substring(0, description.Length - separator.Length);
            }

            return(description);
        }
예제 #5
0
        // ----------------------------------------------------------------------------------------------------------------------------------

        public static WebLibraryDetail PickWebLibrary(string message = null)
        {
            List <WebLibraryDetail> wlds = WebLibraryManager.Instance.WebLibraryDetails_WorkingWebLibraries;

            ASSERT.Test(wlds.Count > 0);

            switch (wlds.Count)
            {
            case 1:
                // If we have only one library, use that...
                return(wlds[0]);

            default:
                // Otherwise fall back on the GUI
                return(PickWebLibrary_GUI(message));
            }
        }
        private void ButtonInCite_Snippet_Click(object sender, RoutedEventArgs e)
        {
            ButtonInCitePopup.Close();

            FeatureTrackingManager.Instance.UseFeature(Features.InCite_AddNewCitationSnippet_FromDocument);

            PDFDocument pdf_document = GetPDFDocument();

            ASSERT.Test(pdf_document != null);

            if (pdf_document != null)
            {
                PDFDocumentCitingTools.CiteSnippetPDFDocument(false, pdf_document);
            }

            e.Handled = true;
        }
예제 #7
0
        public void Test_Conversion_To_And_From_BibTeX_Text(string filepath)
        {
            string path = GetNormalizedPathToAnyTestDataTestFile(filepath);

            ASSERT.FileExists(path);

            string data_in = GetTestFileContent(path);
            string s1      = data_in;
            string s2      = BibTexCharacterMap.ASCIIToBibTex(s1);
            string s3      = BibTexCharacterMap.BibTexToASCII(s2);

            //ASSERT.AreEqual(s1, s3);
            ApprovalTests.Approvals.Verify(
                new QiqqaApprover(s3, filepath),
                ApprovalTests.Approvals.GetReporter()
                );
        }
예제 #8
0
        private static void ExpandThemes(PDFDocument doc, NodeControl node_control)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();
            ASSERT.Test(doc != null);

            FeatureTrackingManager.Instance.UseFeature(Features.Brainstorm_ExploreLibrary_Document_Themes);

            if (doc != null)
            {
                ASSERT.Test(doc.LibraryRef.Xlibrary != null);

                bool added_at_least_one_theme = false;

                ExpeditionDataSource eds = doc.LibraryRef.Xlibrary?.ExpeditionManager?.ExpeditionDataSource;
                if (null != eds)
                {
                    if (eds.docs_index.ContainsKey(doc.Fingerprint))
                    {
                        int doc_id = eds.docs_index[doc.Fingerprint];
                        TopicProbability[] topics = eds.LDAAnalysis.DensityOfTopicsInDocsSorted[doc_id];

                        WPFDoEvents.InvokeInUIThread(() =>
                        {
                            for (int t = 0; t < Math.Min(topics.Length, 5); ++t)
                            {
                                string topic_name    = eds.GetDescriptionForTopic(topics[t].topic, include_topic_number: false, "\n");
                                ThemeNodeContent tnc = new ThemeNodeContent(topic_name, doc.LibraryRef.Id);
                                NodeControlAddingByKeyboard.AddChildToNodeControl(node_control, tnc, false);

                                added_at_least_one_theme = true;
                            }
                        });
                    }
                    else
                    {
                        Logging.Warn("Expedition has not been run for library '{0}'.", doc.LibraryRef.Title);
                    }
                }

                if (!added_at_least_one_theme)
                {
                    MessageBoxes.Warn("There were no themes available for this document.  Please run Expedition against your library.");
                }
            }
        }
예제 #9
0
        internal static Attribute GetCustomAttribute(Type type)
        {
            if (!IsDefined(type))
            {
                return(null);
            }

            int        pack = 0, size = 0;
            LayoutKind layoutKind = LayoutKind.Auto;

            switch (type.Attributes & TypeAttributes.LayoutMask)
            {
            case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break;

            case TypeAttributes.AutoLayout: layoutKind = LayoutKind.Auto; break;

            case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break;

            default: ASSERT.UNREACHABLE(); break;
            }

            CharSet charSet = CharSet.None;

            switch (type.Attributes & TypeAttributes.StringFormatMask)
            {
            case TypeAttributes.AnsiClass: charSet = CharSet.Ansi; break;

            case TypeAttributes.AutoClass: charSet = CharSet.Auto; break;

            case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break;

            default: ASSERT.UNREACHABLE(); break;
            }
            type.Module.MetadataImport.GetClassLayout(type.MetadataToken, out pack, out size);

            // Metadata parameter checking should not have allowed 0 for packing size.
            // The runtime later converts a packing size of 0 to 8 so do the same here
            // because it's more useful from a user perspective.
            if (pack == 0)
            {
                pack = DEFAULT_PACKING_SIZE;
            }

            return(new StructLayoutAttribute(layoutKind, pack, size, charSet));
        }
예제 #10
0
        public static void SaveSafely(string filename, object animal_to_save)
        {
            if (!ShutdownableManager.Instance.IsShuttingDown)
            {
                ASSERT.Test(animal_to_save != null);
            }

            if (animal_to_save != null)
            {
                try
                {
                    SaveRedundant(filename, animal_to_save);
                }
                catch (Exception ex)
                {
                    Logging.Warn(ex, $"Error saving '{filename}'");
                }
            }
        }
예제 #11
0
        public static PDFDocument CreateFromVanillaReference(WebLibraryDetail web_library_detail)
        {
            PDFDocument pdf_document = new PDFDocument(web_library_detail);

            // Store the most important information
            //
            // thread-UNSAFE access is permitted as the PDF has just been created so there's no thread-safety risk yet.
            pdf_document.FileType            = Constants.VanillaReferenceFileType;
            pdf_document.Fingerprint         = VanillaReferenceCreating.CreateVanillaReferenceFingerprint();
            pdf_document.DateAddedToDatabase = DateTime.UtcNow;
            pdf_document.DateLastModified    = DateTime.UtcNow;

            Directory.CreateDirectory(pdf_document.DocumentBasePath);

            List <LibraryDB.LibraryItem> library_items = web_library_detail.Xlibrary.LibraryDB.GetLibraryItems(PDFDocumentFileLocations.METADATA, new List <string>()
            {
                pdf_document.Fingerprint
            });

            ASSERT.Test(library_items.Count < 2);
            if (0 == library_items.Count)
            {
                pdf_document.QueueToStorage();
            }
            else
            {
                LibraryDB.LibraryItem library_item = null;
                try
                {
                    library_item = library_items[0];
                    pdf_document = LoadFromMetaData(web_library_detail, pdf_document.Fingerprint, library_item.data);
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "There was a problem reloading an existing PDF from existing metadata, so overwriting it! (document fingerprint: {0}, data: {1})", pdf_document.Fingerprint, library_item?.MetadataAsString() ?? "???");

                    // TODO: WARNING: overwriting old (possibly corrupted) records like this can loose you old/corrupted/unsupported metadata content!
                    pdf_document.QueueToStorage();
                }
            }

            return(pdf_document);
        }
예제 #12
0
 public static void InvokeAsyncInUIThread(Action action, DispatcherPriority priority = DispatcherPriority.Normal)
 {
     if (Application.Current != null)
     {
         Application.Current.Dispatcher.BeginInvoke(action, priority);
     }
     else
     {
         ASSERT.Test(ShutdownableManager.Instance.IsShuttingDown);
         try
         {
             throw new Exception("Ignoring async UI invocation during shutdown.");
         }
         catch (Exception ex)
         {
             Logging.Warn(ex);
         }
     }
 }
예제 #13
0
        public void Test_Live_Scholar_Search()
        {
            //GoogleScholarScraper gs_scraper = new GoogleScholarScraper("latent dirichlet allocation", 100, true);
            string url = GenerateQueryUrl("dirichlet", 100);
            List <GoogleScholarScrapePaper> gssps = ScrapeUrl(url);

            ASSERT.IsGreaterOrEqual(gssps.Count, 1);

            foreach (var gs_paper in gssps)
            {
#if false
                bool have_a_match       = false;
                bool have_a_close_match = false;

                foreach (ACLPaperMetadata metadata in ACLPaperMetadatas.GetACLPaperMetadatas().Values)
                {
                    string acl_title  = metadata.title.ToLower();
                    string gs_title   = gs_paper.title.ToLower();
                    double max_length = Math.Max(acl_title.Length, gs_title.Length);
                    int    lewenstein = StringTools.LewensteinDistance(acl_title, gs_title);
                    if (lewenstein / max_length < 0.2)
                    {
                        have_a_close_match = true;
                    }

                    if (acl_title.Contains(gs_title) || gs_title.Contains(acl_title))
                    {
                        have_a_match = true;
                    }
                }

                Logging.Info((have_a_match ? "X" : ".") + (have_a_close_match ? "X" : "."));

                if (have_a_match != have_a_close_match)
                {
                    int aaaaaaaaa = 3;
                }
#endif

                Logging.Info(gs_paper.ToString());
            }
        }
        private void ButtonInCite_BibTeXKey_Click(object sender, RoutedEventArgs e)
        {
            ButtonInCitePopup.Close();

            PDFDocument pdf_document = GetPDFDocument();

            ASSERT.Test(pdf_document != null);

            if (pdf_document != null)
            {
                if (!String.IsNullOrEmpty(pdf_document.BibTexKey))
                {
                    string result = @"\cite{" + pdf_document.BibTexKey + @"}";
                    ClipboardTools.SetText(result);
                    StatusManager.Instance.UpdateStatus("CopyBibTeXKey", String.Format("Copied '{0}' to clipboard.", result));
                }
            }

            e.Handled = true;
        }
예제 #15
0
        internal static void ReadFromDisk(PDFDocument pdf_document)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            byte[] annotations_data = null;

            // Try to load the annotations from file if they exist
            var items = pdf_document.LibraryRef.Xlibrary.LibraryDB.GetLibraryItems(PDFDocumentFileLocations.ANNOTATIONS, new List <string>()
            {
                pdf_document.Fingerprint
            });

            ASSERT.Test(items.Count < 2);
            if (0 < items.Count)
            {
                annotations_data = items[0].data;
            }

            // If we actually have some annotations, load them
            if (null != annotations_data)
            {
                List <DictionaryBasedObject> annotation_dictionaries = null;
                try
                {
                    annotation_dictionaries = ReadFromStream_JSON(annotations_data);
                }
                catch (Exception)
                {
                    annotation_dictionaries = ReadFromStream_BINARY(annotations_data);
                }

                if (null != annotation_dictionaries)
                {
                    foreach (DictionaryBasedObject annotation_dictionary in annotation_dictionaries)
                    {
                        PDFAnnotation pdf_annotation = new PDFAnnotation(annotation_dictionary, false);
                        pdf_document.AddUpdatedAnnotation(pdf_annotation);
                    }
                }
            }
        }
예제 #16
0
        public void TestCallAsyncFireAndForget_ImmediateThrow()
        {
            try
            {
                // output "hello world" as method returns early
                ASSERT.AreEqual(ExampleFireAndForgetFunc(), "hello world");
            }
            catch
            {
                // Exception is NOT caught here
                ASSERT.Fail("exception should not be caught here");
            }
            //ASSERT.IsNull(caught_ex);

            Thread.Sleep(500);

            ASSERT.IsNotNull(caught_ex);
            ASSERT.IsTrue(faulted, "faulted");
            ASSERT.IsTrue(completed, "completed");
            ASSERT.IsFalse(canceled, "cancelled");
        }
        internal void ExecuteSearchQuick(string query)
        {
            ASSERT.Test(query != null);
            SearchQuick.Text = query;

            if (!String.IsNullOrEmpty(query))
            {
                FeatureTrackingManager.Instance.UseFeature(Features.Library_KeywordFilter);

                List <IndexResult> index_results = LibrarySearcher.FindAllFingerprintsMatchingQuery(library_filter_control.web_library_detail, query);

                library_filter_control.search_quick_query        = query;
                library_filter_control.search_quick_scores       = new Dictionary <string, double>();
                library_filter_control.search_quick_fingerprints = new HashSet <string>();
                foreach (var index_result in index_results)
                {
                    library_filter_control.search_quick_fingerprints.Add(index_result.fingerprint);
                    library_filter_control.search_quick_scores[index_result.fingerprint] = index_result.score;
                }
            }
            else
            {
                library_filter_control.search_quick_query        = null;
                library_filter_control.search_quick_fingerprints = null;
                library_filter_control.search_quick_scores       = null;
            }

            // Create the feedback
            library_filter_control.search_quick_fingerprints_span = new Span();
            Bold bold = new Bold();

            bold.Inlines.Add("Search");
            library_filter_control.search_quick_fingerprints_span.Inlines.Add(bold);
            library_filter_control.search_quick_fingerprints_span.Inlines.Add(" (click search score for details)");
            library_filter_control.search_quick_fingerprints_span.Inlines.Add(": ");
            library_filter_control.search_quick_fingerprints_span.Inlines.Add("'");
            library_filter_control.search_quick_fingerprints_span.Inlines.Add(query);
            library_filter_control.search_quick_fingerprints_span.Inlines.Add("'");
            library_filter_control.search_quick_fingerprints_span.Inlines.Add(LibraryFilterHelpers.GetClearImageInline("Clear this filter.", hyperlink_search_quick_fingerprints_span_OnClick));
        }
        private void MoveGuestPreviewPDFDocument(WebLibraryDetail web_library_detail)
        {
            PDFDocument pdf_document = GetPDFDocument();

            ASSERT.Test(pdf_document != null);

            if (pdf_document != null)
            {
                PDFDocument source_pdf_document = pdf_document;

                SafeThreadPool.QueueUserWorkItem(o =>
                {
                    PDFDocument cloned_pdf_document = ImportingIntoLibrary.ClonePDFDocumentsFromOtherLibrary_SYNCHRONOUS(source_pdf_document, web_library_detail);
                    ASSERT.Test(cloned_pdf_document != null);

                    WPFDoEvents.InvokeInUIThread(() =>
                    {
                        // Open the new
                        if (null != cloned_pdf_document)
                        {
                            MainWindowServiceDispatcher.Instance.OpenDocument(cloned_pdf_document);
                        }
                        else
                        {
                            MessageBoxes.Warn("There was a problem moving this document to another library.");
                        }

                        // Close the old
                        MainWindowServiceDispatcher.Instance.ClosePDFReadingControl(this);

                        // Delete the old
                        if (cloned_pdf_document != null && cloned_pdf_document != source_pdf_document)
                        {
                            source_pdf_document.Deleted = true;
                            source_pdf_document.Bindable.NotifyPropertyChanged(nameof(source_pdf_document.Deleted));
                        }
                    });
                });
            }
        }
        public void ReflectLibrary(WebLibraryDetail web_library_detail)
        {
            // Reset
            RegionNoLibrary.Visibility          = Visibility.Collapsed;
            RegionNoExpedition.Visibility       = Visibility.Collapsed;
            RegionStaleExpedition.Visibility    = Visibility.Collapsed;
            RegionExpeditionTooSmall.Visibility = Visibility.Collapsed;

            // Reflect
            if (null == web_library_detail)
            {
                RegionNoLibrary.Visibility = Visibility.Visible;
            }
            else
            {
                ExpeditionDataSource eds = web_library_detail.Xlibrary?.ExpeditionManager?.ExpeditionDataSource;

                if (null != eds)
                {
                    RegionNoExpedition.Visibility = Visibility.Visible;
                }
                else
                {
                    ASSERT.Test(eds.words != null);
                    ASSERT.Test(eds.docs != null);

                    // Is this expedition getting old?
                    if (web_library_detail.Xlibrary.ExpeditionManager.IsStale)
                    {
                        RegionStaleExpedition.Visibility = Visibility.Visible;
                    }

                    // Is this expedition too small?
                    if (eds.docs.Count < 20 || eds.words.Count < 5)
                    {
                        RegionExpeditionTooSmall.Visibility = Visibility.Visible;
                    }
                }
            }
        }
예제 #20
0
        public void Basic_Test(string sample_filepath)
        {
            string path = GetNormalizedPathToAnyTestDataTestFile(sample_filepath);

            ASSERT.FileExists(path);

            string sample_text = GetTestFileContent(path);

            // extract URL from sample file:
            string url     = null;
            string docHtml = null;

            Match match = Regex.Match(sample_text, @"<!--(.*?)-->(.*)", RegexOptions.Singleline); // counter-intuitive flag: https://stackoverflow.com/questions/159118/how-do-i-match-any-character-across-multiple-lines-in-a-regular-expression

            if (Match.Empty != match)
            {
                url     = match.Groups[1].Value.Trim();
                docHtml = match.Groups[2].Value;
            }

            List <GoogleScholarScrapePaper> gssps = new List <GoogleScholarScrapePaper>();

            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(docHtml);
            //doc.Load(ms, System.Text.Encoding.UTF8, detectEncodingFromByteOrderMarks: false);

            ScrapeDoc(doc, url, ref gssps);

            ASSERT.IsGreaterOrEqual(gssps.Count, 1);

            // Serialize the result to JSON for easier comparison via ApprovalTests->BeyondCompare (that's what I use for *decades* now)
            string json_out = JsonConvert.SerializeObject(gssps, Newtonsoft.Json.Formatting.Indented).Replace("\r\n", "\n");

            //ApprovalTests.Approvals.VerifyJson(json_out);   --> becomes the code below:
            ApprovalTests.Approvals.Verify(
                new QiqqaApprover(json_out, sample_filepath),
                ApprovalTests.Approvals.GetReporter()
                );
        }
        private void GetCombinedWordsList(List <string> words, List <int> page_word_offsets)
        {
            PDFDocument pdf_document = GetPDFDocument();

            ASSERT.Test(pdf_document != null);

            if (null != pdf_document)
            {
                for (int page = 1; page <= pdf_document.PageCount; ++page)
                {
                    WordList words_on_page = pdf_document.GetOCRText(page);
                    page_word_offsets.Add(words.Count);
                    if (null != words_on_page)
                    {
                        foreach (Word word in words_on_page)
                        {
                            words.Add(word.Text);
                        }
                    }
                }
            }
        }
예제 #22
0
        public void GetFirstWord_Test(string data_filepath)
        {
            string path = GetNormalizedPathToAnyTestDataTestFile(data_filepath);

            ASSERT.FileExists(path);

            string data_text = GetTestFileContent(path);

            Result rv = new Result();

            rv.input  = data_text;
            rv.result = StringTools.GetFirstWord(data_text);

            // Serialize the result to JSON for easier comparison via ApprovalTests->BeyondCompare (that's what I use for *decades* now)
            string json_out = JsonConvert.SerializeObject(rv, Newtonsoft.Json.Formatting.Indented).Replace("\r\n", "\n");

            //ApprovalTests.Approvals.VerifyJson(json_out);   --> becomes the code below:
            ApprovalTests.Approvals.Verify(
                new QiqqaApprover(json_out, data_filepath),
                ApprovalTests.Approvals.GetReporter()
                );
        }
예제 #23
0
        internal static Attribute GetCustomAttribute(int token, Module scope)
        {
            UnmanagedType unmanagedType, arraySubType;
            VarEnum       safeArraySubType;
            int           sizeParamIndex = 0, sizeConst = 0;
            string        marshalTypeName = null, marshalCookie = null, safeArrayUserDefinedTypeName = null;
            int           iidParamIndex = 0;

            ConstArray nativeType = scope.ModuleHandle.GetMetadataImport().GetFieldMarshal(token);

            if (nativeType.Length == 0)
            {
                return(null);
            }

            MetadataImport.GetMarshalAs(nativeType,
                                        out unmanagedType, out safeArraySubType, out safeArrayUserDefinedTypeName, out arraySubType, out sizeParamIndex,
                                        out sizeConst, out marshalTypeName, out marshalCookie, out iidParamIndex);

            Type safeArrayUserDefinedType = safeArrayUserDefinedTypeName == null || safeArrayUserDefinedTypeName.Length == 0 ? null :
                                            RuntimeTypeHandle.GetTypeByNameUsingCARules(safeArrayUserDefinedTypeName, scope);
            Type marshalTypeRef = null;

            try
            {
                marshalTypeRef = marshalTypeName == null ? null : RuntimeTypeHandle.GetTypeByNameUsingCARules(marshalTypeName, scope);
            }
            catch (System.TypeLoadException)
            {
                // The user may have supplied a bad type name string causing this TypeLoadException
                // Regardless, we return the bad type name
                ASSERT.CONSISTENCY_CHECK(marshalTypeName != null);
            }

            return(new MarshalAsAttribute(
                       unmanagedType, safeArraySubType, safeArrayUserDefinedType, arraySubType,
                       (short)sizeParamIndex, sizeConst, marshalTypeName, marshalTypeRef, marshalCookie, iidParamIndex));
        }
        private void SetSearchKeywords_EXECUTE(string search_string)
        {
            // Check if we are repeating the search or not...
            if (previous_search_string != search_string)
            {
                FeatureTrackingManager.Instance.UseFeature(Features.Document_Search);
                previous_search_string = search_string;

                PDFDocument pdf_document = GetPDFDocument();
                ASSERT.Test(pdf_document != null);

                if (pdf_document != null)
                {
                    previous_search_result_set = PDFSearcher.Search(pdf_document, search_string);
                }
            }
            else
            {
                FeatureTrackingManager.Instance.UseFeature(Features.Document_SearchAgain);
            }

            PDFSearchResultSet search_result_set = previous_search_result_set;

            // Set the PDF viewer search results
            pdf_renderer_control.SetSearchKeywords(search_result_set);

            // Set the bottom list box search results
            if (null != search_result_set && search_result_set.Count > 0)
            {
                GridBOTTOM.Visibility = Visibility.Visible;
            }
            else
            {
                GridBOTTOM.Visibility = Visibility.Collapsed;
            }

            ListSearchDetails.DataContext = search_result_set.AsList();
        }
예제 #25
0
        private static void ExpandRelevants(PDFDocument doc, NodeControl node_control)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();
            ASSERT.Test(doc != null);

            FeatureTrackingManager.Instance.UseFeature(Features.Brainstorm_ExploreLibrary_Document_Similars);

            if (doc != null)
            {
                List <ExpeditionPaperSuggestions.Result> results = ExpeditionPaperSuggestions.GetRelevantOthers(doc, 10);

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

                    foreach (ExpeditionPaperSuggestions.Result result in results)
                    {
                        PDFDocumentNodeContent content = new PDFDocumentNodeContent(result.pdf_document.Fingerprint, result.pdf_document.LibraryRef.Id);
                        NodeControlAddingByKeyboard.AddChildToNodeControl(node_control, content, false);
                    }
                });
            }
        }
예제 #26
0
        public void Basic_Import_Test(string pubmed_filepath)
        {
            // See http://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html for the low-down

            string path = GetNormalizedPathToPubMedXMLTestFile(pubmed_filepath);

            ASSERT.FileExists(path);

            string pubmed_xml = GetTestFileContent(path);

            Result rv = new Result();

            rv.success = PubMedXMLToBibTex.TryConvert(pubmed_xml, out rv.bibtex, out rv.messages);

            // Serialize the result to JSON for easier comparison via ApprovalTests->BeyondCompare (that's what I use for *decades* now)
            string json_out = JsonConvert.SerializeObject(rv, Newtonsoft.Json.Formatting.Indented).Replace("\r\n", "\n");

            //ApprovalTests.Approvals.VerifyJson(json_out);   --> becomes the code below:
            ApprovalTests.Approvals.Verify(
                new QiqqaApprover(json_out, pubmed_filepath),
                ApprovalTests.Approvals.GetReporter()
                );
        }
예제 #27
0
        private static void ExpandTags(PDFDocument doc, NodeControl node_control)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();
            ASSERT.Test(doc != null);

            FeatureTrackingManager.Instance.UseFeature(Features.Brainstorm_ExploreLibrary_Document_Tags);

            if (doc != null)
            {
                var tags = TagTools.ConvertTagBundleToTags(doc.Tags);

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

                    foreach (string tag in tags)
                    {
                        PDFTagNodeContent pdf_tag = new PDFTagNodeContent(doc.LibraryRef.Id, tag);
                        NodeControlAddingByKeyboard.AddChildToNodeControl(node_control, pdf_tag, false);
                    }
                });
            }
        }
예제 #28
0
        private static void ExpandAutoTags(PDFDocument doc, NodeControl node_control)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();
            ASSERT.Test(doc != null);

            FeatureTrackingManager.Instance.UseFeature(Features.Brainstorm_ExploreLibrary_Document_AutoTags);

            if (doc != null)
            {
                HashSet <string> tags = doc.LibraryRef.Xlibrary.AITagManager.AITags.GetTagsWithDocument(doc.Fingerprint);

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

                    foreach (string tag in tags)
                    {
                        PDFAutoTagNodeContent pdf_auto_tag = new PDFAutoTagNodeContent(doc.LibraryRef.Id, tag);
                        NodeControlAddingByKeyboard.AddChildToNodeControl(node_control, pdf_auto_tag, false);
                    }
                });
            }
        }
예제 #29
0
        public static void SaveDesktop()
        {
            List <string> restore_settings = new List <string>();

            // Get the remembrances
            List <FrameworkElement> framework_elements = MainWindowServiceDispatcher.Instance.MainWindow.DockingManager.GetAllFrameworkElements();

            foreach (FrameworkElement framework_element in framework_elements)
            {
                {
                    LibraryControl library_control = framework_element as LibraryControl;
                    if (null != library_control)
                    {
                        Logging.Info("Remembering a library control {0}", library_control.LibraryRef.Id);
                        restore_settings.Add(String.Format("PDF_LIBRARY,{0}", library_control.LibraryRef.Id));
                    }
                }

                {
                    PDFReadingControl pdf_reading_control = framework_element as PDFReadingControl;
                    if (null != pdf_reading_control)
                    {
                        PDFDocument pdf_document = pdf_reading_control.GetPDFDocument();
                        ASSERT.Test(pdf_document != null);

                        if (pdf_document != null)
                        {
                            Logging.Info("Remembering a PDF reader {0}", pdf_document.Fingerprint);
                            restore_settings.Add(String.Format("PDF_DOCUMENT,{0},{1}", pdf_document.LibraryRef.Id, pdf_document.Fingerprint));
                        }
                    }
                }
            }

            // Store the remembrances
            File.WriteAllLines(Filename, restore_settings);
        }
        protected virtual void Dispose(bool disposing)
        {
            Logging.Debug("PDFReadingControl::Dispose({0}) @{1}", disposing, dispose_count);

            WPFDoEvents.InvokeInUIThread(() =>
            {
                WPFDoEvents.SafeExec(() =>
                {
                    if (dispose_count == 0)
                    {
                        // GetPDFDocument() depends on a valid pdf_renderer_control reference, so we do this one first!
                        PDFDocument pdf_document = GetPDFDocument();
                        ASSERT.Test(pdf_document != null);

                        pdf_document?.FlushCachedPageRenderings();
                    }
                });

                WPFDoEvents.SafeExec(() =>
                {
                    if (dispose_count == 0)
                    {
                        // Get rid of managed resources
                        PDFRendererControlArea.Children.Clear();

                        pdf_renderer_control?.Dispose();
                    }
                });

                WPFDoEvents.SafeExec(() =>
                {
                    pdf_renderer_control = null;
                });

                ++dispose_count;
            });
        }