protected virtual void Dispose(bool disposing)
        {
            Logging.Debug("PDFInkLayer::Dispose({0}) @{1}", disposing, dispose_count);

            try
            {
                if (0 == dispose_count)
                {
                    WPFDoEvents.InvokeInUIThread(() =>
                    {
                        ObjInkCanvas.StrokeCollected  -= ObjInkCanvas_StrokeCollected;
                        ObjInkCanvas.StrokeErased     -= ObjInkCanvas_StrokeErased;
                        ObjInkCanvas.SelectionMoved   -= ObjInkCanvas_SelectionMoved;
                        ObjInkCanvas.SelectionResized -= ObjInkCanvas_SelectionResized;

                        ObjInkCanvas.RequestBringIntoView -= ObjInkCanvas_RequestBringIntoView;

                        try
                        {
                            foreach (var el in Children)
                            {
                                IDisposable node = el as IDisposable;
                                if (null != node)
                                {
                                    node.Dispose();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.Error(ex);
                        }

                        try
                        {
                            Children.Clear();
                        }
                        catch (Exception ex)
                        {
                            Logging.Error(ex);
                        }
                    }, Dispatcher);
                }

                // Clear the references for sanity's sake
                pdf_renderer_control_stats = null;

                DataContext = null;
            }
            catch (Exception ex)
            {
                Logging.Error(ex);
            }

            ++dispose_count;

            //base.Dispose(disposing);     // parent only throws an exception (intentionally), so depart from best practices and don't call base.Dispose(bool)
        }
Пример #2
0
        protected virtual void Dispose(bool disposing)
        {
            Logging.Debug("WebBrowserControl::Dispose({0}) @{1}", disposing, dispose_count);

            WPFDoEvents.SafeExec(() =>
            {
                // Prevent recursive run-away of the code via the chain:
                //
                // ***  Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserControl.Dispose(bool disposing)
                // **   Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserControl.Dispose()
                //      Utilities.dll!Utilities.GUI.DualTabbedLayoutStuff.DualTabbedLayout.WantsClose(Utilities.GUI.DualTabbedLayoutStuff.DualTabbedLayoutItem item)
                //      Utilities.dll!Utilities.GUI.DualTabbedLayoutStuff.DualTabbedLayout.CloseContent(System.Windows.FrameworkElement fe)
                //      Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserHostControl.DeleteSearchers()
                //      Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserHostControl.Dispose(bool disposing)
                //      Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserHostControl.Dispose()
                // ***  Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserControl.Dispose(bool disposing)
                // **   Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserControl.Dispose()
                //
                // and prevent partial/broken cleanup due to chains like this one, resulting in
                // a dispose_count == 2:
                //
                // =2 * Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserHostControl.Dispose(bool disposing)
                //      Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserHostControl.Dispose()
                // =2 * Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserControl.Dispose(bool disposing)
                //      Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserControl.Dispose()
                // =1   Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserHostControl.Dispose(bool disposing)
                //      Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserHostControl.Dispose()
                // =1   Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserControl.Dispose(bool disposing)
                //      Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserControl.Dispose()
                //      Utilities.dll!Utilities.GUI.DualTabbedLayoutStuff.DualTabbedLayout.WantsClose(Utilities.GUI.DualTabbedLayoutStuff.DualTabbedLayoutItem item)
                //      Utilities.dll!Utilities.GUI.DualTabbedLayoutStuff.DualTabbedLayout.CloseContent(System.Windows.FrameworkElement fe)
                // *    Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserHostControl.DeleteSearchers()
                //      Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserHostControl.RebuildSearchers(System.Collections.Generic.HashSet<string> once_off_requested_web_searchers)
                //      Qiqqa.exe!Qiqqa.WebBrowsing.WebBrowserHostControl.ForceSnifferSearchers()
                //
                if (dispose_count == 0)
                {
                    // Get rid of managed resources
                    ObjWebBrowser?.Dispose();
                    ObjWebBrowser = null;

                    // Multiple WebBrowserControl instances MAY SHARE a single WebBrowserHostControl.
                    // It is passed to this class/instance as a reference anyway, so we SHOULD NOT
                    // kill/dispose it in here!
                    //
                    //web_browser_host_control.Dispose();
                    web_browser_host_control = null;
                }
            });

            WPFDoEvents.SafeExec(() =>
            {
                ObjWebBrowser            = null;
                web_browser_host_control = null;
            });

            ++dispose_count;
        }
        protected virtual void Dispose(bool disposing)
        {
            Logging.Debug("PDFRendererControl::Dispose({0}) @{1}", disposing, dispose_count);

            WPFDoEvents.InvokeInUIThread(() =>
            {
                WPFDoEvents.SafeExec(() =>
                {
                    if (dispose_count == 0)
                    {
                        if (!ShutdownableManager.Instance.IsShuttingDown)
                        {
                            pdf_renderer_control_stats?.pdf_document.QueueToStorage();
                        }
                    }
                });

                WPFDoEvents.SafeExec(() =>
                {
                    if (dispose_count == 0)
                    {
                        // Get rid of managed resources
                        List <PDFRendererPageControl> children = new List <PDFRendererPageControl>();
                        foreach (PDFRendererPageControl child in ObjPagesPanel.Children.OfType <PDFRendererPageControl>())
                        {
                            children.Add(child);
                        }

                        ObjPagesPanel.Children.Clear();

                        foreach (PDFRendererPageControl child in children)
                        {
                            WPFDoEvents.SafeExec(() =>
                            {
                                child.Dispose();
                            });
                        }
                    }
                });

                WPFDoEvents.SafeExec(() =>
                {
                    if (dispose_count == 0)
                    {
                        pdf_renderer_control_stats?.pdf_document.FlushCachedPageRenderings();
                    }

                    Dispatcher.ShutdownStarted -= Dispatcher_ShutdownStarted;
                });

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

                ++dispose_count;
            });
        }
Пример #4
0
        protected virtual void Dispose(bool disposing)
        {
            Logging.Debug("PDFTextSentenceLayer::Dispose({0}) @{1}", disposing, dispose_count);

            try
            {
                if (null != drag_area_tracker)
                {
                    WPFDoEvents.InvokeInUIThread(() =>
                    {
                        try
                        {
                            foreach (var el in Children)
                            {
                                IDisposable node = el as IDisposable;
                                if (null != node)
                                {
                                    node.Dispose();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.Error(ex);
                        }

                        try
                        {
                            ClearChildren();
                            Children.Clear();
                        }
                        catch (Exception ex)
                        {
                            Logging.Error(ex);
                        }

                        drag_area_tracker.OnDragStarted    -= drag_area_tracker_OnDragStarted;
                        drag_area_tracker.OnDragInProgress -= drag_area_tracker_OnDragInProgress;
                        drag_area_tracker.OnDragComplete   -= drag_area_tracker_OnDragComplete;
                    }, Dispatcher);
                }

                // Clear the references for sanity's sake
                pdf_renderer_control_stats = null;
                drag_area_tracker          = null;
                text_selection_manager     = null;

                DataContext = null;
            }
            catch (Exception ex)
            {
                Logging.Error(ex);
            }

            ++dispose_count;

            //base.Dispose(disposing);     // parent only throws an exception (intentionally), so depart from best practices and don't call base.Dispose(bool)
        }
Пример #5
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);
        }
        protected virtual void Dispose(bool disposing)
        {
            Logging.Debug("PDFTextSentenceLayer::Dispose({0}) @{1}", disposing, dispose_count);

            WPFDoEvents.InvokeInUIThread(() =>
            {
                WPFDoEvents.SafeExec(() =>
                {
                    if (dispose_count == 0)
                    {
                        foreach (var el in Children)
                        {
                            IDisposable node = el as IDisposable;
                            if (null != node)
                            {
                                node.Dispose();
                            }
                        }
                    }
                });

                WPFDoEvents.SafeExec(() =>
                {
                    ClearChildren();
                    Children.Clear();
                });

                WPFDoEvents.SafeExec(() =>
                {
                    if (drag_area_tracker != null)
                    {
                        drag_area_tracker.OnDragStarted    -= drag_area_tracker_OnDragStarted;
                        drag_area_tracker.OnDragInProgress -= drag_area_tracker_OnDragInProgress;
                        drag_area_tracker.OnDragComplete   -= drag_area_tracker_OnDragComplete;
                    }

                    Dispatcher.ShutdownStarted -= Dispatcher_ShutdownStarted;
                });

                WPFDoEvents.SafeExec(() =>
                {
                    // Clear the references for sanity's sake
                    pdf_renderer_control   = null;
                    drag_area_tracker      = null;
                    text_selection_manager = null;
                });

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

                ++dispose_count;

                //base.Dispose(disposing);     // parent only throws an exception (intentionally), so depart from best practices and don't call base.Dispose(bool)
            });
        }
        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
                        )
                    );
            }
        }
