Use storage class to return document objects

This commit is contained in:
Veronica Berglyd Olsen
2022-11-06 00:29:43 +01:00
parent 76a1421fde
commit a75424e44b
14 changed files with 36 additions and 46 deletions
-2
View File
@@ -20,7 +20,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from novelwriter.core.coretools import DocMerger, DocSplitter, ProjectBuilder
from novelwriter.core.document import NWDoc
from novelwriter.core.index import countWords
from novelwriter.core.project import NWProject
from novelwriter.core.spellcheck import NWSpellEnchant
@@ -33,7 +32,6 @@ __all__ = [
"DocSplitter",
"ProjectBuilder",
"countWords",
"NWDoc",
"NWProject",
"NWSpellEnchant",
"ToHtml",
+10 -11
View File
@@ -38,7 +38,6 @@ from novelwriter.enum import nwAlert
from novelwriter.common import minmax, simplified
from novelwriter.constants import nwItemClass
from novelwriter.core.project import NWProject
from novelwriter.core.document import NWDoc
logger = logging.getLogger(__name__)
@@ -102,7 +101,7 @@ class DocMerger:
if srcItem is None:
return False
inDoc = NWDoc(self.theProject, srcHandle)
inDoc = self.theProject.storage.getDocument(srcHandle)
docText = (inDoc.readDocument() or "").rstrip("\n")
if addComment:
@@ -122,7 +121,7 @@ class DocMerger:
if self._targetDoc is None:
return False
outDoc = NWDoc(self.theProject, self._targetDoc)
outDoc = self.theProject.storage.getDocument(self._targetDoc)
docText = (outDoc.readDocument() or "").rstrip("\n")
if docText:
self._targetText.insert(0, docText)
@@ -247,7 +246,7 @@ class DocSplitter:
newItem.setStatus(self._srcItem.itemStatus)
newItem.setImport(self._srcItem.itemImport)
outDoc = NWDoc(self.theProject, dHandle)
outDoc = self.theProject.storage.getDocument(dHandle)
status = outDoc.writeDocument("\n".join(docText))
if not status:
self._error = outDoc.getError()
@@ -337,18 +336,18 @@ class ProjectBuilder:
if project.data.authors:
titlePage += f">> {lblByAuthors} {project.getFormattedAuthors()} <<\n\n"
aDoc = NWDoc(project, hTitlePage)
aDoc = project.storage.getDocument(hTitlePage)
aDoc.writeDocument(titlePage)
if popMinimal:
# Creating a minimal project with a few root folders and a
# single chapter with a single scene.
hChapter = project.newFile(lblNewChapter, hNovelRoot)
aDoc = NWDoc(project, hChapter)
aDoc = project.storage.getDocument(hChapter)
aDoc.writeDocument(f"## {lblNewChapter}\n\n")
hScene = project.newFile(lblNewScene, hChapter)
aDoc = NWDoc(project, hScene)
aDoc = project.storage.getDocument(hScene)
aDoc.writeDocument(f"### {lblNewScene}\n\n")
project.newRoot(nwItemClass.PLOT)
@@ -376,7 +375,7 @@ class ProjectBuilder:
for ch in range(numChapters):
chTitle = self.tr("Chapter {0}").format(f"{ch+1:d}")
cHandle = project.newFile(chTitle, hNovelRoot)
aDoc = NWDoc(project, cHandle)
aDoc = project.storage.getDocument(cHandle)
aDoc.writeDocument(f"## {chTitle}\n\n% Synopsis: {chSynop}\n\n")
# Create chapter scenes
@@ -384,7 +383,7 @@ class ProjectBuilder:
for sc in range(numScenes):
scTitle = self.tr("Scene {0}").format(f"{ch+1:d}.{sc+1:d}")
sHandle = project.newFile(scTitle, cHandle)
aDoc = NWDoc(project, sHandle)
aDoc = project.storage.getDocument(sHandle)
aDoc.writeDocument(f"### {scTitle}\n\n% Synopsis: {scSynop}\n\n")
# Create scenes (no chapters)
@@ -392,7 +391,7 @@ class ProjectBuilder:
for sc in range(numScenes):
scTitle = self.tr("Scene {0}").format(f"{sc+1:d}")
sHandle = project.newFile(scTitle, hNovelRoot)
aDoc = NWDoc(project, sHandle)
aDoc = project.storage.getDocument(sHandle)
aDoc.writeDocument(f"### {scTitle}\n\n% Synopsis: {scSynop}\n\n")
# Create notes folders
@@ -409,7 +408,7 @@ class ProjectBuilder:
if addNotes:
aHandle = project.newFile(noteTitles[newRoot], rHandle)
ntTag = simplified(noteTitles[newRoot]).replace(" ", "")
aDoc = NWDoc(project, aHandle)
aDoc = project.storage.getDocument(aHandle)
aDoc.writeDocument(f"# {noteTitles[newRoot]}\n\n@tag: {ntTag}\n\n")
# Also add the archive and trash folders
+1 -2
View File
@@ -35,7 +35,6 @@ from pathlib import Path
from novelwriter.enum import nwItemType, nwItemLayout
from novelwriter.error import logException
from novelwriter.constants import nwFiles, nwKeyWords, nwUnicode, nwHeaders
from novelwriter.core.document import NWDoc
from novelwriter.common import (
checkInt, isHandle, isItemClass, isTitleTag, jsonEncode
)
@@ -118,7 +117,7 @@ class NWIndex:
return False
logger.debug("Re-indexing item '%s'", tHandle)
theDoc = NWDoc(self.theProject, tHandle)
theDoc = self.theProject.storage.getDocument(tHandle)
self.scanText(tHandle, theDoc.readDocument() or "")
return True
+3 -4
View File
@@ -45,7 +45,6 @@ from novelwriter.core.item import NWItem
from novelwriter.core.index import NWIndex
from novelwriter.core.options import OptionState
from novelwriter.core.storage import NWStorage
from novelwriter.core.document import NWDoc
from novelwriter.core.projectxml import ProjectXMLReader, ProjectXMLWriter, XMLReadState
from novelwriter.core.projectdata import NWProjectData
from novelwriter.common import (
@@ -183,7 +182,7 @@ class NWProject(QObject):
if not tItem.isFileType():
return False
newDoc = NWDoc(self, tHandle)
newDoc = self._storage.getDocument(tHandle)
if (newDoc.readDocument() or "").strip():
return False
@@ -204,7 +203,7 @@ class NWProject(QObject):
project entry and a document file if it exists.
"""
if self._tree.checkType(tHandle, nwItemType.FILE):
delDoc = NWDoc(self, tHandle)
delDoc = self._storage.getDocument(tHandle)
if not delDoc.deleteDocument():
self.mainGui.makeAlert([
self.tr("Could not delete document file."), delDoc.getError()
@@ -820,7 +819,7 @@ class NWProject(QObject):
oClass = None
oLayout = None
aDoc = NWDoc(self, oHandle)
aDoc = self._storage.getDocument(oHandle)
if aDoc.readDocument(isOrphan=True) is not None:
oName, oParent, oClass, oLayout = aDoc.getMeta()
+4 -4
View File
@@ -30,6 +30,7 @@ from time import time
from pathlib import Path
from novelwriter.constants import nwFiles
from novelwriter.core.document import NWDoc
from novelwriter.core.projectxml import ProjectXMLReader, ProjectXMLWriter
from novelwriter.error import logException
@@ -153,7 +154,9 @@ class NWStorage:
def getDocument(self, tHandle):
"""Return a document wrapper object.
"""
pass
if self._runtimePath is not None:
return NWDoc(self.theProject, tHandle)
return NWDoc(self.theProject, None)
def getMetaFile(self, fileName):
"""Return the path to a file in the project meta folder.
@@ -232,9 +235,6 @@ class NWStorage:
def _zipIt(self, target):
pass
def _writeLockFile(self):
pass
def _prepareStorage(self, checkLegacy=True, newProject=False):
"""Prepare the storage area for the project.
"""
+1 -2
View File
@@ -36,7 +36,6 @@ from PyQt5.QtCore import QCoreApplication, QRegularExpression
from novelwriter.enum import nwItemLayout, nwItemType
from novelwriter.common import numberToRoman, checkInt
from novelwriter.constants import nwConst, nwRegEx, nwUnicode
from novelwriter.core.document import NWDoc
logger = logging.getLogger(__name__)
@@ -305,7 +304,7 @@ class Tokenizer(ABC):
return False
if theText is None:
theText = NWDoc(self.theProject, theHandle).readDocument() or ""
theText = self.theProject.storage.getDocument(theHandle).readDocument() or ""
self._theText = theText
+1 -2
View File
@@ -33,7 +33,6 @@ from PyQt5.QtWidgets import (
QListWidgetItem, QDialogButtonBox, QLabel, QGridLayout
)
from novelwriter.core import NWDoc
from novelwriter.custom import QHelpLabel, QSwitch
logger = logging.getLogger(__name__)
@@ -204,7 +203,7 @@ class GuiDocSplit(QDialog):
spLevel = self.splitLevel.currentData()
if not self._text:
inDoc = NWDoc(self.theProject, sHandle)
inDoc = self.theProject.storage.getDocument(sHandle)
self._text = (inDoc.readDocument() or "").splitlines()
for lineNo, aLine in enumerate(self._text):
+2 -2
View File
@@ -50,7 +50,7 @@ from PyQt5.QtWidgets import (
QFrame
)
from novelwriter.core import NWDoc, NWSpellEnchant, countWords
from novelwriter.core import NWSpellEnchant, countWords
from novelwriter.enum import nwAlert, nwDocAction, nwDocInsert, nwDocMode
from novelwriter.common import transferCase
from novelwriter.constants import nwConst, nwKeyWords, nwUnicode
@@ -339,7 +339,7 @@ class GuiDocEditor(QTextEdit):
document is new (empty string), we set up the editor for editing
the file.
"""
self._nwDocument = NWDoc(self.theProject, tHandle)
self._nwDocument = self.theProject.storage.getDocument(tHandle)
self._nwItem = self._nwDocument.getCurrentItem()
theDoc = self._nwDocument.readDocument()
+1 -2
View File
@@ -31,7 +31,6 @@ from tools import C, buildTestProject, cmpFiles, XML_IGNORE
from novelwriter.constants import nwItemClass
from novelwriter.core.project import NWProject
from novelwriter.core.document import NWDoc
from novelwriter.core.coretools import DocMerger, DocSplitter, ProjectBuilder
@@ -164,7 +163,7 @@ def testCoreTools_DocSplitter(monkeypatch, mockGUI, fncDir, outDir, refDir, mock
docText = "\n\n".join(docData)
docRaw = docText.splitlines()
assert NWDoc(theProject, hSplitDoc).writeDocument(docText) is True
assert theProject.storage.getDocument(hSplitDoc).writeDocument(docText) is True
theProject.tree[hSplitDoc].setStatus(C.sFinished)
theProject.tree[hSplitDoc].setImport(C.iMain)
+4 -3
View File
@@ -38,7 +38,6 @@ from novelwriter.core.tree import NWTree
from novelwriter.core.index import NWIndex
from novelwriter.core.project import NWProject
from novelwriter.core.options import OptionState
from novelwriter.core.document import NWDoc
from novelwriter.core.projectxml import ProjectXMLReader, ProjectXMLWriter, XMLReadState
@@ -125,11 +124,13 @@ def testCoreProject_NewFileFolder(monkeypatch, fncDir, outDir, refDir, mockGUI,
# Write to file, success
assert theProject.writeNewFile("0000000000011", 2, True) is True
assert NWDoc(theProject, "0000000000011").readDocument() == "## Hello\n\n"
assert theProject.storage.getDocument("0000000000011").readDocument() == "## Hello\n\n"
# Write to file with additional text, success
assert theProject.writeNewFile("0000000000012", 1, False, "Hi Jane\n\n") is True
assert NWDoc(theProject, "0000000000012").readDocument() == "# Jane\n\nHi Jane\n\n"
assert theProject.storage.getDocument("0000000000012").readDocument() == (
"# Jane\n\nHi Jane\n\n"
)
# Save, close and check
assert theProject.projChanged is True
+1 -2
View File
@@ -25,7 +25,6 @@ import pytest
from tools import C, buildTestProject, readFile
from novelwriter.core.project import NWProject
from novelwriter.core.document import NWDoc
from novelwriter.core.tokenizer import Tokenizer
@@ -156,7 +155,7 @@ def testCoreToken_TextOps(monkeypatch, mockGUI, mockRnd, fncDir):
)
docTextR = docText.replace("<A>", "this").replace("<B>", "that")
nDoc = NWDoc(theProject, C.hSceneDoc)
nDoc = theProject.storage.getDocument(C.hSceneDoc)
assert nDoc.writeDocument(docText)
theProject.data.setAutoReplace({"A": "this", "B": "that"})
+3 -4
View File
@@ -29,7 +29,6 @@ from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMessageBox, QMenu, QTreeWidgetItem, QDialog
from novelwriter.enum import nwItemLayout, nwItemType, nwItemClass
from novelwriter.core import NWDoc
from novelwriter.gui.projtree import GuiProjectTree
from novelwriter.dialogs.docmerge import GuiDocMerge
from novelwriter.dialogs.docsplit import GuiDocSplit
@@ -714,7 +713,7 @@ def testGuiProjTree_MergeDocuments(qtbot, monkeypatch, nwGUI, fncDir, mockRnd, i
# The merge goes through
assert projTree._mergeDocuments(hChapter1, True) is True
assert len(NWDoc(theProject, mergedDoc1).readDocument()) > lenAll
assert len(theProject.storage.getDocument(mergedDoc1).readDocument()) > lenAll
# Merge to Existing Doc
# =====================
@@ -733,9 +732,9 @@ def testGuiProjTree_MergeDocuments(qtbot, monkeypatch, nwGUI, fncDir, mockRnd, i
# Successful merge, and move to trash
mergeData["moveToTrash"] = True
assert len(NWDoc(theProject, hChapter1).readDocument()) < lenAll
assert len(theProject.storage.getDocument(hChapter1).readDocument()) < lenAll
assert projTree._mergeDocuments(hChapter1, False) is True
assert len(NWDoc(theProject, hChapter1).readDocument()) > lenAll
assert len(theProject.storage.getDocument(hChapter1).readDocument()) > lenAll
assert theProject.tree.isTrash(hSceneOne11)
assert theProject.tree.isTrash(hSceneOne12)
+1 -2
View File
@@ -25,7 +25,6 @@ import pytest
from tools import C, buildTestProject
from novelwriter.enum import nwState
from novelwriter.core.document import NWDoc
@pytest.mark.gui
@@ -34,7 +33,7 @@ def testGuiStatusBar_Main(qtbot, nwGUI, fncProj, mockRnd):
"""
buildTestProject(nwGUI, fncProj)
cHandle = nwGUI.theProject.newFile("A Note", C.hCharRoot)
newDoc = NWDoc(nwGUI.theProject, cHandle)
newDoc = nwGUI.theProject.storage.getDocument(cHandle)
newDoc.writeDocument("# A Note\n\n")
nwGUI.projView.projTree.revealNewTreeItem(cHandle)
nwGUI.rebuildIndex(beQuiet=True)
+4 -4
View File
@@ -156,7 +156,7 @@ def buildTestProject(theObject, projPath):
object as the parent.
"""
from novelwriter.enum import nwItemClass
from novelwriter.core import NWProject, NWDoc
from novelwriter.core import NWProject
if isinstance(theObject, NWProject):
theGUI = None
@@ -187,15 +187,15 @@ def buildTestProject(theObject, projPath):
xHandle[7] = theProject.newFile("New Chapter", xHandle[6])
xHandle[8] = theProject.newFile("New Scene", xHandle[6])
aDoc = NWDoc(theProject, xHandle[5])
aDoc = theProject.storage.getDocument(xHandle[5])
aDoc.writeDocument("#! New Novel\n\n>> By Jane Doe <<\n")
theProject.index.reIndexHandle(xHandle[5])
aDoc = NWDoc(theProject, xHandle[7])
aDoc = theProject.storage.getDocument(xHandle[7])
aDoc.writeDocument("## %s\n\n" % theProject.tr("New Chapter"))
theProject.index.reIndexHandle(xHandle[7])
aDoc = NWDoc(theProject, xHandle[8])
aDoc = theProject.storage.getDocument(xHandle[8])
aDoc.writeDocument("### %s\n\n" % theProject.tr("New Scene"))
theProject.index.reIndexHandle(xHandle[8])