Пример #1
0
def testCoreToOdt_SaveFull(mockGUI, fncDir, outDir, refDir):
    """Test the document save functions.
    """
    theProject = NWProject(mockGUI)

    theDoc = ToOdt(theProject, isFlat=False)
    theDoc._isNovel = True

    theDoc._theText = ("## Chapter One\n\n"
                       "Text\n\n"
                       "## Chapter Two\n\n"
                       "Text\n\n")
    theDoc.tokenizeText()
    theDoc.initDocument()
    theDoc.doConvert()
    theDoc.closeDocument()

    fullFile = os.path.join(fncDir, "document.odt")

    theDoc.saveOpenDocText(fullFile)
    assert os.path.isfile(fullFile)
    assert zipfile.is_zipfile(fullFile)

    maniFile = os.path.join(outDir, "coreToOdt_SaveFull_manifest.xml")
    settFile = os.path.join(outDir, "coreToOdt_SaveFull_settings.xml")
    contFile = os.path.join(outDir, "coreToOdt_SaveFull_content.xml")
    metaFile = os.path.join(outDir, "coreToOdt_SaveFull_meta.xml")
    stylFile = os.path.join(outDir, "coreToOdt_SaveFull_styles.xml")

    maniComp = os.path.join(refDir, "coreToOdt_SaveFull_manifest.xml")
    settComp = os.path.join(refDir, "coreToOdt_SaveFull_settings.xml")
    contComp = os.path.join(refDir, "coreToOdt_SaveFull_content.xml")
    metaComp = os.path.join(refDir, "coreToOdt_SaveFull_meta.xml")
    stylComp = os.path.join(refDir, "coreToOdt_SaveFull_styles.xml")

    extaxtTo = os.path.join(outDir, "coreToOdt_SaveFull")

    with zipfile.ZipFile(fullFile, mode="r") as theZip:
        theZip.extract("META-INF/manifest.xml", extaxtTo)
        theZip.extract("settings.xml", extaxtTo)
        theZip.extract("content.xml", extaxtTo)
        theZip.extract("meta.xml", extaxtTo)
        theZip.extract("styles.xml", extaxtTo)

    maniOut = os.path.join(outDir, "coreToOdt_SaveFull", "META-INF",
                           "manifest.xml")
    settOut = os.path.join(outDir, "coreToOdt_SaveFull", "settings.xml")
    contOut = os.path.join(outDir, "coreToOdt_SaveFull", "content.xml")
    metaOut = os.path.join(outDir, "coreToOdt_SaveFull", "meta.xml")
    stylOut = os.path.join(outDir, "coreToOdt_SaveFull", "styles.xml")

    def prettifyXml(inFile, outFile):
        with open(outFile, mode="wb") as fileStream:
            fileStream.write(
                etree.tostring(etree.parse(inFile),
                               pretty_print=True,
                               encoding="utf-8",
                               xml_declaration=True))

    prettifyXml(maniOut, maniFile)
    prettifyXml(settOut, settFile)
    prettifyXml(contOut, contFile)
    prettifyXml(metaOut, metaFile)
    prettifyXml(stylOut, stylFile)

    assert cmpFiles(maniFile, maniComp)
    assert cmpFiles(settFile, settComp)
    assert cmpFiles(contFile, contComp)
    assert cmpFiles(metaFile, metaComp, [4, 5])
    assert cmpFiles(stylFile, stylComp)