Пример #8
0
        private void MainWindow_ContentRendered(object sender, EventArgs e)
        {
            Logging.Debug特("MainWindow::ContentRendered event");

            // hold off: level 2 -> 1
            MaintainableManager.Instance.BumpHoldOffPendingLevel();

            WPFDoEvents.ResetHourglassCursor();
        }
Пример #9
0
        private void RepopulatePanels(PDFDocument doc)
        {
            var links = doc.PDFDocumentCitationManager.GetLinkedDocuments();

            WPFDoEvents.InvokeInUIThread(() =>
            {
                CitationsUserControl.PopulatePanelWithCitations(DocsPanel_Linked, doc, links, Features.LinkedDocument_InfoBar_OpenDoc);
            });
        }
        protected virtual void Dispose(bool disposing)
        {
            Logging.Debug("LibraryCatalogOverviewControl::Dispose({0}) @{1}", disposing, dispose_count);

            WPFDoEvents.SafeExec(() =>
            {
                if (dispose_count == 0)
                {
                    // Get rid of managed resources / get rid of cyclic references:
                    library_index_hover_popup?.Dispose();
                }
            });

            WPFDoEvents.SafeExec(() =>
            {
                WPFDoEvents.AssertThisCodeIsRunningInTheUIThread();
                if (dispose_count == 0)
                {
                    WizardDPs.ClearPointOfInterest(PanelSearchScore);
                }
            }, must_exec_in_UI_thread: true);

            WPFDoEvents.SafeExec(() =>
            {
                if (dispose_count == 0)
                {
                    WizardDPs.ClearPointOfInterest(ObjLookInsidePanel);
                }
            }, must_exec_in_UI_thread: true);

            WPFDoEvents.SafeExec(() =>
            {
                TextTitle.MouseLeftButtonUp -= TextTitle_MouseLeftButtonUp;

                ButtonOpen.ToolTipOpening -= HyperlinkPreview_ToolTipOpening;
                ButtonOpen.ToolTipClosing -= HyperlinkPreview_ToolTipClosing;

                ListSearchDetails.SearchClicked -= ListSearchDetails_SearchSelectionChanged;

                DataContextChanged -= LibraryCatalogOverviewControl_DataContextChanged;
            }, must_exec_in_UI_thread: true);

            WPFDoEvents.SafeExec(() =>
            {
                DataContext = null;
            }, must_exec_in_UI_thread: true);

            WPFDoEvents.SafeExec(() =>
            {
                // Clear the references for sanity's sake
                library_index_hover_popup = null;
                drag_drop_helper          = null;
            });

            ++dispose_count;
        }
