Contains the logic behind the PublishView control, which involves creating a pdf from the html book and letting you print it.
Inheritance: IDisposable
Ejemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="inputHtmlPath"></param>
        /// <param name="outputPdfPath"></param>
        /// <param name="paperSizeName">A0,A1,A2,A3,A4,A5,A6,A7,A8,A9,B0,B1,B10,B2,B3,B4,B5,B6,B7,B8,B9,C5E,Comm10E,DLE,Executive,Folio,Ledger,Legal,Letter,Tabloid</param>
        /// <param name="landscape"> </param>
        /// <param name="booketLayoutMethod"> </param>
        /// <param name="bookletPortion"></param>
        /// <param name="doWorkEventArgs"> </param>
        /// <param name="getIsLandscape"></param>
        public void MakePdf(string inputHtmlPath, string outputPdfPath, string paperSizeName, bool landscape, PublishModel.BookletLayoutMethod booketLayoutMethod, PublishModel.BookletPortions bookletPortion,  DoWorkEventArgs doWorkEventArgs)
        {
            Guard.Against(Path.GetExtension(inputHtmlPath) != ".htm",
                          "wkhtmtopdf will croak if the input file doesn't have an htm extension.");

            MakeSimplePdf(inputHtmlPath, outputPdfPath, paperSizeName, landscape, doWorkEventArgs);
            if (doWorkEventArgs.Cancel || (doWorkEventArgs.Result!=null && doWorkEventArgs.Result is Exception))
                return;
            if (bookletPortion != PublishModel.BookletPortions.AllPagesNoBooklet)
            {
                //remake the pdf by reording the pages (and sometimes rotating, shrinking, etc)
                MakeBooklet(outputPdfPath, paperSizeName, booketLayoutMethod);
            }
        }
Ejemplo n.º 2
0
        public delegate PublishView Factory();        //autofac uses this

        public PublishView(PublishModel model,
                           SelectedTabChangedEvent selectedTabChangedEvent, LocalizationChangedEvent localizationChangedEvent, BookTransfer bookTransferrer, LoginDialog login)
        {
            _bookTransferrer = bookTransferrer;
            _loginDialog     = login;

            InitializeComponent();

            if (this.DesignMode)
            {
                return;
            }

            _model      = model;
            _model.View = this;

            _makePdfBackgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(_makePdfBackgroundWorker_RunWorkerCompleted);

            //NB: just triggering off "VisibilityChanged" was unreliable. So now we trigger
            //off the tab itself changing, either to us or away from us.
            selectedTabChangedEvent.Subscribe(c =>
            {
                if (c.To == this)
                {
                    Activate();
                }
                else if (c.To != this && IsMakingPdf)
                {
                    _makePdfBackgroundWorker.CancelAsync();
                }
            });

            //TODO: find a way to call this just once, at the right time:

            //			DeskAnalytics.Track("Publish");

//#if DEBUG
//          var linkLabel = new LinkLabel() {Text = "DEBUG"};
//			linkLabel.Click+=new EventHandler((x,y)=>_model.DebugCurrentPDFLayout());
//          tableLayoutPanel1.Controls.Add(linkLabel);
//#endif

            _menusToolStrip.Renderer = new EditingView.FixedToolStripRenderer();
            GeckoPreferences.Default["pdfjs.disabled"] = false;
            SetupLocalization();
            localizationChangedEvent.Subscribe(o => SetupLocalization());
        }
Ejemplo n.º 3
0
        public delegate PublishView Factory();        //autofac uses this

        public PublishView(PublishModel model,
                           SelectedTabChangedEvent selectedTabChangedEvent)
        {
            InitializeComponent();
            Controls.Remove(_saveButton);                    //our parent will retrieve this
            Controls.Remove(_printButton);                   //our parent will retrieve this

            if (this.DesignMode)
            {
                return;
            }

            _model      = model;
            _model.View = this;

            _makePdfBackgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(_makePdfBackgroundWorker_RunWorkerCompleted);

            //NB: just triggering off "VisibilityChanged" was unreliable. So now we trigger
            //off the tab itself changing, either to us or away from us.
            selectedTabChangedEvent.Subscribe(c =>
            {
                if (c.To == this)
                {
                    Activate();
                }
                else if (c.To != this && _makePdfBackgroundWorker.IsBusy)
                {
                    _makePdfBackgroundWorker.CancelAsync();
                }
            });

            //TODO: find a way to call this just once, at the right time:

            //			DeskAnalytics.Track("Publish");

//#if DEBUG
//          var linkLabel = new LinkLabel() {Text = "DEBUG"};
//			linkLabel.Click+=new EventHandler((x,y)=>_model.DebugCurrentPDFLayout());
//          tableLayoutPanel1.Controls.Add(linkLabel);
//#endif

            _menusToolStrip.Renderer = new EditingView.FixedToolStripRenderer();
        }
