예제 #1
0
파일: build.py 프로젝트: Jiaogh/novelWriter
    def _buildPreview(self):
        """Build a preview of the project in the document viewer.
        """
        # Get Settings
        fmtTitle = self.fmtTitle.text().strip()
        fmtChapter = self.fmtChapter.text().strip()
        fmtUnnumbered = self.fmtUnnumbered.text().strip()
        fmtScene = self.fmtScene.text().strip()
        fmtSection = self.fmtSection.text().strip()
        justifyText = self.justifyText.isChecked()
        noStyling = self.noStyling.isChecked()
        textFont = self.textFont.text()
        textSize = self.textSize.value()
        incSynopsis = self.includeSynopsis.isChecked()
        incComments = self.includeComments.isChecked()
        incKeywords = self.includeKeywords.isChecked()
        novelFiles = self.novelFiles.isChecked()
        noteFiles = self.noteFiles.isChecked()
        ignoreFlag = self.ignoreFlag.isChecked()
        includeBody = self.includeBody.isChecked()
        replaceTabs = self.replaceTabs.isChecked()

        makeHtml = ToHtml(self.theProject, self.theParent)
        makeHtml.setTitleFormat(fmtTitle)
        makeHtml.setChapterFormat(fmtChapter)
        makeHtml.setUnNumberedFormat(fmtUnnumbered)
        makeHtml.setSceneFormat(fmtScene, fmtScene == "")
        makeHtml.setSectionFormat(fmtSection, fmtSection == "")
        makeHtml.setBodyText(includeBody)
        makeHtml.setSynopsis(incSynopsis)
        makeHtml.setComments(incComments)
        makeHtml.setKeywords(incKeywords)
        makeHtml.setJustify(justifyText)
        makeHtml.setStyles(not noStyling)

        # Make sure the tree order is correct
        self.theParent.treeView.flushTreeOrder()

        self.buildProgress.setMaximum(len(self.theProject.projTree))
        self.buildProgress.setValue(0)

        tStart = int(time())

        self.htmlText = []
        self.htmlStyle = []
        self.nwdText = []

        htmlSize = 0

        for nItt, tItem in enumerate(self.theProject.projTree):

            noteRoot = noteFiles
            noteRoot &= tItem.itemType == nwItemType.ROOT
            noteRoot &= tItem.itemClass != nwItemClass.NOVEL
            noteRoot &= tItem.itemClass != nwItemClass.ARCHIVE

            try:
                if noteRoot:
                    # Add headers for root folders of notes
                    makeHtml.addRootHeading(tItem.itemHandle)
                    makeHtml.doConvert()
                    self.htmlText.append(makeHtml.getResult())
                    self.nwdText.append(makeHtml.getFilteredMarkdown())
                    htmlSize += makeHtml.getResultSize()

                elif self._checkInclude(tItem, noteFiles, novelFiles,
                                        ignoreFlag):
                    makeHtml.setText(tItem.itemHandle)
                    makeHtml.doAutoReplace()
                    makeHtml.tokenizeText()
                    makeHtml.doHeaders()
                    makeHtml.doConvert()
                    makeHtml.doPostProcessing()
                    self.htmlText.append(makeHtml.getResult())
                    self.nwdText.append(makeHtml.getFilteredMarkdown())
                    htmlSize += makeHtml.getResultSize()

            except Exception as e:
                logger.error("Failed to generate html of document '%s'" %
                             tItem.itemHandle)
                logger.error(str(e))
                self.docView.setText(
                    ("Failed to generate preview. "
                     "Document with title '%s' could not be parsed.") %
                    tItem.itemName)
                return False

            # Update progress bar, also for skipped items
            self.buildProgress.setValue(nItt + 1)

        if makeHtml.errData:
            self.theParent.makeAlert(
                ("There were problems when building the project:"
                 "<br>-&nbsp;%s") % "<br>-&nbsp;".join(makeHtml.errData),
                nwAlert.ERROR)

        if replaceTabs:
            htmlText = []
            eightSpace = "&nbsp;" * 8
            for aLine in self.htmlText:
                htmlText.append(aLine.replace("\t", eightSpace))
            self.htmlText = htmlText

            nwdText = []
            for aLine in self.nwdText:
                nwdText.append(aLine.replace("\t", "        "))
            self.nwdText = nwdText

        tEnd = int(time())
        logger.debug("Built project in %.3f ms" % (1000 * (tEnd - tStart)))
        self.htmlStyle = makeHtml.getStyleSheet()
        self.buildTime = tEnd

        # Load the preview document with the html data
        self.docView.setTextFont(textFont, textSize)
        self.docView.setJustify(justifyText)
        if noStyling:
            self.docView.clearStyleSheet()
        else:
            self.docView.setStyleSheet(self.htmlStyle)

        if htmlSize < nwConst.maxBuildSize:
            self.docView.setContent(self.htmlText, self.buildTime)
            self._enableQtSave(True)
        else:
            self.docView.setText(
                "Failed to generate preview. The result is too big.")
            self._enableQtSave(False)

        self._saveCache()

        return
예제 #2
0
    def loadText(self, tHandle, updateHistory=True):
        """Load text into the viewer from an item handle.
        """
        tItem = self.theProject.projTree[tHandle]
        if tItem is None:
            logger.warning("Item not found")
            return False

        if tItem.itemType != nwItemType.FILE:
            return False

        logger.debug("Generating preview for item %s" % tHandle)
        qApp.setOverrideCursor(QCursor(Qt.WaitCursor))

        sPos = self.verticalScrollBar().value()
        aDoc = ToHtml(self.theProject, self.theParent)
        aDoc.setPreview(True, self.mainConf.viewComments,
                        self.mainConf.viewSynopsis)
        aDoc.setLinkHeaders(True)

        # Be extra careful here to prevent crashes when first opening a
        # project as a crash here leaves no way of recovering.
        # See issue #298
        try:
            aDoc.setText(tHandle)
            aDoc.doAutoReplace()
            aDoc.tokenizeText()
            aDoc.doConvert()
            aDoc.doPostProcessing()
        except Exception as e:
            logger.error(
                "Failed to generate preview for document with handle '%s'" %
                tHandle)
            logger.error(str(e))
            self.setText("An error occurred while generating the preview.")
            return False

        # Refresh the tab stops
        if self.mainConf.verQtValue >= 51000:
            self.setTabStopDistance(self.mainConf.getTabWidth())
        else:
            self.setTabStopWidth(self.mainConf.getTabWidth())

        # Must be before setHtml
        if updateHistory:
            self.docHistory.append(tHandle)

        self.setHtml(aDoc.theResult.replace("\t", "!!tab!!"))
        self.setDocumentTitle(tHandle)

        # Loop through the text and put back in the tabs. Tabs are removed by
        # the setHtml function, so the ToHtml class puts in a placeholder.
        while self.find("!!tab!!"):
            theCursor = self.textCursor()
            theCursor.insertText("\t")

        if self.theHandle == tHandle:
            self.verticalScrollBar().setValue(sPos)
        self.theHandle = tHandle
        self.theProject.setLastViewed(tHandle)
        self.docHeader.setTitleFromHandle(self.theHandle)
        self.updateDocMargins()

        # Make sure the main GUI knows we changed the content
        self.theParent.viewMeta.refreshReferences(tHandle)

        # Since we change the content while it may still be rendering, we mark
        # the document dirty again to make sure it's re-rendered properly.
        self.redrawText()
        qApp.restoreOverrideCursor()

        return True