Пример #11
0
        public MainWindow()
        {
            MainWindowServiceDispatcher.Instance.MainWindow = this;

            //Theme.Initialize(); -- already done in StandardWindow base class

            InitializeComponent();

            Application.Current.SessionEnding += Current_SessionEnding;
            Application.Current.Exit          += Current_Exit;

            HourglassState = 2;
            WPFDoEvents.SetHourglassCursor();

            DataContext = ConfigurationManager.Instance.ConfigurationRecord_Bindable;

            // Set a DEV title if necessary
            Title = String.Format("Qiqqa v{0}", ClientVersion.CurrentBuild);
            if (WebsiteAccess.IsTestEnvironment)
            {
                Title = String.Format("Qiqqa v{0} (TEST ENVIRONMENT)", ClientVersion.CurrentBuild);
            }

            DockingManager.WindowIcon  = Icons.GetAppIconICO(Icons.Qiqqa);
            DockingManager.OwnerWindow = this;

            DockingManager.AddContent(TITLE_START_PAGE, TITLE_START_PAGE, Icons.GetAppIcon(Icons.ModuleStartPage), false, true, ObjStartPage);
            DockingManager.MakeActive(TITLE_START_PAGE);

            ObjStatusBar.Background     = ThemeColours.Background_Brush_Blue_LightToDark;
            ObjTabBackground.Background = ThemeColours.Background_Brush_Blue_VeryDark;

            SizeChanged += MainWindow_SizeChanged;
            KeyUp       += MainWindow_KeyUp;

            //Unloaded += MainWindow_Unloaded;
            Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;
            Closing += MainWindow_Closing;
            Closed  += MainWindow_Closed;

            // We've looked for the LAST event that triggers dependably at the start of the application:
            //   ContentRendered
            // is the last one triggered of this bunch:
            //
            //this.Activated += MainWindow_Activated;
            ContentRendered += MainWindow_ContentRendered;
            //this.Initialized += MainWindow_Initialized;
            //this.LayoutUpdated += MainWindow_LayoutUpdated;
            //this.Loaded += MainWindow_Loaded;
            //this.ManipulationCompleted += MainWindow_ManipulationCompleted;
            //this.ManipulationStarting += MainWindow_ManipulationStarting;
            //this.SourceInitialized += MainWindow_SourceInitialized;
            //this.StateChanged += MainWindow_StateChanged;

            WebLibraryManager.Instance.WebLibrariesChanged += Instance_WebLibrariesChanged;
        }
        public static PivotResult GeneratePivot(MultiMapSet <string, string> map_y_axis, MultiMapSet <string, string> map_x_axis)
        {
            List <string> y_keys = new List <string>(map_y_axis.Keys);
            List <string> x_keys = new List <string>(map_x_axis.Keys);

            y_keys.Sort();
            x_keys.Sort();

            List <string>[,] common_fingerprints = new List <string> [y_keys.Count, x_keys.Count];

            StatusManager.Instance.ClearCancelled("LibraryPivot");
            int y_progress = 0;

            Parallel.For(0, y_keys.Count, (y, loop_state) =>
                         //for (int y = 0; y < y_keys.Count; ++y)
            {
                int y_progress_locked = Interlocked.Increment(ref y_progress);

                if (General.HasPercentageJustTicked(y_progress_locked, y_keys.Count))
                {
                    StatusManager.Instance.UpdateStatusBusy("LibraryPivot", "Building library pivot", y_progress_locked, y_keys.Count, true);

                    WPFDoEvents.WaitForUIThreadActivityDone(); // HackityHack

                    if (StatusManager.Instance.IsCancelled("LibraryPivot"))
                    {
                        Logging.Warn("User cancelled library pivot generation");
                        loop_state.Break();
                    }
                }

                string y_key = y_keys[y];
                HashSet <string> y_values = map_y_axis.Get(y_key);

                for (int x = 0; x < x_keys.Count; ++x)
                {
                    string x_key = x_keys[x];
                    HashSet <string> x_values = map_x_axis.Get(x_key);

                    var common_fingerprint = y_values.Intersect(x_values);
                    if (common_fingerprint.Any())
                    {
                        common_fingerprints[y, x] = new List <string>(common_fingerprint);
                    }
                }
            });

            StatusManager.Instance.UpdateStatus("LibraryPivot", "Built library pivot");

            PivotResult pivot_result = new PivotResult();

            pivot_result.y_keys = y_keys;
            pivot_result.x_keys = x_keys;
            pivot_result.common_fingerprints = common_fingerprints;
            return(pivot_result);
        }
 /// <summary>
 /// Always call this using the form xyz.NotifyPropertyChanged(nameof(yyy.ZZZ)), where ZZZ is the property that just got updated.
 /// That way the compiler will catch any property name changes.
 /// </summary>
 /// <param name="property_name"></param>
 public void NotifyPropertyChanged(string property_name)
 {
     // if (Application.Current == null || Application.Current.Dispatcher.Thread == Thread.CurrentThread)
     // as per: https://stackoverflow.com/questions/5143599/detecting-whether-on-ui-thread-in-wpf-and-winforms#answer-14280425
     // and: https://stackoverflow.com/questions/2982498/wpf-dispatcher-the-calling-thread-cannot-access-this-object-because-a-differen/13726324#13726324
     WPFDoEvents.InvokeInUIThread(() =>
     {
         NotifyPropertyChanged_THREADSAFE(property_name);
     });
 }
        public static void Popup()
        {
            FeatureTrackingManager.Instance.UseFeature(Features.InCite_OpenPopup);

            WPFDoEvents.InvokeAsyncInUIThread(() =>
            {
                Popup_DISPATCHER();
            }
                                              );
        }