Ejemplo n.º 4
0
        //autofac uses this
        public PublishView(PublishModel model,
			SelectedTabChangedEvent selectedTabChangedEvent)
        {
            InitializeComponent();
                Controls.Remove(_saveButton);//our parent will retrieve this
                Controls.Remove(_printButton);//our parent will retrieve this

            if(this.DesignMode)
                return;

            _model = model;
            _model.View = this;

            _makePdfBackgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(_makePdfBackgroundWorker_RunWorkerCompleted);

            //NB: just triggering off "VisibilityChanged" was unreliable. So now we trigger
            //off the tab itself changing, either to us or away from us.
            selectedTabChangedEvent.Subscribe(c=>
                                                {
                                                    if (c.To == this)
                                                    {
                                                        Activate();
                                                    }
                                                    else if (c.To!=this && _makePdfBackgroundWorker.IsBusy)
                                                        _makePdfBackgroundWorker.CancelAsync();
                                                });

            //TODO: find a way to call this just once, at the right time:

            //			DeskAnalytics.Track("Publish");

            //#if DEBUG
            //        	var linkLabel = new LinkLabel() {Text = "DEBUG"};
            //			linkLabel.Click+=new EventHandler((x,y)=>_model.DebugCurrentPDFLayout());
            //        	tableLayoutPanel1.Controls.Add(linkLabel);
            //#endif

            _menusToolStrip.Renderer = new EditingView.FixedToolStripRenderer();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Handles the recursion through directories: if a folder looks like a Bloom book upload it; otherwise, try its children.
        /// Invisible folders like .hg are ignored.
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="dlg"></param>
        /// <param name="container"></param>
        /// <param name="context"></param>
        private void UploadInternal(string folder, BulkUploadProgressDlg dlg, ApplicationContainer container, ref ProjectContext context)
        {
            if (Path.GetFileName(folder).StartsWith("."))
                return; // secret folder, probably .hg

            if (Directory.GetFiles(folder, "*.htm").Count() == 1)
            {
                // Exactly one htm file, assume this is a bloom book folder.
                dlg.Progress.WriteMessage("Starting to upload " + folder);

                // Make sure the files we want to upload are up to date.
                // Unfortunately this requires making a book object, which requires making a ProjectContext, which must be created with the
                // proper parent book collection if possible.
                var parent = Path.GetDirectoryName(folder);
                var collectionPath = Directory.GetFiles(parent, "*.bloomCollection").FirstOrDefault();
                if (collectionPath == null && context == null)
                {
                    collectionPath = Settings.Default.MruProjects.Latest;
                }
                if (context == null || context.SettingsPath != collectionPath)
                {
                    if (context != null)
                        context.Dispose();
                    // optimise: creating a context seems to be quite expensive. Probably the only thing we need to change is
                    // the collection. If we could update that in place...despite autofac being told it has lifetime scope...we would save some time.
                    // Note however that it's not good enough to just store it in the project context. The one that is actually in
                    // the autofac object (_scope in the ProjectContext) is used by autofac to create various objects, in particular, books.
                    context = container.CreateProjectContext(collectionPath);
                }
                var server = context.BookServer;
                var book = server.GetBookFromBookInfo(new BookInfo(folder, true));
                book.BringBookUpToDate(new NullProgress());

                // Assemble the various arguments needed to make the objects normally involved in an upload.
                // We leave some constructor arguments not actually needed for this purpose null.
                var bookSelection = new BookSelection();
                bookSelection.SelectBook(book);
                var currentEditableCollectionSelection = new CurrentEditableCollectionSelection();
                if (collectionPath != null)
                {
                    var collection = new BookCollection(collectionPath, BookCollection.CollectionType.SourceCollection,
                        bookSelection);
                    currentEditableCollectionSelection.SelectCollection(collection);
                }
                var publishModel = new PublishModel(bookSelection, new PdfMaker(), currentEditableCollectionSelection, null, server, _thumbnailer, null);
                publishModel.PageLayout = book.GetLayout();
                var view = new PublishView(publishModel, new SelectedTabChangedEvent(), new LocalizationChangedEvent(), this, null, null);
                string dummy;
                // Normally we let the user choose which languages to upload. Here, just the ones that have complete information.
                var langDict = book.AllLanguages;
                var languagesToUpload = langDict.Keys.Where(l => langDict[l]).ToArray();
                if (languagesToUpload.Any())
                    FullUpload(book, dlg.Progress, view, languagesToUpload, out dummy, dlg);
                return;
            }
            foreach (var sub in Directory.GetDirectories(folder))
                UploadInternal(sub, dlg, container, ref context);
        }
 public ElectronicPublishView(PublishModel publishModel)
 {
     _model = publishModel;
 }
Ejemplo n.º 7
0
        ///  <summary>
        ///
        ///  </summary>
        /// <param name="inputHtmlPath"></param>
        /// <param name="outputPdfPath"></param>
        /// <param name="paperSizeName">A0,A1,A2,A3,A4,A5,A6,A7,A8,A9,B0,B1,B10,B2,B3,B4,B5,B6,B7,B8,B9,C5E,Comm10E,DLE,Executive,Folio,Ledger,Legal,Letter,Tabloid</param>
        /// <param name="landscape">true if landscape orientation, false if portrait orientation</param>
        /// <param name="saveMemoryMode">true if PDF file is to be produced using less memory (but more time)</param>
        /// <param name="layoutPagesForRightToLeft">true if RTL, false if LTR layout</param>
        /// <param name="booketLayoutMethod">NoBooklet,SideFold,CutAndStack,Calendar</param>
        /// <param name="bookletPortion">None,AllPagesNoBooklet,BookletCover,BookletPages,InnerContent</param>
        /// <param name="worker">If not null, the Background worker which is running this task, and may be queried to determine whether a cancel is being attempted</param>
        /// <param name="doWorkEventArgs">The event passed to the worker when it was started. If a cancel is successful, it's Cancel property should be set true.</param>
        /// <param name="owner">A control which can be used to invoke parts of the work which must be done on the ui thread.</param>
        public void MakePdf(string inputHtmlPath, string outputPdfPath, string paperSizeName, bool landscape, bool saveMemoryMode, bool layoutPagesForRightToLeft,
			PublishModel.BookletLayoutMethod booketLayoutMethod, PublishModel.BookletPortions bookletPortion, BackgroundWorker worker, DoWorkEventArgs doWorkEventArgs, Control owner)
        {
            // Try up to 4 times. This is a last-resort attempt to handle BL-361.
            // Most likely that was caused by a race condition in MakePdfUsingGeckofxHtmlToPdfComponent.MakePdf,
            // but as it was an intermittent problem and we're not sure that was the cause, this might help.
            for (int i = 0; i < 4; i++)
            {
                new MakePdfUsingGeckofxHtmlToPdfProgram().MakePdf(inputHtmlPath, outputPdfPath, paperSizeName, landscape, saveMemoryMode,
                    owner, worker, doWorkEventArgs);

                if (doWorkEventArgs.Cancel || (doWorkEventArgs.Result != null && doWorkEventArgs.Result is Exception))
                    return;
                if (RobustFile.Exists(outputPdfPath))
                    break; // normally the first time
            }
            if (!RobustFile.Exists(outputPdfPath) && owner != null)
            {
                // Should never happen, but...
                owner.Invoke((Action) (() =>
                {
                    // Review: should we localize this? Hopefully the user never sees it...don't want to increase burden on localizers...
                    MessageBox.Show(
                        "Bloom unexpectedly failed to create the PDF. If this happens repeatedy please report it to the developers. Probably it will work if you just try again.",
                        "Pdf creation failed", MessageBoxButtons.OK);
                }));
            }

            try
            {
                if (bookletPortion != PublishModel.BookletPortions.AllPagesNoBooklet)
                {
                    //remake the pdf by reording the pages (and sometimes rotating, shrinking, etc)
                    MakeBooklet(outputPdfPath, paperSizeName, booketLayoutMethod, layoutPagesForRightToLeft);
                }
                else
                {
                     // Just check that we got a valid, readable PDF. (MakeBooklet has to read the PDF itself,
                    // so we don't need to do this check if we're calling that.)
                    // If we get a reliable fix to BL-932 we can take this 'else' out altogether.
                    CheckPdf(outputPdfPath);
                }
            }
            catch (KeyNotFoundException e)
            {
                // This is characteristic of BL-932, where Gecko29 fails to make a valid PDF, typically
                // because the user has embedded a really huge image, something like 4000 pixels wide.
                // We think it could also happen with a very long book or if the user is short of memory.
                // The resulting corruption of the PDF file takes the form of a syntax error in an embedded
                // object so that the parser finds an empty string where it expected a 'generationNumber'
                // (currently line 106 of Parser.cs). This exception is swallowed but leads to an empty
                // externalIDs dictionary in PdfImportedObjectTable, and eventually a new exception trying
                // to look up an object ID at line 121 of that class. We catch that exception here and
                // suggest possible actions the user can take until we find a better solution.
                SIL.Reporting.ErrorReport.NotifyUserOfProblem(e,
                    LocalizationManager.GetString("PublishTab.PdfMaker.BadPdf", "Bloom had a problem making a PDF of this book. You may need technical help or to contact the developers. But here are some things you can try:")
                        + Environment.NewLine + "- "
                        + LocalizationManager.GetString("PublishTab.PdfMaker.TryRestart", "Restart your computer and try this again right away")
                        + Environment.NewLine + "- "
                        +
                        LocalizationManager.GetString("PublishTab.PdfMaker.TrySmallerImages",
                            "Replace large, high-resolution images in your document with lower-resolution ones")
                        + Environment.NewLine + "- "
                        + LocalizationManager.GetString("PublishTab.PdfMaker.TryMoreMemory", "Try doing this on a computer with more memory"));

            }
        }
Ejemplo n.º 8
0
        ///  <summary>
        ///
        ///  </summary>
        /// <param name="pdfPath">this is the path where it already exists, and the path where we leave the transformed version</param>
        /// <param name="incomingPaperSize"></param>
        /// <param name="booketLayoutMethod"></param>
        /// <param name="layoutPagesForRightToLeft"></param>
        private void MakeBooklet(string pdfPath, string incomingPaperSize, PublishModel.BookletLayoutMethod booketLayoutMethod, bool layoutPagesForRightToLeft)
        {
            //TODO: we need to let the user chose the paper size, as they do in PdfDroplet.
            //For now, just assume a size double the original

            PageSize pageSize;
            switch (incomingPaperSize)
            {
                case "A3":
                    pageSize = PageSize.A2;
                    break;
                case "A4":
                    pageSize = PageSize.A3;
                    break;
                case "A5":
                    pageSize = PageSize.A4;
                    break;
                case "A6":
                    pageSize = PageSize.A5;
                    break;
                case "B5":
                    pageSize = PageSize.B4;
                    break;
                case "Letter":
                    pageSize = PageSize.Ledger;
                    break;
                case "HalfLetter":
                    pageSize = PageSize.Letter;
                    break;
                case "QuarterLetter":
                    pageSize = PageSize.Statement;	// ?? Wikipedia says HalfLetter is aka Statement
                    break;
                case "Legal":
                    pageSize = PageSize.Legal;//TODO... what's reasonable?
                    break;
                case "HalfLegal":
                    pageSize = PageSize.Legal;
                    break;
                default:
                    throw new ApplicationException("PdfMaker.MakeBooklet() does not contain a map from " + incomingPaperSize + " to a PdfSharp paper size.");
            }

            using (var incoming = new TempFile())
            {
                RobustFile.Delete(incoming.Path);
                RobustFile.Move(pdfPath, incoming.Path);

                LayoutMethod method;
                switch (booketLayoutMethod)
                {
                    case PublishModel.BookletLayoutMethod.NoBooklet:
                        method = new NullLayoutMethod();
                        break;
                    case PublishModel.BookletLayoutMethod.SideFold:
                        // To keep the GUI simple, we assume that A6 page size for booklets
                        // implies 4up printing on A4 paper.  This feature was requested by
                        // https://jira.sil.org/browse/BL-1059 "A6 booklets should print 4
                        // to an A4 sheet".  The same is done for QuarterLetter booklets
                        // printing on Letter size sheets.
                        if (incomingPaperSize == "A6")
                        {
                            method = new SideFold4UpBookletLayouter();
                            pageSize = PageSize.A4;
                        }
                        else if (incomingPaperSize == "QuarterLetter")
                        {
                            method = new SideFold4UpBookletLayouter();
                            pageSize = PageSize.Letter;
                        }
                        else
                        {
                            method = new SideFoldBookletLayouter();
                        }
                        break;
                    case PublishModel.BookletLayoutMethod.CutAndStack:
                        method = new CutLandscapeLayout();
                        break;
                    case PublishModel.BookletLayoutMethod.Calendar:
                        method = new CalendarLayouter();
                        break;
                    default:
                        throw new ArgumentOutOfRangeException("booketLayoutMethod");
                }
                var paperTarget = new PaperTarget("ZZ"/*we're not displaying this anyhwere, so we don't need to know the name*/, pageSize);
                var pdf = XPdfForm.FromFile(incoming.Path);//REVIEW: this whole giving them the pdf and the file too... I checked once and it wasn't wasting effort...the path was only used with a NullLayout option
                method.Layout(pdf, incoming.Path, pdfPath, paperTarget, layoutPagesForRightToLeft, ShowCropMarks);
            }
        }
Ejemplo n.º 9
0
        public delegate PublishView Factory();        //autofac uses this

        public PublishView(PublishModel model,
                           SelectedTabChangedEvent selectedTabChangedEvent, LocalizationChangedEvent localizationChangedEvent, BookTransfer bookTransferrer, LoginDialog login, NavigationIsolator isolator,
                           PublishToAndroidApi publishApi, PublishEpubApi publishEpubApi, BloomWebSocketServer webSocketServer)
        {
            _bookTransferrer = bookTransferrer;
            _loginDialog     = login;
            _isolator        = isolator;
            _publishApi      = publishApi;
            _publishEpubApi  = publishEpubApi;
            _webSocketServer = webSocketServer;

            InitializeComponent();

            if (this.DesignMode)
            {
                return;
            }

            _model      = model;
            _model.View = this;

            _makePdfBackgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(_makePdfBackgroundWorker_RunWorkerCompleted);
            _pdfViewer.PrintProgress += new System.EventHandler <PdfPrintProgressEventArgs>(OnPrintProgress);

            // BL-625: With mono, if a RadioButton group has its AutoCheck properties set to true, the default RadioButton.OnEnter
            //         event checks to make sure one of the RadioButtons is checked. If none are checked, the one the mouse pointer
            //         is over is checked, causing the CheckChanged event to fire.
            if (SIL.PlatformUtilities.Platform.IsMono)
            {
                SetAutoCheck(false);
            }

            //NB: just triggering off "VisibilityChanged" was unreliable. So now we trigger
            //off the tab itself changing, either to us or away from us.
            selectedTabChangedEvent.Subscribe(c =>
            {
                if (c.To == this)
                {
                    Activate();
                }
                else if (c.To != this)
                {
                    Deactivate();
                }
            });

            //TODO: find a way to call this just once, at the right time:

            //			DeskAnalytics.Track("Publish");

//#if DEBUG
//          var linkLabel = new LinkLabel() {Text = "DEBUG"};
//			linkLabel.Click+=new EventHandler((x,y)=>_model.DebugCurrentPDFLayout());
//          tableLayoutPanel1.Controls.Add(linkLabel);
//#endif
            _menusToolStrip.BackColor = _layoutChoices.BackColor = tableLayoutPanel1.BackColor = Palette.GeneralBackground;
            if (SIL.PlatformUtilities.Platform.IsMono)
            {
                BackgroundColorsForLinux();
            }

            // Adding this renderer prevents a white line from showing up under the components.
            _menusToolStrip.Renderer = new EditingView.FixedToolStripRenderer();

            // As far as I can tell, this is not needed anymore, and its presence,
            // at least in this place in the code, causes errors when running command-line tools
            // like UploadCommand which needs a PublishView but must not have something fully initialized.
            //GeckoPreferences.Default["pdfjs.disabled"] = false;
            SetupLocalization();
            localizationChangedEvent.Subscribe(o =>
            {
                SetupLocalization();
                UpdateLayoutChoiceLabels();
                UpdateSaveButton();
            });

            // Make this extra box available to show when wanted.
            _previewBox         = new PictureBox();
            _previewBox.Visible = false;
            Controls.Add(_previewBox);
            _previewBox.BringToFront();
        }
Ejemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pdfPath">this is the path where it already exists, and the path where we leave the transformed version</param>
        /// <param name="incomingPaperSize"></param>
        /// <param name="booketLayoutMethod"></param>
        private void MakeBooklet(string pdfPath, string incomingPaperSize, PublishModel.BookletLayoutMethod booketLayoutMethod)
        {
            //TODO: we need to let the user chose the paper size, as they do in PdfDroplet.
            //For now, just assume a size double the original

            PageSize pageSize;
            switch (incomingPaperSize)
            {
                case "A3":
                    pageSize = PageSize.A2;
                    break;
                case "A4":
                    pageSize = PageSize.A3;
                    break;
                case "A5":
                    pageSize = PageSize.A4;
                    break;
                case "A6":
                    pageSize = PageSize.A5;
                    break;
                case "B5":
                    pageSize = PageSize.B4;
                    break;
                case "Letter":
                    pageSize = PageSize.Letter;//TODO... what's reasonable?
                    break;
                case "HalfLetter":
                    pageSize = PageSize.Letter;
                    break;
                case "Legal":
                    pageSize = PageSize.Legal;//TODO... what's reasonable?
                    break;
                default:
                    throw new ApplicationException("PdfMaker.MakeBooklet() does not contain a map from " + incomingPaperSize + " to a PdfSharp paper size.");
            }

            using (var incoming = new TempFile())
            {
                File.Delete(incoming.Path);
                File.Move(pdfPath, incoming.Path);

                LayoutMethod method;
                switch(booketLayoutMethod)
                {
                    case PublishModel.BookletLayoutMethod.NoBooklet:
                        method = new NullLayoutMethod();
                        break;
                    case PublishModel.BookletLayoutMethod.SideFold:
                        method = new SideFoldBookletLayouter();
                        break;
                    case PublishModel.BookletLayoutMethod.CutAndStack:
                        method = new CutLandscapeLayout();
                        break;
                    case PublishModel.BookletLayoutMethod.Calendar:
                        method = new CalendarLayouter();
                        break;
                    default:
                        throw new ArgumentOutOfRangeException("booketLayoutMethod");
                }
                var paperTarget = new PaperTarget("ZZ"/*we're not displaying this anyhwere, so we don't need to know the name*/, pageSize);
                var pdf = XPdfForm.FromFile(incoming.Path);//REVIEW: this whole giving them the pdf and the file too... I checked once and it wasn't wasting effort...the path was only used with a NullLayout option
                method.Layout(pdf, incoming.Path, pdfPath, paperTarget, /*TODO: rightToLeft*/ false, ShowCropMarks);
            }
        }
Ejemplo n.º 11
0
        public HtmlDom GetDomForPrinting(PublishModel.BookletPortions bookletPortion, BookCollection currentBookCollection, BookServer bookServer)
        {
            var printingDom = GetBookDomWithStyleSheets("previewMode.css", "origami.css");
            AddCreationTypeAttribute(printingDom);

            if (IsFolio)
            {
                AddChildBookContentsToFolio(printingDom, currentBookCollection, bookServer);
                printingDom.SortStyleSheetLinks();
            }

            //whereas the base is to our embedded server during editing, it's to the file folder
            //when we make a PDF, because we wan the PDF to use the original hi-res versions

            var pathSafeForWkHtml2Pdf = FileUtils.MakePathSafeFromEncodingProblems(FolderPath);
            BookStorage.SetBaseForRelativePaths(printingDom, pathSafeForWkHtml2Pdf);

            switch (bookletPortion)
            {
                case PublishModel.BookletPortions.AllPagesNoBooklet:
                    break;
                case PublishModel.BookletPortions.BookletCover:
                    DeletePages(printingDom.RawDom, p => !p.GetAttribute("class").ToLowerInvariant().Contains("cover"));
                    break;
                 case PublishModel.BookletPortions.BookletPages:
                    DeletePages(printingDom.RawDom, p => p.GetAttribute("class").ToLowerInvariant().Contains("cover"));
                    break;
                 default:
                    throw new ArgumentOutOfRangeException("bookletPortion");
            }
            AddCoverColor(printingDom, Color.White);
            AddPreviewJavascript(printingDom);
            return printingDom;
        }
Ejemplo n.º 12
0
 public void SetDisplayMode(PublishModel.DisplayModes displayMode)
 {
     switch (displayMode)
     {
         case PublishModel.DisplayModes.NoBook:
             _printButton.Enabled = _saveButton.Enabled = false;
             Cursor = Cursors.Default;
             _workingIndicator.Visible = false;
             break;
         case PublishModel.DisplayModes.Working:
             _printButton.Enabled = _saveButton.Enabled = false;
             _workingIndicator.Cursor = Cursors.WaitCursor;
             Cursor = Cursors.WaitCursor;
             _workingIndicator.Visible = true;
             break;
         case PublishModel.DisplayModes.ShowPdf:
             if (File.Exists(_model.PdfFilePath))
             {
                 _saveButton.Enabled = true;
                 _workingIndicator.Visible = false;
                 Cursor = Cursors.Default;
                 _printButton.Enabled = _adobeReaderControl.ShowPdf(_model.PdfFilePath);
             }
             break;
     }
 }
Ejemplo n.º 13
0
		/// <summary>
		/// Runs PdfMaker.MakePdf() with the desired arguments.  Note that the implementation (as of March 2015)
		/// uses an external program to generate the PDF from the HTML file, so it doesn't need to be run on
		/// a background thread.  The process includes a (possibly overgenerous) timeout, so we don't try to
		/// impose one here.
		/// </summary>
		/// <remarks>
		/// Running this on a background thread would be okay, except that on Linux, the interaction between
		/// Mono and NUnit and the Bloom method result in the BackgroundWorker.RunWorkerCompleted event
		/// never being fired if tests other than those in this file are run along with these tests.  This is
		/// almost certainly an obscure bug in Mono.  Running the method directly as we do here sidesteps that
		/// problem.  (See https://jira.sil.org/browse/BL-831.)
		/// </remarks>
		void RunMakePdf(PdfMaker maker, string input, string output, string paperSize, bool landscape, bool saveMemoryMode, bool rightToLeft,
			PublishModel.BookletLayoutMethod layout, PublishModel.BookletPortions portion)
		{
			// Passing in a DoWorkEventArgs object prevents a possible exception being thrown.  Which may not
			// really matter much in the test situation since NUnit would catch the exception.  But I'd rather
			// have a nice test failure message than an unexpected exception caught message.
			var eventArgs = new DoWorkEventArgs(null);
			maker.MakePdf(input, output, paperSize, landscape, saveMemoryMode, rightToLeft, layout, portion, null, eventArgs, null);
		}
Ejemplo n.º 14
0
        private bool _publishWithoutAudio = false; // True if the user has said to go ahead without audio

        #endregion Fields

        #region Constructors

        //autofac uses this
        public PublishView(PublishModel model,
			SelectedTabChangedEvent selectedTabChangedEvent, LocalizationChangedEvent localizationChangedEvent, BookTransfer bookTransferrer, LoginDialog login, NavigationIsolator isolator)
        {
            _bookTransferrer = bookTransferrer;
            _loginDialog = login;
            _isolator = isolator;

            InitializeComponent();

            if (this.DesignMode)
                return;

            _model = model;
            _model.View = this;

            _makePdfBackgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(_makePdfBackgroundWorker_RunWorkerCompleted);
            _pdfViewer.PrintProgress += new System.EventHandler<PdfPrintProgressEventArgs>(OnPrintProgress);

            // BL-625: With mono, if a RadioButton group has its AutoCheck properties set to true, the default RadioButton.OnEnter
            //         event checks to make sure one of the RadioButtons is checked. If none are checked, the one the mouse pointer
            //         is over is checked, causing the CheckChanged event to fire.
            if (SIL.PlatformUtilities.Platform.IsMono)
                SetAutoCheck(false);

            //NB: just triggering off "VisibilityChanged" was unreliable. So now we trigger
            //off the tab itself changing, either to us or away from us.
            selectedTabChangedEvent.Subscribe(c=>
                                                {
                                                    if (c.To == this)
                                                    {
                                                        Activate();
                                                    }
                                                    else if (c.To!=this && IsMakingPdf)
                                                        _makePdfBackgroundWorker.CancelAsync();
                                                });

            //TODO: find a way to call this just once, at the right time:

            //			DeskAnalytics.Track("Publish");

            //#if DEBUG
            //        	var linkLabel = new LinkLabel() {Text = "DEBUG"};
            //			linkLabel.Click+=new EventHandler((x,y)=>_model.DebugCurrentPDFLayout());
            //        	tableLayoutPanel1.Controls.Add(linkLabel);
            //#endif
            if (SIL.PlatformUtilities.Platform.IsMono)
            {
                BackgroundColorsForLinux();
            }

            // Adding this renderer prevents a white line from showing up under the components.
            _menusToolStrip.Renderer = new EditingView.FixedToolStripRenderer();

            GeckoPreferences.Default["pdfjs.disabled"] = false;
            SetupLocalization();
            localizationChangedEvent.Subscribe(o =>
            {
                SetupLocalization();
                UpdateLayoutChoiceLabels();
                UpdateSaveButton();
            });

            // Make this extra box available to show when wanted.
            _previewBox = new PictureBox();
            _previewBox.Visible = false;
            Controls.Add(_previewBox);
            _previewBox.BringToFront();
        }
Ejemplo n.º 15
0
        public void SetDisplayMode(PublishModel.DisplayModes displayMode)
        {
            if (displayMode != PublishModel.DisplayModes.Upload && _publishControl != null)
            {
                Controls.Remove(_publishControl);
                _publishControl = null;
            }
            if (displayMode != PublishModel.DisplayModes.EPUB && _epubPreviewControl != null && Controls.Contains(_epubPreviewControl))
            {
                Controls.Remove(_epubPreviewControl);
            }
            if (displayMode != PublishModel.DisplayModes.Upload && displayMode != PublishModel.DisplayModes.EPUB)
                _pdfViewer.Visible = true;
            switch (displayMode)
            {
                case PublishModel.DisplayModes.WaitForUserToChooseSomething:
                    _printButton.Enabled = _saveButton.Enabled = false;
                    Cursor = Cursors.Default;
                    _workingIndicator.Visible = false;
                    _pdfViewer.Visible = false;
                    break;
                case PublishModel.DisplayModes.Working:
                    _printButton.Enabled = _saveButton.Enabled = false;
                    _workingIndicator.Cursor = Cursors.WaitCursor;
                    Cursor = Cursors.WaitCursor;
                    _workingIndicator.Visible = true;
                    break;
                case PublishModel.DisplayModes.ShowPdf:
                    if (RobustFile.Exists(_model.PdfFilePath))
                    {
                        _pdfViewer.Visible = true;
                        _workingIndicator.Visible = false;
                        Cursor = Cursors.Default;
                        _saveButton.Enabled = true;
                        _printButton.Enabled = _pdfViewer.ShowPdf(_model.PdfFilePath);
                    }
                    break;
                case PublishModel.DisplayModes.Printing:
                    _simpleAllPagesRadio.Enabled = false;
                    _bookletCoverRadio.Enabled = false;
                    _bookletBodyRadio.Enabled = false;
                    _printButton.Enabled = _saveButton.Enabled = false;
                    _workingIndicator.Cursor = Cursors.WaitCursor;
                    Cursor = Cursors.WaitCursor;
                    _workingIndicator.Visible = true;
                    break;
                case PublishModel.DisplayModes.ResumeAfterPrint:
                    _simpleAllPagesRadio.Enabled = true;
                    _pdfViewer.Visible = true;
                    _workingIndicator.Visible = false;
                    Cursor = Cursors.Default;
                    _saveButton.Enabled = true;
                    _printButton.Enabled = true;
                    break;
                case PublishModel.DisplayModes.Upload:
                {
                    _workingIndicator.Visible = false; // If we haven't finished creating the PDF, we will indicate that in the progress window.
                    _saveButton.Enabled = _printButton.Enabled = false; // Can't print or save in this mode...wouldn't be obvious what would be saved.
                    _pdfViewer.Visible = false;
                    Cursor = Cursors.Default;

                    if (_publishControl == null)
                    {
                        SetupPublishControl();
                    }

                    break;
                }
                case PublishModel.DisplayModes.EPUB:
                {
                    // We may reuse this for the process of generating the ePUB staging files. For now, skip it.
                    _workingIndicator.Visible = false;
                    _printButton.Enabled = false; // don't know how to print an ePUB
                    _saveButton.Enabled = true; // lets us save it to an actual ePUB
                    _pdfViewer.Visible = false;
                    Cursor = Cursors.Default;

                    SetupEpubControl();

                    break;
                }
            }
            UpdateSaveButton();
        }
Ejemplo n.º 16
0
        public XmlDocument GetDomForPrinting(PublishModel.BookletPortions bookletPortion, BookCollection currentBookCollection, BookServer bookServer)
        {
            var printingDom = GetBookDomWithStyleSheets("previewMode.css");
            //dom.LoadXml(OurHtmlDom.OuterXml);

            if (IsFolio)
            {
                AddChildBookContentsToFolio(printingDom, currentBookCollection, bookServer);
            }

            //whereas the base is to our embedded server during editing, it's to the file folder
            //when we make a PDF, because we wan the PDF to use the original hi-res versions
            BookStorage.SetBaseForRelativePaths(printingDom, FolderPath, false);

            switch (bookletPortion)
            {
                case PublishModel.BookletPortions.AllPagesNoBooklet:
                    break;
                case PublishModel.BookletPortions.BookletCover:
                    HidePages(printingDom.RawDom, p=>!p.GetAttribute("class").ToLower().Contains("cover"));
                    break;
                 case PublishModel.BookletPortions.BookletPages:
                    HidePages(printingDom.RawDom, p => p.GetAttribute("class").ToLower().Contains("cover"));
                    break;
                 default:
                    throw new ArgumentOutOfRangeException("bookletPortion");
            }
            AddCoverColor(printingDom, Color.White);
            AddPreviewJScript(printingDom);
            return printingDom.RawDom;
        }