Exemplo n.º 1
0
        public LibraryView(LibraryModel model, LibraryListView.Factory libraryListViewFactory,
                           LibraryBookView.Factory templateBookViewFactory,
                           SelectedTabChangedEvent selectedTabChangedEvent,
                           SendReceiveCommand sendReceiveCommand,
                           TeamCollectionManager tcManager)
        {
            _model = model;
            InitializeComponent();
            splitContainer1.BackColor = Palette.BookListSplitterColor;             // controls the left vs. right splitter
            _toolStrip.Renderer       = new NoBorderToolStripRenderer();
            _toolStripLeft.Renderer   = new NoBorderToolStripRenderer();

            _collectionListView      = libraryListViewFactory();
            _collectionListView.Dock = DockStyle.Fill;
            splitContainer1.Panel1.Controls.Add(_collectionListView);

            _bookView = templateBookViewFactory();
            _bookView.TeamCollectionMgr = tcManager;
            _bookView.Dock = DockStyle.Fill;
            splitContainer1.Panel2.Controls.Add(_bookView);

            // When going down to Shrink Stage 3 (see WorkspaceView), we want the right-side toolstrip to take precedence
            // (Settings, Other Collection).
            // This essentially makes the TC Status button's zIndex less than the buttons on the right side.
            _toolStripLeft.SendToBack();

            splitContainer1.SplitterDistance = _collectionListView.PreferredWidth;
            _makeBloomPackButton.Visible     = model.IsShellProject;
            _sendReceiveButton.Visible       = Settings.Default.ShowSendReceive;

            if (sendReceiveCommand != null)
            {
#if Chorus
                _sendReceiveButton.Click  += (x, y) => sendReceiveCommand.Raise(this);
                _sendReceiveButton.Enabled = !SendReceiver.SendReceiveDisabled;
#endif
            }
            else
            {
                _sendReceiveButton.Enabled = false;
            }

            if (SIL.PlatformUtilities.Platform.IsMono)
            {
                BackgroundColorsForLinux();
            }

            selectedTabChangedEvent.Subscribe(c =>
            {
                if (c.To == this)
                {
                    Logger.WriteEvent("Entered Collections Tab");
                }
            });
            SetTeamCollectionStatus(tcManager);
            TeamCollectionManager.TeamCollectionStatusChanged += (sender, args) =>
            {
                if (IsHandleCreated && !IsDisposed)
                {
                    SafeInvoke.InvokeIfPossible("update TC status", this, false,
                                                () => SetTeamCollectionStatus(tcManager));
                }
            };
            _tcStatusButton.Click += (sender, args) =>
            {
                // Any messages for which reloading the collection is a useful action?
                var showReloadButton = tcManager.MessageLog.ShouldShowReloadButton;
                // Reinstate this to see messages from before we started up.
                // We think it might be too expensive to show a list as long as this might get.
                // Instead, in the short term we may add a button to show the file.
                // Later we may implement some efficient way to scroll through them.
                // tcManager.CurrentCollection?.MessageLog?.LoadSavedMessages();
                using (var dlg = new ReactDialog("teamCollectionDialogBundle", new
                {
                    showReloadButton
                }, "Team Collection"))
                {
                    dlg.ShowDialog(this);
                    tcManager.CurrentCollectionEvenIfDisconnected?.MessageLog.WriteMilestone(MessageAndMilestoneType
                                                                                             .LogDisplayed);
                }
            };
        }
        private void ShowIdCollisionDialog()
        {
            var newThumbPath = ChooseBestUploadingThumbnailPath(_model.Book).ToLocalhost();
            var newTitle     = _model.Book.TitleBestForUserDisplay;
            var newLanguages = ConvertLanguageCodesToNames(LanguagesCheckedToUpload, _model.Book.BookData);

            if (_signLanguageCheckBox.Checked && !string.IsNullOrEmpty(CurrentSignLanguageName))
            {
                var newLangs = newLanguages.ToList();
                if (!newLangs.Contains(CurrentSignLanguageName))
                {
                    newLangs.Add(CurrentSignLanguageName);
                }
                newLanguages = newLangs;
            }

            var existingBookInfo = _model.ConflictingBookInfo;
            var updatedDateTime  = (DateTime)existingBookInfo.updatedAt;
            var createdDateTime  = (DateTime)existingBookInfo.createdAt;
            // Find the best title available (BL-11027)
            // Users can click on this title to bring up the existing book's page.
            var existingTitle = existingBookInfo.title?.Value;

            if (String.IsNullOrEmpty(existingTitle))
            {
                // If title is undefined (which should not be the case), then use the first title from allTitles.
                var allTitlesString = existingBookInfo.allTitles?.Value;
                if (!String.IsNullOrEmpty(allTitlesString))
                {
                    try
                    {
                        var allTitles = Newtonsoft.Json.Linq.JObject.Parse(allTitlesString);
                        foreach (var title in allTitles)
                        {
                            // title.Value is dynamic language code / title string pair
                            // title.Value.Value is the actual book title in the associated language
                            if (title?.Value?.Value != null)
                            {
                                existingTitle = title.Value.Value;
                                break;
                            }
                        }
                    }
                    catch
                    {
                        // ignore parse failure -- should never happen at this point.
                    }
                }
            }
            // If neither title nor allTitles are defined, just give a placeholder value.
            if (String.IsNullOrEmpty(existingTitle))
            {
                existingTitle = "Unknown";
            }

            var existingId      = existingBookInfo.objectId.ToString();
            var existingBookUrl = BloomLibraryUrlPrefix + "/book/" + existingId;

            var existingLanguages = ConvertLanguagePointerObjectsToNames(existingBookInfo.langPointers);
            var createdDate       = createdDateTime.ToString("d", CultureInfo.CurrentCulture);
            var updatedDate       = updatedDateTime.ToString("d", CultureInfo.CurrentCulture);
            var existingThumbUrl  = GetBloomLibraryThumbnailUrl(existingBookInfo);

            using (var dlg = new ReactDialog("uploadIDCollisionDlgBundle",
                                             // Props for dialog; must be the same as IUploadCollisionDlgProps in js-land.
                                             new
            {
                userEmail = _model.LoggedIn ? _userId.Text : "",
                newThumbUrl = newThumbPath,
                newTitle,
                newLanguages,
                existingTitle = existingTitle,
                existingLanguages,
                existingCreatedDate = createdDate,
                existingUpdatedDate = updatedDate,
                existingBookUrl,
                existingThumbUrl
            }
                                             ))
            {
                dlg.Width      = 770;
                dlg.Height     = 570;
                dlg.ControlBox = false;
                dlg.ShowDialog(Shell.GetShellOrOtherOpenForm());
            }
        }