Пример #15
0
        private void word_connector_CitationClusterChanged(CitationCluster context_citation_cluster)
        {
            Logging.Debug特("InCite: CitationClusterChanged: {0}", context_citation_cluster);

            WPFDoEvents.InvokeAsyncInUIThread(() =>
            {
                ObjCitationClusterEditorControl.SetCitationCluster(context_citation_cluster);
            }
                                              );
        }
Пример #16
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");
        }
Пример #17
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);
        }
        protected virtual void Dispose(bool disposing)
        {
            Logging.Debug("PDFAnnotationLayer::Dispose({0}) @{1}", disposing, dispose_count);

            WPFDoEvents.InvokeInUIThread(() =>
            {
                WPFDoEvents.SafeExec(() =>
                {
                    foreach (var el in Children)
                    {
                        IDisposable node = el as IDisposable;
                        if (null != node)
                        {
                            node.Dispose();
                        }
                    }
                });

                WPFDoEvents.SafeExec(() =>
                {
                    Children.Clear();
                });

                WPFDoEvents.SafeExec(() =>
                {
                    WizardDPs.ClearPointOfInterest(this);
                });

                WPFDoEvents.SafeExec(() =>
                {
                    if (drag_area_tracker != null)
                    {
                        drag_area_tracker.OnDragComplete -= drag_area_tracker_OnDragComplete;
                    }

                    Dispatcher.ShutdownStarted -= Dispatcher_ShutdownStarted;
                });

                WPFDoEvents.SafeExec(() =>
                {
                    // Clear the references for sanity's sake
                    pdf_document      = null;
                    drag_area_tracker = null;
                });

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

                ++dispose_count;

                //base.Dispose(disposing);     // parent only throws an exception (intentionally), so depart from best practices and don't call base.Dispose(bool)
            });
        }
        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);
                }
            }
        }
