Rename open and save document to read and write in NWDoc

This commit is contained in:
Veronica K. B. Olsen
2021-04-25 17:10:12 +02:00
parent 1e48c6dcfe
commit d473615ccf
11 changed files with 67 additions and 59 deletions
+4 -4
View File
@@ -68,8 +68,8 @@ class NWDoc():
self._docMeta = {} self._docMeta = {}
return return
def openDocument(self, tHandle, showStatus=True, isOrphan=False): def readDocument(self, tHandle, showStatus=True, isOrphan=False):
"""Open a document from handle, capturing potential file system """Read a document from handle, capturing potential file system
errors and parse meta data. If the document doesn't exist on errors and parse meta data. If the document doesn't exist on
disk, return an empty string. If something went wrong, return disk, return an empty string. If something went wrong, return
None. None.
@@ -134,8 +134,8 @@ class NWDoc():
return theText return theText
def saveDocument(self, docText): def writeDocument(self, docText):
"""Save the document. The file is saved via a temp file in case """Write the document. The file is saved via a temp file in case
of save failure. Returns True if successful, False if not. of save failure. Returns True if successful, False if not.
""" """
if self._docHandle is None: if self._docHandle is None:
+1 -1
View File
@@ -117,7 +117,7 @@ class NWIndex():
return False return False
theDoc = NWDoc(self.theProject, self.theParent) theDoc = NWDoc(self.theProject, self.theParent)
theText = theDoc.openDocument(tHandle, showStatus=False) theText = theDoc.readDocument(tHandle, showStatus=False)
if theText: if theText:
self.scanText(tHandle, theText) self.scanText(tHandle, theText)
+15 -15
View File
@@ -284,16 +284,16 @@ class NWProject():
self.projTree.setFileItemLayout(xHandle[5], nwItemLayout.TITLE) self.projTree.setFileItemLayout(xHandle[5], nwItemLayout.TITLE)
self.projTree.setFileItemLayout(xHandle[7], nwItemLayout.CHAPTER) self.projTree.setFileItemLayout(xHandle[7], nwItemLayout.CHAPTER)
aDoc.openDocument(xHandle[5], showStatus=False) aDoc.readDocument(xHandle[5], showStatus=False)
aDoc.saveDocument(titlePage) aDoc.writeDocument(titlePage)
aDoc.clearDocument() aDoc.clearDocument()
aDoc.openDocument(xHandle[7], showStatus=False) aDoc.readDocument(xHandle[7], showStatus=False)
aDoc.saveDocument("## %s\n\n" % self.tr("New Chapter")) aDoc.writeDocument("## %s\n\n" % self.tr("New Chapter"))
aDoc.clearDocument() aDoc.clearDocument()
aDoc.openDocument(xHandle[8], showStatus=False) aDoc.readDocument(xHandle[8], showStatus=False)
aDoc.saveDocument("### %s\n\n" % self.tr("New Scene")) aDoc.writeDocument("### %s\n\n" % self.tr("New Scene"))
aDoc.clearDocument() aDoc.clearDocument()
elif popCustom: elif popCustom:
@@ -311,8 +311,8 @@ class NWProject():
tHandle = self.newFile(self.tr("Title Page"), nwItemClass.NOVEL, nHandle) tHandle = self.newFile(self.tr("Title Page"), nwItemClass.NOVEL, nHandle)
self.projTree.setFileItemLayout(tHandle, nwItemLayout.TITLE) self.projTree.setFileItemLayout(tHandle, nwItemLayout.TITLE)
aDoc.openDocument(tHandle, showStatus=False) aDoc.readDocument(tHandle, showStatus=False)
aDoc.saveDocument(titlePage) aDoc.writeDocument(titlePage)
aDoc.clearDocument() aDoc.clearDocument()
# Create chapters and scenes # Create chapters and scenes
@@ -331,8 +331,8 @@ class NWProject():
cHandle = self.newFile(chTitle, nwItemClass.NOVEL, pHandle) cHandle = self.newFile(chTitle, nwItemClass.NOVEL, pHandle)
self.projTree.setFileItemLayout(cHandle, nwItemLayout.CHAPTER) self.projTree.setFileItemLayout(cHandle, nwItemLayout.CHAPTER)
aDoc.openDocument(cHandle, showStatus=False) aDoc.readDocument(cHandle, showStatus=False)
aDoc.saveDocument("## %s\n\n" % chTitle) aDoc.writeDocument("## %s\n\n" % chTitle)
aDoc.clearDocument() aDoc.clearDocument()
# Create chapter scenes # Create chapter scenes
@@ -341,8 +341,8 @@ class NWProject():
scTitle = self.tr("Scene {0}").format(f"{ch+1:d}.{sc+1:d}") scTitle = self.tr("Scene {0}").format(f"{ch+1:d}.{sc+1:d}")
sHandle = self.newFile(scTitle, nwItemClass.NOVEL, pHandle) sHandle = self.newFile(scTitle, nwItemClass.NOVEL, pHandle)
aDoc.openDocument(sHandle, showStatus=False) aDoc.readDocument(sHandle, showStatus=False)
aDoc.saveDocument("### %s\n\n" % scTitle) aDoc.writeDocument("### %s\n\n" % scTitle)
aDoc.clearDocument() aDoc.clearDocument()
# Create scenes (no chapters) # Create scenes (no chapters)
@@ -351,8 +351,8 @@ class NWProject():
scTitle = self.tr("Scene {0}").format(f"{sc+1:d}") scTitle = self.tr("Scene {0}").format(f"{sc+1:d}")
sHandle = self.newFile(scTitle, nwItemClass.NOVEL, nHandle) sHandle = self.newFile(scTitle, nwItemClass.NOVEL, nHandle)
aDoc.openDocument(sHandle, showStatus=False) aDoc.readDocument(sHandle, showStatus=False)
aDoc.saveDocument("### %s\n\n" % scTitle) aDoc.writeDocument("### %s\n\n" % scTitle)
aDoc.clearDocument() aDoc.clearDocument()
# Finalise # Finalise
@@ -1404,7 +1404,7 @@ class NWProject():
oParent = None oParent = None
oClass = None oClass = None
oLayout = None oLayout = None
if aDoc.openDocument(oHandle, showStatus=False, isOrphan=True) is not None: if aDoc.readDocument(oHandle, showStatus=False, isOrphan=True) is not None:
oName, oParent, oClass, oLayout = aDoc.getMeta() oName, oParent, oClass, oLayout = aDoc.getMeta()
if oName: if oName:
+5 -2
View File
@@ -278,13 +278,16 @@ class Tokenizer():
if self.theItem is None: if self.theItem is None:
return False return False
self.theText = ""
if theText is not None: if theText is not None:
# If the text is set, just use that # If the text is set, just use that
self.theText = theText self.theText = theText
else: else:
# Otherwise, load it from file # Otherwise, load it from file
theDocument = NWDoc(self.theProject, self.theParent) theDoc = NWDoc(self.theProject, self.theParent)
self.theText = theDocument.openDocument(theHandle) theText = theDoc.readDocument(theHandle)
if theText:
self.theText = theText
docSize = len(self.theText) docSize = len(self.theText)
if docSize > nwConst.MAX_DOCSIZE: if docSize > nwConst.MAX_DOCSIZE:
+5 -4
View File
@@ -110,8 +110,9 @@ class GuiDocMerge(QDialog):
theDoc = NWDoc(self.theProject, self.theParent) theDoc = NWDoc(self.theProject, self.theParent)
theText = "" theText = ""
for tHandle in finalOrder: for tHandle in finalOrder:
theText += theDoc.openDocument(tHandle, False).rstrip("\n") docText = theDoc.readDocument(tHandle, False).rstrip("\n")
theText += "\n\n" if docText:
theText += docText+"\n\n"
if self.sourceItem is None: if self.sourceItem is None:
self.theParent.makeAlert( self.theParent.makeAlert(
@@ -130,8 +131,8 @@ class GuiDocMerge(QDialog):
newItem = self.theProject.projTree[nHandle] newItem = self.theProject.projTree[nHandle]
newItem.setStatus(srcItem.itemStatus) newItem.setStatus(srcItem.itemStatus)
theDoc.openDocument(nHandle, False) theDoc.readDocument(nHandle, False)
theDoc.saveDocument(theText) theDoc.writeDocument(theText)
self.theParent.treeView.revealNewTreeItem(nHandle) self.theParent.treeView.revealNewTreeItem(nHandle)
self.theParent.openDocument(nHandle, doScroll=True) self.theParent.openDocument(nHandle, doScroll=True)
+10 -5
View File
@@ -127,8 +127,11 @@ class GuiDocSplit(QDialog):
) )
return return
theDoc = NWDoc(self.theProject, self.theParent) theDoc = NWDoc(self.theProject, self.theParent)
theText = theDoc.openDocument(self.sourceItem, False) theText = theDoc.readDocument(self.sourceItem, False)
if theText is None:
theText = ""
theLines = theText.splitlines() theLines = theText.splitlines()
nLines = len(theLines) nLines = len(theLines)
theLines.insert(0, "%Split Doc") theLines.insert(0, "%Split Doc")
@@ -214,8 +217,8 @@ class GuiDocSplit(QDialog):
theText = "\n".join(theLines[iStart:iEnd]) theText = "\n".join(theLines[iStart:iEnd])
theText = theText.rstrip("\n") + "\n\n" theText = theText.rstrip("\n") + "\n\n"
theDoc.openDocument(nHandle, False) theDoc.readDocument(nHandle, False)
theDoc.saveDocument(theText) theDoc.writeDocument(theText)
theDoc.clearDocument() theDoc.clearDocument()
self.theParent.treeView.revealNewTreeItem(nHandle) self.theParent.treeView.revealNewTreeItem(nHandle)
@@ -257,7 +260,9 @@ class GuiDocSplit(QDialog):
self.listBox.clear() self.listBox.clear()
theDoc = NWDoc(self.theProject, self.theParent) theDoc = NWDoc(self.theProject, self.theParent)
theText = theDoc.openDocument(self.sourceItem, False) theText = theDoc.readDocument(self.sourceItem, False)
if theText is None:
theText = ""
spLevel = self.splitLevel.currentData() spLevel = self.splitLevel.currentData()
self.optState.setValue("GuiDocSplit", "spLevel", spLevel) self.optState.setValue("GuiDocSplit", "spLevel", spLevel)
+3 -3
View File
@@ -297,7 +297,7 @@ class GuiDocEditor(QTextEdit):
document is new (empty string), we set up the editor for editing document is new (empty string), we set up the editor for editing
the file. the file.
""" """
theDoc = self.nwDocument.openDocument(tHandle, showStatus=showStatus) theDoc = self.nwDocument.readDocument(tHandle, showStatus=showStatus)
if theDoc is None: if theDoc is None:
# There was an io error # There was an io error
self.clearEditor() self.clearEditor()
@@ -438,7 +438,7 @@ class GuiDocEditor(QTextEdit):
theItem.setParaCount(self.paraCount) theItem.setParaCount(self.paraCount)
self.saveCursorPosition() self.saveCursorPosition()
self.nwDocument.saveDocument(docText) self.nwDocument.writeDocument(docText)
self.setDocumentChanged(False) self.setDocumentChanged(False)
self.theIndex.scanText(tHandle, docText) self.theIndex.scanText(tHandle, docText)
@@ -454,7 +454,7 @@ class GuiDocEditor(QTextEdit):
if self.theProject.projTree.updateItemLayout(tHandle, hLevel): if self.theProject.projTree.updateItemLayout(tHandle, hLevel):
self.theParent.treeView.setTreeItemValues(tHandle) self.theParent.treeView.setTreeItemValues(tHandle)
self.nwDocument.saveDocument(docText) self.nwDocument.writeDocument(docText)
self.docFooter.updateInfo() self.docFooter.updateInfo()
return True return True
+5 -2
View File
@@ -287,7 +287,10 @@ class GuiProjectTree(QTreeWidget):
# This is a new files, so let's add some content # This is a new files, so let's add some content
newDoc = NWDoc(self.theProject, self.theParent) newDoc = NWDoc(self.theProject, self.theParent)
curTxt = newDoc.openDocument(tHandle, showStatus=False) curTxt = newDoc.readDocument(tHandle, showStatus=False)
if curTxt is None:
curTxt = ""
if curTxt == "": if curTxt == "":
if nwItem.itemLayout == nwItemLayout.CHAPTER: if nwItem.itemLayout == nwItemLayout.CHAPTER:
newText = f"## {nwItem.itemName}\n\n" newText = f"## {nwItem.itemName}\n\n"
@@ -299,7 +302,7 @@ class GuiProjectTree(QTreeWidget):
newText = f"# {nwItem.itemName}\n\n" newText = f"# {nwItem.itemName}\n\n"
# Save the text and index it # Save the text and index it
newDoc.saveDocument(newText) newDoc.writeDocument(newText)
self.theIndex.scanText(tHandle, newText) self.theIndex.scanText(tHandle, newText)
# Get Word Counts # Get Word Counts
+2 -6
View File
@@ -48,7 +48,7 @@ from nw.dialogs import (
GuiProjectLoad, GuiProjectSettings, GuiWordList GuiProjectLoad, GuiProjectSettings, GuiWordList
) )
from nw.tools import GuiBuildNovel, GuiProjectWizard, GuiWritingStats from nw.tools import GuiBuildNovel, GuiProjectWizard, GuiWritingStats
from nw.core import NWProject, NWDoc, NWIndex from nw.core import NWProject, NWIndex
from nw.enum import nwItemType, nwItemClass, nwAlert, nwWidget from nw.enum import nwItemType, nwItemClass, nwAlert, nwWidget
from nw.common import getGuiItem, hexToInt from nw.common import getGuiItem, hexToInt
from nw.constants import nwLists from nw.constants import nwLists
@@ -878,7 +878,6 @@ class GuiMain(QMainWindow):
self.treeView.saveTreeOrder() self.treeView.saveTreeOrder()
self.theIndex.clearIndex() self.theIndex.clearIndex()
theDoc = NWDoc(self.theProject, self)
for nDone, tItem in enumerate(self.theProject.projTree): for nDone, tItem in enumerate(self.theProject.projTree):
if tItem is not None: if tItem is not None:
@@ -888,10 +887,7 @@ class GuiMain(QMainWindow):
if tItem is not None and tItem.itemType == nwItemType.FILE: if tItem is not None and tItem.itemType == nwItemType.FILE:
logger.verbose("Scanning: %s" % tItem.itemName) logger.verbose("Scanning: %s" % tItem.itemName)
theText = theDoc.openDocument(tItem.itemHandle, showStatus=False) self.theIndex.reIndexHandle(tItem.itemHandle)
# Build tag index
self.theIndex.scanText(tItem.itemHandle, theText)
# Get Word Counts # Get Word Counts
cC, wC, pC = self.theIndex.getCounts(tItem.itemHandle) cC, wC, pC = self.theIndex.getCounts(tItem.itemHandle)
+15 -15
View File
@@ -41,10 +41,10 @@ def testCoreDocument_LoadSave(monkeypatch, dummyGUI, nwMinimal):
sHandle = "8c659a11cd429" sHandle = "8c659a11cd429"
# Not a valid handle # Not a valid handle
assert theDoc.openDocument("dummy") is None assert theDoc.readDocument("dummy") is None
# Non-existent handle # Non-existent handle
assert theDoc.openDocument("0000000000000") is None assert theDoc.readDocument("0000000000000") is None
# Cause open() to fail while loading # Cause open() to fail while loading
def dummyOpen(*args, **kwargs): def dummyOpen(*args, **kwargs):
@@ -52,29 +52,29 @@ def testCoreDocument_LoadSave(monkeypatch, dummyGUI, nwMinimal):
with monkeypatch.context() as mp: with monkeypatch.context() as mp:
mp.setattr("builtins.open", dummyOpen) mp.setattr("builtins.open", dummyOpen)
assert theDoc.openDocument(sHandle) is None assert theDoc.readDocument(sHandle) is None
# Load the text # Load the text
assert theDoc.openDocument(sHandle) == "### New Scene\n\n" assert theDoc.readDocument(sHandle) == "### New Scene\n\n"
# Try to open a new (non-existent) file # Try to open a new (non-existent) file
nHandle = theProject.projTree.findRoot(nwItemClass.NOVEL) nHandle = theProject.projTree.findRoot(nwItemClass.NOVEL)
assert nHandle is not None assert nHandle is not None
xHandle = theProject.newFile("New File", nwItemClass.NOVEL, nHandle) xHandle = theProject.newFile("New File", nwItemClass.NOVEL, nHandle)
assert theDoc.openDocument(xHandle) == "" assert theDoc.readDocument(xHandle) == ""
# Check cached item # Check cached item
assert isinstance(theDoc._theItem, NWItem) assert isinstance(theDoc._theItem, NWItem)
assert theDoc.openDocument(xHandle, isOrphan=True) == "" assert theDoc.readDocument(xHandle, isOrphan=True) == ""
assert theDoc._theItem is None assert theDoc._theItem is None
# Set handle and save again # Set handle and save again
theText = "### Test File\n\nText ...\n\n" theText = "### Test File\n\nText ...\n\n"
assert theDoc.openDocument(xHandle) == "" assert theDoc.readDocument(xHandle) == ""
assert theDoc.saveDocument(theText) assert theDoc.writeDocument(theText)
# Save again to ensure temp file and previous file is handled # Save again to ensure temp file and previous file is handled
assert theDoc.saveDocument(theText) assert theDoc.writeDocument(theText)
# Check file content # Check file content
docPath = os.path.join(nwMinimal, "content", xHandle+".nwd") docPath = os.path.join(nwMinimal, "content", xHandle+".nwd")
@@ -89,7 +89,7 @@ def testCoreDocument_LoadSave(monkeypatch, dummyGUI, nwMinimal):
# Force no meta data # Force no meta data
theDoc._theItem = None theDoc._theItem = None
assert theDoc.saveDocument(theText) assert theDoc.writeDocument(theText)
with open(docPath, mode="r", encoding="utf8") as inFile: with open(docPath, mode="r", encoding="utf8") as inFile:
assert inFile.read() == theText assert inFile.read() == theText
@@ -97,11 +97,11 @@ def testCoreDocument_LoadSave(monkeypatch, dummyGUI, nwMinimal):
# Cause open() to fail while saving # Cause open() to fail while saving
with monkeypatch.context() as mp: with monkeypatch.context() as mp:
mp.setattr("builtins.open", causeOSError) mp.setattr("builtins.open", causeOSError)
assert not theDoc.saveDocument(theText) assert not theDoc.writeDocument(theText)
# Saving with no handle # Saving with no handle
theDoc.clearDocument() theDoc.clearDocument()
assert not theDoc.saveDocument(theText) assert not theDoc.writeDocument(theText)
# Delete the last document # Delete the last document
assert not theDoc.deleteDocument("dummy") assert not theDoc.deleteDocument("dummy")
@@ -130,7 +130,7 @@ def testCoreDocument_Methods(monkeypatch, dummyGUI, nwMinimal):
sHandle = "8c659a11cd429" sHandle = "8c659a11cd429"
docPath = os.path.join(nwMinimal, "content", sHandle+".nwd") docPath = os.path.join(nwMinimal, "content", sHandle+".nwd")
assert theDoc.openDocument(sHandle) == "### New Scene\n\n" assert theDoc.readDocument(sHandle) == "### New Scene\n\n"
# Check location # Check location
assert theDoc.getFileLocation() == docPath assert theDoc.getFileLocation() == docPath
@@ -147,7 +147,7 @@ def testCoreDocument_Methods(monkeypatch, dummyGUI, nwMinimal):
assert theLayout == nwItemLayout.SCENE assert theLayout == nwItemLayout.SCENE
# Add meta data garbage # Add meta data garbage
assert theDoc.saveDocument("%%~ stuff\n### Test File\n\nText ...\n\n") assert theDoc.writeDocument("%%~ stuff\n### Test File\n\nText ...\n\n")
with open(docPath, mode="r", encoding="utf8") as inFile: with open(docPath, mode="r", encoding="utf8") as inFile:
assert inFile.read() == ( assert inFile.read() == (
"%%~name: New Scene\n" "%%~name: New Scene\n"
@@ -158,6 +158,6 @@ def testCoreDocument_Methods(monkeypatch, dummyGUI, nwMinimal):
"Text ...\n\n" "Text ...\n\n"
) )
assert theDoc.openDocument(sHandle) == "### Test File\n\nText ...\n\n" assert theDoc.readDocument(sHandle) == "### Test File\n\nText ...\n\n"
# END Test testCoreDocument_Methods # END Test testCoreDocument_Methods
+2 -2
View File
@@ -138,8 +138,8 @@ def testCoreToken_TextOps(monkeypatch, nwMinimal, dummyGUI):
docTextR = docText.replace("<A>", "this").replace("<B>", "that") docTextR = docText.replace("<A>", "this").replace("<B>", "that")
nDoc = NWDoc(theProject, dummyGUI) nDoc = NWDoc(theProject, dummyGUI)
nDoc.openDocument(sHandle) nDoc.readDocument(sHandle)
nDoc.saveDocument(docText) nDoc.writeDocument(docText)
nDoc.clearDocument() nDoc.clearDocument()
theProject.setAutoReplace({"A": "this", "B": "that"}) theProject.setAutoReplace({"A": "this", "B": "that"})