Пример #2
0
    def _saveDocument(self, theFmt):
        """Save the document to various formats.
        """
        replaceTabs = self.replaceTabs.isChecked()

        fileExt = ""
        textFmt = ""

        # Settings
        # ========

        if theFmt == self.FMT_ODT:
            fileExt = "odt"
            textFmt = self.tr("Open Document")

        elif theFmt == self.FMT_FODT:
            fileExt = "fodt"
            textFmt = self.tr("Flat Open Document")

        elif theFmt == self.FMT_HTM:
            fileExt = "htm"
            textFmt = self.tr("Plain HTML")

        elif theFmt == self.FMT_NWD:
            fileExt = "nwd"
            textFmt = self.tr("novelWriter Markdown")

        elif theFmt == self.FMT_MD:
            fileExt = "md"
            textFmt = self.tr("Standard Markdown")

        elif theFmt == self.FMT_GH:
            fileExt = "md"
            textFmt = self.tr("GitHub Markdown")

        elif theFmt == self.FMT_JSON_H:
            fileExt = "json"
            textFmt = self.tr("JSON + novelWriter HTML")

        elif theFmt == self.FMT_JSON_M:
            fileExt = "json"
            textFmt = self.tr("JSON + novelWriter Markdown")

        elif theFmt == self.FMT_PDF:
            fileExt = "pdf"
            textFmt = self.tr("PDF")

        else:
            return False

        # Generate File Name
        # ==================

        cleanName = makeFileNameSafe(self.theProject.projName)
        fileName = "%s.%s" % (cleanName, fileExt)
        saveDir = self.mainConf.lastPath
        if not os.path.isdir(saveDir):
            saveDir = os.path.expanduser("~")

        savePath = os.path.join(saveDir, fileName)
        savePath, _ = QFileDialog.getSaveFileName(
            self, self.tr("Save Document As"), savePath
        )
        if not savePath:
            return False

        self.mainConf.setLastPath(savePath)

        # Build and Write
        # ===============

        errMsg = ""
        wSuccess = False

        if theFmt == self.FMT_ODT:
            makeOdt = ToOdt(self.theProject, isFlat=False)
            self._doBuild(makeOdt)
            try:
                makeOdt.saveOpenDocText(savePath)
                wSuccess = True
            except Exception as exc:
                errMsg = formatException(exc)

        elif theFmt == self.FMT_FODT:
            makeOdt = ToOdt(self.theProject, isFlat=True)
            self._doBuild(makeOdt)
            try:
                makeOdt.saveFlatXML(savePath)
                wSuccess = True
            except Exception as exc:
                errMsg = formatException(exc)

        elif theFmt == self.FMT_HTM:
            makeHtml = ToHtml(self.theProject)
            self._doBuild(makeHtml)
            if replaceTabs:
                makeHtml.replaceTabs()

            try:
                makeHtml.saveHTML5(savePath)
                wSuccess = True
            except Exception as exc:
                errMsg = formatException(exc)

        elif theFmt == self.FMT_NWD:
            makeNwd = ToMarkdown(self.theProject)
            makeNwd.setKeepMarkdown(True)
            self._doBuild(makeNwd, doConvert=False)
            if replaceTabs:
                makeNwd.replaceTabs(spaceChar=" ")

            try:
                makeNwd.saveRawMarkdown(savePath)
                wSuccess = True
            except Exception as exc:
                errMsg = formatException(exc)

        elif theFmt in (self.FMT_MD, self.FMT_GH):
            makeMd = ToMarkdown(self.theProject)
            if theFmt == self.FMT_GH:
                makeMd.setGitHubMarkdown()
            else:
                makeMd.setStandardMarkdown()

            self._doBuild(makeMd)
            if replaceTabs:
                makeMd.replaceTabs(nSpaces=4, spaceChar=" ")

            try:
                makeMd.saveMarkdown(savePath)
                wSuccess = True
            except Exception as exc:
                errMsg = formatException(exc)

        elif theFmt == self.FMT_JSON_H or theFmt == self.FMT_JSON_M:
            jsonData = {
                "meta": {
                    "workingTitle": self.theProject.projName,
                    "novelTitle": self.theProject.bookTitle,
                    "authors": self.theProject.bookAuthors,
                    "buildTime": self.buildTime,
                }
            }

            if theFmt == self.FMT_JSON_H:
                makeHtml = ToHtml(self.theProject)
                self._doBuild(makeHtml)
                if replaceTabs:
                    makeHtml.replaceTabs()

                theBody = []
                for htmlPage in makeHtml.fullHTML:
                    theBody.append(htmlPage.rstrip("\n").split("\n"))
                jsonData["text"] = {
                    "css": self.htmlStyle,
                    "html": theBody,
                }

            elif theFmt == self.FMT_JSON_M:
                makeMd = ToHtml(self.theProject)
                makeMd.setKeepMarkdown(True)
                self._doBuild(makeMd, doConvert=False)
                if replaceTabs:
                    makeMd.replaceTabs(spaceChar=" ")

                theBody = []
                for nwdPage in makeMd.theMarkdown:
                    theBody.append(nwdPage.split("\n"))
                jsonData["text"] = {
                    "nwd": theBody,
                }

            try:
                with open(savePath, mode="w", encoding="utf-8") as outFile:
                    outFile.write(json.dumps(jsonData, indent=2))
                    wSuccess = True
            except Exception as exc:
                errMsg = formatException(exc)

        elif theFmt == self.FMT_PDF:
            try:
                thePrinter = QPrinter()
                thePrinter.setOutputFormat(QPrinter.PdfFormat)
                thePrinter.setOrientation(QPrinter.Portrait)
                thePrinter.setDuplex(QPrinter.DuplexLongSide)
                thePrinter.setFontEmbeddingEnabled(True)
                thePrinter.setColorMode(QPrinter.Color)
                thePrinter.setOutputFileName(savePath)
                self.docView.document().print(thePrinter)
                wSuccess = True

            except Exception as exc:
                errMsg = formatException(exc)

        else:
            # If the if statements above and here match, it should not
            # be possible to reach this else statement.
            return False  # pragma: no cover

        # Report to User
        # ==============

        if wSuccess:
            self.mainGui.makeAlert([
                self.tr("{0} file successfully written to:").format(textFmt), savePath
            ], nwAlert.INFO)
        else:
            self.mainGui.makeAlert(self.tr(
                "Failed to write {0} file. {1}"
            ).format(textFmt, errMsg), nwAlert.ERROR)

        return wSuccess