Пример #20
0
        protected virtual void Dispose(bool disposing)
        {
            Logging.Debug("PDFSearchLayer::Dispose({0}) @{1}", disposing, dispose_count);

            try
            {
                if (dispose_count == 0)
                {
                    WPFDoEvents.InvokeInUIThread(() =>
                    {
                        WPFDoEvents.AssertThisCodeIsRunningInTheUIThread();

                        try
                        {
                            foreach (var el in Children)
                            {
                                IDisposable node = el as IDisposable;
                                if (null != node)
                                {
                                    node.Dispose();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.Error(ex);
                        }

                        try
                        {
                            Children.Clear();
                        }
                        catch (Exception ex)
                        {
                            Logging.Error(ex);
                        }
                    }, Dispatcher);
                }

                // Clear the references for sanity's sake
                pdf_renderer_control_stats = null;
                search_result_set          = null;

                DataContext = null;
            }
            catch (Exception ex)
            {
                Logging.Error(ex);
            }

            ++dispose_count;

            //base.Dispose(disposing);     // parent only throws an exception (intentionally), so depart from best practices and don't call base.Dispose(bool)
        }
        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.");
        }
        protected virtual void Dispose(bool disposing)
        {
            Logging.Debug("StartPageControl::Dispose({0}) @{1}", disposing, dispose_count);

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

            ++dispose_count;
        }
Пример #23
0
        private void UpdateLibraryStatistics_Stats_Background_GUI_FillPlaceHolder(DocumentDisplayWork ddw)
        {
            WPFDoEvents.AssertThisCodeIsRunningInTheUIThread();

            if (ddw.image != null)
            {
                ddw.image.Source  = ddw.page_bitmap_source ?? Backgrounds.GetBackground(Backgrounds.PageRenderingFailed_Relax);
                ddw.image.Stretch = Stretch.Uniform;
            }
            ddw.border.Visibility = Visibility.Visible;
        }
Пример #24
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();
            }
        }
