Make NWDoc class non-reusable

This commit is contained in:
Veronica K. B. Olsen
2021-04-25 23:01:20 +02:00
parent fd28cbca4e
commit 470daf0036
8 changed files with 50 additions and 65 deletions
+14 -24
View File
@@ -38,16 +38,16 @@ logger = logging.getLogger(__name__)
class NWDoc(): class NWDoc():
def __init__(self, theProject): def __init__(self, theProject, theHandle):
self.theProject = theProject self.theProject = theProject
self.theParent = theProject.theParent self.theParent = theProject.theParent
# Internal Variables # Internal Variables
self._theItem = None # The currently open item self._docHandle = theHandle
self._docHandle = None # The handle of the currently open item self._theItem = self.theProject.projTree[theHandle]
self._fileLoc = None # The file location of the currently open item self._fileLoc = None
self._docMeta = {} # The meta data of the currently open item self._docMeta = {}
# Internal Mapping # Internal Mapping
self.makeAlert = self.theParent.makeAlert self.makeAlert = self.theParent.makeAlert
@@ -68,26 +68,16 @@ class NWDoc():
self._docMeta = {} self._docMeta = {}
return return
def readDocument(self, tHandle, isOrphan=False): def readDocument(self, isOrphan=False):
"""Read a document from handle, capturing potential file system """Read a document from set handle, capturing potential file
errors and parse meta data. If the document doesn't exist on system errors and parse meta data. If the document doesn't exist
disk, return an empty string. If something went wrong, return on disk, return an empty string. If something went wrong, return
None. None.
""" """
if not isHandle(tHandle): if not isHandle(self._docHandle):
return None return None
# Always clear first, since the object will often be reused.
self.clearDocument()
self._docHandle = tHandle
if not isOrphan:
self._theItem = self.theProject.projTree[tHandle]
else:
self._theItem = None
if self._theItem is None and not isOrphan: if self._theItem is None and not isOrphan:
self.clearDocument()
return None return None
docFile = self._docHandle+".nwd" docFile = self._docHandle+".nwd"
@@ -133,7 +123,7 @@ class NWDoc():
"""Write 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 not isHandle(self._docHandle):
return False return False
self.theProject.ensureFolderStructure() self.theProject.ensureFolderStructure()
@@ -170,14 +160,14 @@ class NWDoc():
return True return True
def deleteDocument(self, tHandle): def deleteDocument(self):
"""Permanently delete a document source file and related files """Permanently delete a document source file and related files
from the project data folder. from the project data folder.
""" """
if not isHandle(tHandle): if not isHandle(self._docHandle):
return False return False
docFile = tHandle+".nwd" docFile = self._docHandle+".nwd"
chkList = [] chkList = []
chkList.append(os.path.join(self.theProject.projContent, docFile)) chkList.append(os.path.join(self.theProject.projContent, docFile))
+2 -2
View File
@@ -115,8 +115,8 @@ class NWIndex():
if tItem.itemType != nwItemType.FILE: if tItem.itemType != nwItemType.FILE:
return False return False
theDoc = NWDoc(self.theProject) theDoc = NWDoc(self.theProject, tHandle)
theText = theDoc.readDocument(tHandle) theText = theDoc.readDocument()
if theText: if theText:
self.scanText(tHandle, theText) self.scanText(tHandle, theText)
+10 -19
View File
@@ -265,9 +265,6 @@ class NWProject():
if self.bookAuthors: if self.bookAuthors:
titlePage = "%s%s %s\n" % (titlePage, self.tr("By"), self.getAuthors()) titlePage = "%s%s %s\n" % (titlePage, self.tr("By"), self.getAuthors())
# Document object for writing files
aDoc = NWDoc(self)
if popMinimal: if popMinimal:
# Creating a minimal project with a few root folders and a # Creating a minimal project with a few root folders and a
# single chapter folder with a single file. # single chapter folder with a single file.
@@ -284,17 +281,14 @@ 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.readDocument(xHandle[5]) aDoc = NWDoc(self, xHandle[5])
aDoc.writeDocument(titlePage) aDoc.writeDocument(titlePage)
aDoc.clearDocument()
aDoc.readDocument(xHandle[7]) aDoc = NWDoc(self, xHandle[7])
aDoc.writeDocument("## %s\n\n" % self.tr("New Chapter")) aDoc.writeDocument("## %s\n\n" % self.tr("New Chapter"))
aDoc.clearDocument()
aDoc.readDocument(xHandle[8]) aDoc = NWDoc(self, xHandle[8])
aDoc.writeDocument("### %s\n\n" % self.tr("New Scene")) aDoc.writeDocument("### %s\n\n" % self.tr("New Scene"))
aDoc.clearDocument()
elif popCustom: elif popCustom:
# Create a project structure based on selected root folders # Create a project structure based on selected root folders
@@ -311,9 +305,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.readDocument(tHandle) aDoc = NWDoc(self, tHandle)
aDoc.writeDocument(titlePage) aDoc.writeDocument(titlePage)
aDoc.clearDocument()
# Create chapters and scenes # Create chapters and scenes
numChapters = projData.get("numChapters", 0) numChapters = projData.get("numChapters", 0)
@@ -331,9 +324,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.readDocument(cHandle) aDoc = NWDoc(self, cHandle)
aDoc.writeDocument("## %s\n\n" % chTitle) aDoc.writeDocument("## %s\n\n" % chTitle)
aDoc.clearDocument()
# Create chapter scenes # Create chapter scenes
if numScenes > 0: if numScenes > 0:
@@ -341,9 +333,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.readDocument(sHandle) aDoc = NWDoc(self, sHandle)
aDoc.writeDocument("### %s\n\n" % scTitle) aDoc.writeDocument("### %s\n\n" % scTitle)
aDoc.clearDocument()
# Create scenes (no chapters) # Create scenes (no chapters)
elif numScenes > 0: elif numScenes > 0:
@@ -351,9 +342,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.readDocument(sHandle) aDoc = NWDoc(self, sHandle)
aDoc.writeDocument("### %s\n\n" % scTitle) aDoc.writeDocument("### %s\n\n" % scTitle)
aDoc.clearDocument()
# Finalise # Finalise
if popCustom or popMinimal: if popCustom or popMinimal:
@@ -1393,7 +1383,6 @@ class NWProject():
return return
# Handle orphans # Handle orphans
aDoc = NWDoc(self)
nOrph = 0 nOrph = 0
noWhere = False noWhere = False
oPrefix = self.tr("Recovered") oPrefix = self.tr("Recovered")
@@ -1404,7 +1393,9 @@ class NWProject():
oParent = None oParent = None
oClass = None oClass = None
oLayout = None oLayout = None
if aDoc.readDocument(oHandle, isOrphan=True) is not None:
aDoc = NWDoc(self, oHandle)
if aDoc.readDocument(isOrphan=True) is not None:
oName, oParent, oClass, oLayout = aDoc.getMeta() oName, oParent, oClass, oLayout = aDoc.getMeta()
if oName: if oName:
+2 -2
View File
@@ -284,8 +284,8 @@ class Tokenizer():
self.theText = theText self.theText = theText
else: else:
# Otherwise, load it from file # Otherwise, load it from file
theDoc = NWDoc(self.theProject) theDoc = NWDoc(self.theProject, theHandle)
theText = theDoc.readDocument(theHandle) theText = theDoc.readDocument()
if theText: if theText:
self.theText = theText self.theText = theText
+5 -4
View File
@@ -107,10 +107,10 @@ class GuiDocMerge(QDialog):
) )
return return
theDoc = NWDoc(self.theProject)
theText = "" theText = ""
for tHandle in finalOrder: for tHandle in finalOrder:
docText = theDoc.readDocument(tHandle).rstrip("\n") inDoc = NWDoc(self.theProject, tHandle)
docText = inDoc.readDocument().rstrip("\n")
if docText: if docText:
theText += docText+"\n\n" theText += docText+"\n\n"
@@ -131,8 +131,9 @@ class GuiDocMerge(QDialog):
newItem = self.theProject.projTree[nHandle] newItem = self.theProject.projTree[nHandle]
newItem.setStatus(srcItem.itemStatus) newItem.setStatus(srcItem.itemStatus)
theDoc.readDocument(nHandle) outDoc = NWDoc(self.theProject, nHandle)
theDoc.writeDocument(theText) outDoc.writeDocument(theText)
self.theParent.treeView.revealNewTreeItem(nHandle) self.theParent.treeView.revealNewTreeItem(nHandle)
self.theParent.openDocument(nHandle, doScroll=True) self.theParent.openDocument(nHandle, doScroll=True)
+8 -7
View File
@@ -127,8 +127,8 @@ class GuiDocSplit(QDialog):
) )
return return
theDoc = NWDoc(self.theProject) inDoc = NWDoc(self.theProject, self.sourceItem)
theText = theDoc.readDocument(self.sourceItem) theText = inDoc.readDocument()
if theText is None: if theText is None:
theText = "" theText = ""
@@ -217,9 +217,10 @@ 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.readDocument(nHandle)
theDoc.writeDocument(theText) outDoc = NWDoc(self.theProject, nHandle)
theDoc.clearDocument() outDoc.writeDocument(theText)
self.theParent.treeView.revealNewTreeItem(nHandle) self.theParent.treeView.revealNewTreeItem(nHandle)
self._doClose() self._doClose()
@@ -259,8 +260,8 @@ class GuiDocSplit(QDialog):
return return
self.listBox.clear() self.listBox.clear()
theDoc = NWDoc(self.theProject) inDoc = NWDoc(self.theProject, self.sourceItem)
theText = theDoc.readDocument(self.sourceItem) theText = inDoc.readDocument()
if theText is None: if theText is None:
theText = "" theText = ""
+5 -3
View File
@@ -75,7 +75,7 @@ class GuiDocEditor(QTextEdit):
self.theTheme = theParent.theTheme self.theTheme = theParent.theTheme
self.theIndex = theParent.theIndex self.theIndex = theParent.theIndex
self.theProject = theParent.theProject self.theProject = theParent.theProject
self.nwDocument = NWDoc(self.theProject) self.nwDocument = NWDoc(self.theProject, None)
self.docChanged = False # Flag for changed status of document self.docChanged = False # Flag for changed status of document
self.spellCheck = False # Flag for spell checking enabled self.spellCheck = False # Flag for spell checking enabled
@@ -165,7 +165,7 @@ class GuiDocEditor(QTextEdit):
"""Clear the current document and reset all document related """Clear the current document and reset all document related
flags and counters. flags and counters.
""" """
self.nwDocument.clearDocument() self.nwDocument = NWDoc(self.theProject, None)
self.setReadOnly(True) self.setReadOnly(True)
self.clear() self.clear()
self.wcTimer.stop() self.wcTimer.stop()
@@ -297,7 +297,9 @@ 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.readDocument(tHandle) self.nwDocument = NWDoc(self.theProject, tHandle)
theDoc = self.nwDocument.readDocument()
if theDoc is None: if theDoc is None:
# There was an io error # There was an io error
self.clearEditor() self.clearEditor()
+4 -4
View File
@@ -286,8 +286,8 @@ class GuiProjectTree(QTreeWidget):
return True return True
# 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) newDoc = NWDoc(self.theProject, tHandle)
curTxt = newDoc.readDocument(tHandle) curTxt = newDoc.readDocument()
if curTxt is None: if curTxt is None:
curTxt = "" curTxt = ""
@@ -527,8 +527,8 @@ class GuiProjectTree(QTreeWidget):
if self.theParent.docEditor.theHandle == tHandle: if self.theParent.docEditor.theHandle == tHandle:
self.theParent.closeDocument() self.theParent.closeDocument()
theDoc = NWDoc(self.theProject) delDoc = NWDoc(self.theProject, tHandle)
theDoc.deleteDocument(tHandle) delDoc.deleteDocument()
self.theIndex.deleteHandle(tHandle) self.theIndex.deleteHandle(tHandle)
self._deleteTreeItem(tHandle) self._deleteTreeItem(tHandle)
self._setTreeChanged(True) self._setTreeChanged(True)