Exemplo n.º 3
0
        // ENHANCE: Reduce duplication in HtmlErrorReporter and ProblemReportApi code. Some of the ProblemReportApi code can move to HtmlErrorReporter code.

        // ENHANCE: I think levelOfProblem would benefit from being required and being an enum.

        /// <summary>
        /// Shows a problem dialog.
        /// </summary>
        /// <param name="controlForScreenshotting"></param>
        /// <param name="exception"></param>
        /// <param name="detailedMessage"></param>
        /// <param name="levelOfProblem">"user", "nonfatal", or "fatal"</param>
        /// <param name="additionalPathsToInclude"></param>
        public static void ShowProblemDialog(Control controlForScreenshotting, Exception exception,
                                             string detailedMessage            = "", string levelOfProblem = "user", string shortUserLevelMessage = "", bool isShortMessagePreEncoded = false,
                                             string[] additionalPathsToInclude = null)
        {
            // Before we do anything that might be "risky", put the problem in the log.
            LogProblem(exception, detailedMessage, levelOfProblem);
            if (Program.RunningHarvesterMode)
            {
                Console.WriteLine(levelOfProblem + " Problem Detected: " + shortUserLevelMessage + "  " + detailedMessage + "  " + exception);
                return;
            }
            StartupScreenManager.CloseSplashScreen();             // if it's still up, it'll be on top of the dialog

            lock (_showingProblemReportLock)
            {
                if (_showingProblemReport)
                {
                    // If a problem is reported when already reporting a problem, that could
                    // be an unbounded recursion that freezes the program and prevents the original
                    // problem from being reported.  So minimally report the recursive problem and stop
                    // the recursion in its tracks.
                    //
                    // Alternatively, can happen if multiple async BloomAPI calls go out and return errors.
                    // It's probably not helpful to have multiple problem report dialogs at the same time
                    // in this case either (even if there are theoretically a finite (not infinite) number of them)
                    const string msg = "MULTIPLE CALLS to ShowProblemDialog. Suppressing the subsequent calls";
                    Console.Write(msg);
                    Logger.WriteEvent(msg);
                    return;                     // Abort
                }

                _showingProblemReport = true;
            }

            // We have a better UI for this problem
            // Note that this will trigger whether it's a plain 'ol System.IO.PathTooLongException, or our own enhanced subclass, Bloom.Utiles.PathTooLongException
            if (exception is System.IO.PathTooLongException)
            {
                Utils.LongPathAware.ReportLongPath((System.IO.PathTooLongException)exception);
                return;
            }

            GatherReportInfoExceptScreenshot(exception, detailedMessage, shortUserLevelMessage, isShortMessagePreEncoded);

            if (controlForScreenshotting == null)
            {
                controlForScreenshotting = Form.ActiveForm;
            }
            if (controlForScreenshotting == null)             // still possible if we come from a "Details" button
            {
                controlForScreenshotting = FatalExceptionHandler.ControlOnUIThread;
            }
            ResetScreenshotFile();
            // Originally, we used SafeInvoke for both the screenshot and the new dialog display. SafeInvoke was great
            // for trying to get a screenshot, but having the actual dialog inside
            // of it was causing problems for handling any errors in showing the dialog.
            // Now we use SafeInvoke only inside of this extracted method.
            TryGetScreenshot(controlForScreenshotting);

            if (BloomServer._theOneInstance == null)
            {
                // We got an error really early, before we can use HTML dialogs. Report using the old dialog.
                // Hopefully we're still on the one main thread.
                HtmlErrorReporter.ShowFallbackProblemDialog(levelOfProblem, exception, detailedMessage, shortUserLevelMessage, isShortMessagePreEncoded);
                return;
            }

            SafeInvoke.InvokeIfPossible("Show Problem Dialog", controlForScreenshotting, false, () =>
            {
                // Uses a browser ReactDialog (if possible) to show the problem report
                try
                {
                    // We call CloseSplashScreen() above too, where it might help in some cases, but
                    // this one, while apparently redundant might be wise to keep since closing the splash screen
                    // needs to be done on the UI thread.
                    StartupScreenManager.CloseSplashScreen();

                    if (!BloomServer.ServerIsListening)
                    {
                        // We can't use the react dialog!
                        HtmlErrorReporter.ShowFallbackProblemDialog(levelOfProblem, exception, detailedMessage, shortUserLevelMessage, isShortMessagePreEncoded);
                        return;
                    }

                    // Precondition: we must be on the UI thread for Gecko to work.
                    using (var dlg = new ReactDialog("problemReportBundle", new { level = levelOfProblem }, "Problem Report"))
                    {
                        _additionalPathsToInclude = additionalPathsToInclude;
                        dlg.FormBorderStyle       = FormBorderStyle.FixedToolWindow; // Allows the window to be dragged around
                        dlg.ControlBox            = true;                            // Add controls like the X button back to the top bar
                        dlg.Text = "";                                               // Remove the title from the WinForms top bar

                        dlg.Width  = 731;
                        dlg.Height = 616;

                        // ShowDialog will cause this thread to be blocked (because it spins up a modal) until the dialog is closed.
                        BloomServer._theOneInstance.RegisterThreadBlocking();
                        try
                        {
                            // Keep dialog on top of program window if possible.  See https://issues.bloomlibrary.org/youtrack/issue/BL-10292.
                            if (controlForScreenshotting is Bloom.Shell)
                            {
                                dlg.ShowDialog(controlForScreenshotting);
                            }
                            else
                            {
                                dlg.ShowDialog();
                            }
                        }
                        finally
                        {
                            BloomServer._theOneInstance.RegisterThreadUnblocked();
                            _additionalPathsToInclude = null;
                        }
                    }
                }
                catch (Exception problemReportException)
                {
                    Logger.WriteError("*** ProblemReportApi threw an exception trying to display", problemReportException);
                    // At this point our problem reporter has failed for some reason, so we want the old WinForms handler
                    // to report both the original error for which we tried to open our dialog and this new one where
                    // the dialog itself failed.
                    // In order to do that, we create a new exception with the original exception (if there was one) as the
                    // inner exception. We include the message of the exception we just caught. Then we call the
                    // old WinForms fatal exception report directly.
                    // In any case, both of the errors will be logged by now.
                    var message = "Bloom's error reporting failed: " + problemReportException.Message;

                    // Fallback to Winforms in case of trouble getting the browser up
                    var fallbackReporter = new WinFormsErrorReporter();
                    // ENHANCE?: If reporting a non-fatal problem failed, why is the program required to abort? It might be able to handle other tasks successfully
                    fallbackReporter.ReportFatalException(new ApplicationException(message, exception ?? problemReportException));
                }
                finally
                {
                    lock (_showingProblemReportLock)
                    {
                        _showingProblemReport = false;
                    }
                }
            });
        }
        public ReactCollectionTabView(LibraryModel model, LibraryListView.Factory libraryListViewFactory,
                                      LibraryBookView.Factory templateBookViewFactory,
                                      SelectedTabChangedEvent selectedTabChangedEvent,
                                      SendReceiveCommand sendReceiveCommand,
                                      TeamCollectionManager tcManager)
        {
            _model = model;
            InitializeComponent();
            BackColor               = _reactControl.BackColor = Palette.GeneralBackground;
            _toolStrip.Renderer     = new NoBorderToolStripRenderer();
            _toolStripLeft.Renderer = new NoBorderToolStripRenderer();

            // When going down to Shrink Stage 3 (see WorkspaceView), we want the right-side toolstrip to take precedence
            // (Settings, Other Collection).
            // This essentially makes the TC Status button's zIndex less than the buttons on the right side.
            _toolStripLeft.SendToBack();

            //TODO splitContainer1.SplitterDistance = _collectionListView.PreferredWidth;
            _makeBloomPackButton.Visible = model.IsShellProject;
            _sendReceiveButton.Visible   = Settings.Default.ShowSendReceive;

            if (sendReceiveCommand != null)
            {
#if Chorus
                _sendReceiveButton.Click  += (x, y) => sendReceiveCommand.Raise(this);
                _sendReceiveButton.Enabled = !SendReceiver.SendReceiveDisabled;
#endif
            }
            else
            {
                _sendReceiveButton.Enabled = false;
            }

            if (SIL.PlatformUtilities.Platform.IsMono)
            {
                BackgroundColorsForLinux();
            }

            selectedTabChangedEvent.Subscribe(c =>
            {
                if (c.To == this)
                {
                    Logger.WriteEvent("Entered Collections Tab");
                }
            });
            SetTeamCollectionStatus(tcManager);
            TeamCollectionManager.TeamCollectionStatusChanged += (sender, args) =>
            {
                return;

                if (!IsDisposed)
                {
                    SafeInvoke.InvokeIfPossible("update TC status", this, false,
                                                () => SetTeamCollectionStatus(tcManager));
                }
            };
            _tcStatusButton.Click += (sender, args) =>
            {
                // Any messages for which reloading the collection is a useful action?
                var showReloadButton = tcManager.MessageLog.ShouldShowReloadButton;
                // Reinstate this to see messages from before we started up.
                // We think it might be too expensive to show a list as long as this might get.
                // Instead, in the short term we may add a button to show the file.
                // Later we may implement some efficient way to scroll through them.
                // tcManager.CurrentCollection?.MessageLog?.LoadSavedMessages();
                using (var dlg = new ReactDialog("teamCollectionDialog", new { showReloadButton }))
                {
                    dlg.ShowDialog(this);
                    tcManager.CurrentCollectionEvenIfDisconnected?.MessageLog.WriteMilestone(MessageAndMilestoneType.LogDisplayed);
                }
            };

            // We don't want this control initializing until team collections sync (if any) is done.
            // That could change, but for now we're not trying to handle async changes arriving from
            // the TC to the local collection, and as part of that, the collection tab doesn't expect
            // the local collection to change because of TC stuff once it starts loading.
            Controls.Remove(_reactControl);
        }