Пример #25
0
        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;
            }
        }
Пример #26
0
 private static void RemarkOnException(Exception ex)
 {
     Logging.Error(ex, "RemarkOnException.....");
     if (null != Application.Current)
     {
         WPFDoEvents.InvokeInUIThread(() =>
         {
             RemarkOnException_GUI_THREAD(ex);
         }
                                      );
     }
 }
Пример #27
0
        protected virtual void Dispose(bool disposing)
        {
            Logging.Debug("PDFHandLayer::Dispose({0}) @{1}", disposing, dispose_count);

            WPFDoEvents.InvokeInUIThread(() =>
            {
                WPFDoEvents.SafeExec(() =>
                {
                    if (0 == dispose_count)
                    {
                        WPFDoEvents.AssertThisCodeIsRunningInTheUIThread();

                        foreach (var el in Children)
                        {
                            IDisposable node = el as IDisposable;
                            if (null != node)
                            {
                                node.Dispose();
                            }
                        }
                    }
                });

                WPFDoEvents.SafeExec(() =>
                {
                    Children.Clear();
                });

                WPFDoEvents.SafeExec(() =>
                {
                    MouseDown -= PDFHandLayer_MouseDown;
                    MouseUp   -= PDFHandLayer_MouseUp;
                    MouseMove -= PDFHandLayer_MouseMove;

                    Dispatcher.ShutdownStarted -= Dispatcher_ShutdownStarted;
                });

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

                WPFDoEvents.SafeExec(() =>
                {
                    // Clear the references for sanity's sake
                    pdf_renderer_control = null;
                });

                ++dispose_count;

                //base.Dispose(disposing);     // parent only throws an exception (intentionally), so depart from best practices and don't call base.Dispose(bool)
            });
        }
