def testBaseCommon_MakeFileNameSafe(): """Test the fuzzyTime function. """ assert makeFileNameSafe(" aaaa ") == "aaaa" assert makeFileNameSafe("aaaa,bbbb") == "aaaabbbb" assert makeFileNameSafe("aaaa\tbbbb") == "aaaabbbb" assert makeFileNameSafe("aaaa bbbb") == "aaaa bbbb"
def _doBrowse(self): """Select a project folder. """ lastPath = self.mainConf.lastPath if not os.path.isdir(lastPath): lastPath = "" dlgOpt = QFileDialog.Options() dlgOpt |= QFileDialog.ShowDirsOnly dlgOpt |= QFileDialog.DontUseNativeDialog projDir = QFileDialog.getExistingDirectory( self, "Select Project Folder", lastPath, options=dlgOpt ) if projDir: projName = self.field("projName") if projName is not None: fullDir = os.path.join(os.path.abspath(projDir), makeFileNameSafe(projName)) self.projPath.setText(fullDir) else: self.projPath.setText("") return
def _saveDocument(self, theFormat): """Save the document to various formats. """ byteFmt = QByteArray() fileExt = "" textFmt = "" outTool = "" # Create the settings if theFormat == self.FMT_ODT: byteFmt.append("odf") fileExt = "odt" textFmt = "Open Document" outTool = "Qt" elif theFormat == self.FMT_PDF: fileExt = "pdf" textFmt = "PDF" outTool = "QtPrint" elif theFormat == self.FMT_HTM: fileExt = "htm" textFmt = "Plain HTML" outTool = "NW" elif theFormat == self.FMT_MD: byteFmt.append("markdown") fileExt = "md" textFmt = "Markdown" outTool = "Qt" elif theFormat == self.FMT_NWD: fileExt = "nwd" textFmt = "%s Markdown" % nw.__package__ outTool = "NW" elif theFormat == self.FMT_TXT: byteFmt.append("plaintext") fileExt = "txt" textFmt = "Plain Text" outTool = "Qt" elif theFormat == self.FMT_JSON_H: fileExt = "json" textFmt = "JSON + %s HTML" % nw.__package__ outTool = "NW" elif theFormat == self.FMT_JSON_M: fileExt = "json" textFmt = "JSON + %s Markdown" % nw.__package__ outTool = "NW" else: return False # Generate the file name if fileExt: cleanName = makeFileNameSafe(self.theProject.projName) fileName = "%s.%s" % (cleanName, fileExt) saveDir = self.mainConf.lastPath savePath = os.path.join(saveDir, fileName) if not os.path.isdir(saveDir): saveDir = self.mainConf.homePath if self.mainConf.showGUI: dlgOpt = QFileDialog.Options() dlgOpt |= QFileDialog.DontUseNativeDialog savePath, _ = QFileDialog.getSaveFileName(self, "Save Document As", savePath, options=dlgOpt) if not savePath: return False self.mainConf.setLastPath(savePath) else: return False # Do the actual writing wSuccess = False errMsg = "" if outTool == "Qt": docWriter = QTextDocumentWriter() docWriter.setFileName(savePath) docWriter.setFormat(byteFmt) wSuccess = docWriter.write(self.docView.qDocument) elif outTool == "NW": try: with open(savePath, mode="w", encoding="utf8") as outFile: if theFormat == self.FMT_HTM: # Write novelWriter HTML data theStyle = self.htmlStyle.copy() theStyle.append( r"article {width: 800px; margin: 40px auto;}") bodyText = "".join(self.htmlText) bodyText = bodyText.replace("\t", "	") theHtml = ("<!DOCTYPE html>\n" "<html>\n" "<head>\n" "<meta charset='utf-8'>\n" "<title>{projTitle:s}</title>\n" "</head>\n" "<style>\n" "{htmlStyle:s}\n" "</style>\n" "<body>\n" "<article>\n" "{bodyText:s}\n" "</article>\n" "</body>\n" "</html>\n").format( projTitle=self.theProject.projName, htmlStyle="\n".join(theStyle), bodyText=bodyText, ) outFile.write(theHtml) elif theFormat == self.FMT_NWD: # Write novelWriter markdown data for aLine in self.nwdText: outFile.write(aLine) elif theFormat == self.FMT_JSON_H or theFormat == self.FMT_JSON_M: jsonData = { "meta": { "workingTitle": self.theProject.projName, "novelTitle": self.theProject.bookTitle, "authors": self.theProject.bookAuthors, "buildTime": self.buildTime, } } if theFormat == self.FMT_JSON_H: theBody = [] for htmlPage in self.htmlText: theBody.append( htmlPage.rstrip("\n").split("\n")) jsonData["text"] = { "css": self.htmlStyle, "html": theBody, } elif theFormat == self.FMT_JSON_M: theBody = [] for nwdPage in self.nwdText: theBody.append(nwdPage.split("\n")) jsonData["text"] = { "nwd": theBody, } outFile.write(json.dumps(jsonData, indent=2)) wSuccess = True except Exception as e: errMsg = str(e) elif outTool == "QtPrint" and theFormat == 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.qDocument.print(thePrinter) wSuccess = True except Exception as e: errMsg - str(e) else: errMsg = "Unknown format" # Report to user if self.mainConf.showGUI: if wSuccess: self.theParent.makeAlert( "%s file successfully written to:<br> %s" % (textFmt, savePath), nwAlert.INFO) else: self.theParent.makeAlert( "Failed to write %s file. %s" % (textFmt, errMsg), nwAlert.ERROR) return wSuccess
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 # ================== if fileExt: cleanName = makeFileNameSafe(self.theProject.projName) fileName = "%s.%s" % (cleanName, fileExt) saveDir = self.mainConf.lastPath savePath = os.path.join(saveDir, fileName) if not os.path.isdir(saveDir): saveDir = self.mainConf.homePath savePath, _ = QFileDialog.getSaveFileName( self, self.tr("Save Document As"), savePath) if not savePath: return False self.mainConf.setLastPath(savePath) else: return False # Build and Write # =============== errMsg = "" wSuccess = False if theFmt == self.FMT_ODT: makeOdt = ToOdt(self.theProject, self.theParent, isFlat=False) self._doBuild(makeOdt) try: makeOdt.saveOpenDocText(savePath) wSuccess = True except Exception as e: errMsg = str(e) elif theFmt == self.FMT_FODT: makeOdt = ToOdt(self.theProject, self.theParent, isFlat=True) self._doBuild(makeOdt) try: makeOdt.saveFlatXML(savePath) wSuccess = True except Exception as e: errMsg = str(e) elif theFmt == self.FMT_HTM: makeHtml = ToHtml(self.theProject, self.theParent) self._doBuild(makeHtml) if replaceTabs: makeHtml.replaceTabs() try: makeHtml.saveHTML5(savePath) wSuccess = True except Exception as e: errMsg = str(e) elif theFmt == self.FMT_NWD: makeNwd = ToMarkdown(self.theProject, self.theParent) makeNwd.setKeepMarkdown(True) self._doBuild(makeNwd, doConvert=False) if replaceTabs: makeNwd.replaceTabs(spaceChar=" ") try: makeNwd.saveRawMarkdown(savePath) wSuccess = True except Exception as e: errMsg = str(e) elif theFmt in (self.FMT_MD, self.FMT_GH): makeMd = ToMarkdown(self.theProject, self.theParent) 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 e: errMsg = str(e) 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.theParent) 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, self.theParent) 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="utf8") as outFile: outFile.write(json.dumps(jsonData, indent=2)) wSuccess = True except Exception as e: errMsg = str(e) 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.qDocument.print(thePrinter) wSuccess = True except Exception as e: errMsg - str(e) else: errMsg = self.tr("Unknown format") # Report to user if wSuccess: self.theParent.makeAlert( "%s<br>%s" % (self.tr("{0} file successfully written to:").format(textFmt), savePath), nwAlert.INFO) else: self.theParent.makeAlert( self.tr("Failed to write {0} file. {1}").format( textFmt, errMsg), nwAlert.ERROR) return wSuccess