Пример #28
0
        private void NotifySceneRenderingControl()
        {
            WPFDoEvents.InvokeAsyncInUIThread(() =>
            {
                SceneRenderingControl scene_rendering_control = SceneRenderingControl;

                if (scene_rendering_control != null)
                {
                    scene_rendering_control.RecalculateAllNodeControlDimensions();
                }
            }, DispatcherPriority.Background);
        }
        private static BitmapSource GetSnappedImage(DocPageInfo page_info, Point mouse_up_point, Point mouse_down_point)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            BitmapSource cropped_image_page = null;

            using (MemoryStream ms = new MemoryStream(page_info.pdf_document.GetPageByDPIAsImage(page_info.page, 150)))
            {
                PngBitmapDecoder decoder    = new PngBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                BitmapSource     image_page = decoder.Frames[0];
                if (null != image_page)
                {
                    double left   = Math.Min(mouse_up_point.X, mouse_down_point.X) * image_page.PixelWidth / page_info.ActualWidth;
                    double top    = Math.Min(mouse_up_point.Y, mouse_down_point.Y) * image_page.PixelHeight / page_info.ActualHeight;
                    double width  = Math.Abs(mouse_up_point.X - mouse_down_point.X) * image_page.PixelWidth / page_info.ActualWidth;
                    double height = Math.Abs(mouse_up_point.Y - mouse_down_point.Y) * image_page.PixelHeight / page_info.ActualHeight;

                    left   = Math.Max(left, 0);
                    top    = Math.Max(top, 0);
                    width  = Math.Min(width, image_page.PixelWidth - left);
                    height = Math.Min(height, image_page.PixelHeight - top);

                    if (0 < width && 0 < height)
                    {
                        var cropped = new CroppedBitmap(image_page, new Int32Rect((int)left, (int)top, (int)width, (int)height));

                        // UPDATE HERE: CroppedBitmap to BitmapImage
                        // cropped_image_page = GetJpgImage(cropped.Source);
                        // or
                        //cropped_image_page = GetPngImage(cropped.Source);

                        using (MemoryStream mStream = new MemoryStream())
                        {
                            PngBitmapEncoder jEncoder = new PngBitmapEncoder();

                            jEncoder.Frames.Add(BitmapFrame.Create(cropped));  // the croppedBitmap is a CroppedBitmap object

                            // jEncoder.QualityLevel = 75;
                            jEncoder.Save(mStream);

                            cropped_image_page = BitmapImageTools.LoadFromStream(mStream);

                            // I can also get array of bytes that represent the cropped image by call this method : mStream.GetBuffer()

                            //cropped_image_page = BitmapImageTools.CropImageRegion(image_page, left, top, width, height);
                        }
                    }
                }

                return(cropped_image_page);
            }
        }
        protected virtual void Dispose(bool disposing)
        {
            Logging.Debug("PDFAnnotationItem::Dispose({0}) @{1}", disposing, dispose_count);

            WPFDoEvents.InvokeInUIThread(() =>
            {
                WPFDoEvents.SafeExec(() =>
                {
                    if (dispose_count == 0)
                    {
                        // Get rid of managed resources / get rid of cyclic references:
                        if (null != pdf_annotation)
                        {
                            pdf_annotation.Bindable.PropertyChanged -= pdf_annotation_PropertyChanged;
                        }

                        ButtonAnnotationDetails.MouseEnter  -= ButtonAnnotationDetails_MouseEnter;
                        ButtonAnnotationDetails.MouseLeave  -= ButtonAnnotationDetails_MouseLeave;
                        ButtonAnnotationDetails.MouseDown   -= ButtonAnnotationDetails_MouseDown;
                        TextAnnotationText.GotFocus         -= TextAnnotationText_GotFocus;
                        TextAnnotationText.LostFocus        -= TextAnnotationText_LostFocus;
                        TextAnnotationText.PreviewMouseDown -= TextAnnotationText_PreviewMouseDown;
                        TextAnnotationText.PreviewMouseMove -= TextAnnotationText_PreviewMouseMove;
                        TextAnnotationText.PreviewMouseUp   -= TextAnnotationText_PreviewMouseUp;

                        ObjTagEditorControl.GotFocus  -= ObjTagEditorControl_GotFocus;
                        ObjTagEditorControl.LostFocus -= ObjTagEditorControl_LostFocus;

                        ObjTagEditorControl.TagFeature_Add    = null;
                        ObjTagEditorControl.TagFeature_Remove = null;

                        Dispatcher.ShutdownStarted -= Dispatcher_ShutdownStarted;
                    }
                });

                WPFDoEvents.SafeExec(() =>
                {
                    // Clear the references for sanity's sake
                    DataContext = null;
                });

                WPFDoEvents.SafeExec(() =>
                {
                    pdf_annotation_layer = null;
                    pdf_annotation       = null;

                    pdf_annotation_editor_control_popup = null;
                });

                ++dispose_count;
            });
        }