Make project instance private to main GUI class

This commit is contained in:
Veronica Berglyd Olsen
2023-08-08 17:21:00 +02:00
parent 94c95d6f67
commit 12897ff2e1
37 changed files with 445 additions and 465 deletions
+18 -18
View File
@@ -43,9 +43,9 @@ class NWProjectData:
the list of project items. the list of project items.
""" """
def __init__(self, theProject): def __init__(self, project):
self.theProject = theProject self._project = project
# Project Meta # Project Meta
self._uuid = "" self._uuid = ""
@@ -187,13 +187,13 @@ class NWProjectData:
def incSaveCount(self): def incSaveCount(self):
"""Increment the save count by one.""" """Increment the save count by one."""
self._saveCount += 1 self._saveCount += 1
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def incAutoCount(self): def incAutoCount(self):
"""Increment the auto save count by one.""" """Increment the auto save count by one."""
self._autoCount += 1 self._autoCount += 1
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
## ##
@@ -215,74 +215,74 @@ class NWProjectData:
self._uuid = str(uuid.uuid4()) self._uuid = str(uuid.uuid4())
elif value != self._uuid: elif value != self._uuid:
self._uuid = value self._uuid = value
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def setName(self, value: str | None): def setName(self, value: str | None):
"""Set a new project name.""" """Set a new project name."""
if value != self._name: if value != self._name:
self._name = simplified(str(value or "")) self._name = simplified(str(value or ""))
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def setTitle(self, value: str | None): def setTitle(self, value: str | None):
"""Set a new novel title.""" """Set a new novel title."""
if value != self._title: if value != self._title:
self._title = simplified(str(value or "")) self._title = simplified(str(value or ""))
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def setAuthor(self, value: str | None): def setAuthor(self, value: str | None):
"""Set the author value.""" """Set the author value."""
if value != self._title: if value != self._title:
self._author = simplified(str(value or "")) self._author = simplified(str(value or ""))
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def setSaveCount(self, value: Any): def setSaveCount(self, value: Any):
"""Set the save count from last session.""" """Set the save count from last session."""
self._saveCount = checkInt(value, 0) self._saveCount = checkInt(value, 0)
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def setAutoCount(self, value: Any): def setAutoCount(self, value: Any):
"""Set the auto save count from last session.""" """Set the auto save count from last session."""
self._autoCount = checkInt(value, 0) self._autoCount = checkInt(value, 0)
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def setEditTime(self, value: Any): def setEditTime(self, value: Any):
"""Set the edit time from last session.""" """Set the edit time from last session."""
self._editTime = checkInt(value, 0) self._editTime = checkInt(value, 0)
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def setDoBackup(self, value: Any): def setDoBackup(self, value: Any):
"""Set the do write backup flag.""" """Set the do write backup flag."""
if value != self._doBackup: if value != self._doBackup:
self._doBackup = checkBool(value, False) self._doBackup = checkBool(value, False)
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def setLanguage(self, value: str | None): def setLanguage(self, value: str | None):
"""Set the project language.""" """Set the project language."""
if value != self._language: if value != self._language:
self._language = checkStringNone(value, None) self._language = checkStringNone(value, None)
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def setSpellCheck(self, value: Any): def setSpellCheck(self, value: Any):
"""Set the spell check flag.""" """Set the spell check flag."""
if value != self._spellCheck: if value != self._spellCheck:
self._spellCheck = checkBool(value, False) self._spellCheck = checkBool(value, False)
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def setSpellLang(self, value: str | None): def setSpellLang(self, value: str | None):
"""Set the spell check language.""" """Set the spell check language."""
if value != self._spellLang: if value != self._spellLang:
self._spellLang = checkStringNone(value, None) self._spellLang = checkStringNone(value, None)
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def setLastHandle(self, value: str | None, component: str): def setLastHandle(self, value: str | None, component: str):
@@ -291,7 +291,7 @@ class NWProjectData:
""" """
if isinstance(component, str): if isinstance(component, str):
self._lastHandle[component] = checkStringNone(value, None) self._lastHandle[component] = checkStringNone(value, None)
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def setLastHandles(self, value: dict): def setLastHandles(self, value: dict):
@@ -302,7 +302,7 @@ class NWProjectData:
for key, entry in value.items(): for key, entry in value.items():
if key in self._lastHandle: if key in self._lastHandle:
self._lastHandle[key] = str(entry) if isHandle(entry) else None self._lastHandle[key] = str(entry) if isHandle(entry) else None
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
def setInitCounts(self, novel: Any = None, notes: Any = None): def setInitCounts(self, novel: Any = None, notes: Any = None):
@@ -330,7 +330,7 @@ class NWProjectData:
for key, entry in value.items(): for key, entry in value.items():
if isinstance(entry, str): if isinstance(entry, str):
self._autoReplace[key] = simplified(entry) self._autoReplace[key] = simplified(entry)
self.theProject.setProjectChanged(True) self._project.setProjectChanged(True)
return return
# END Class NWProjectData # END Class NWProjectData
+2 -3
View File
@@ -49,8 +49,7 @@ class GuiDocMerge(QDialog):
logger.debug("Create: GuiDocMerge") logger.debug("Create: GuiDocMerge")
self.setObjectName("GuiDocMerge") self.setObjectName("GuiDocMerge")
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
self._data = {} self._data = {}
@@ -156,7 +155,7 @@ class GuiDocMerge(QDialog):
self.listBox.clear() self.listBox.clear()
for tHandle in itemList: for tHandle in itemList:
nwItem = self.theProject.tree[tHandle] nwItem = self.mainGui.project.tree[tHandle]
if nwItem is None or not nwItem.isFileType(): if nwItem is None or not nwItem.isFileType():
continue continue
+5 -6
View File
@@ -51,8 +51,7 @@ class GuiDocSplit(QDialog):
logger.debug("Create: GuiDocSplit") logger.debug("Create: GuiDocSplit")
self.setObjectName("GuiDocSplit") self.setObjectName("GuiDocSplit")
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
self._data = {} self._data = {}
self._text = [] self._text = []
@@ -71,7 +70,7 @@ class GuiDocSplit(QDialog):
vSp = CONFIG.pxInt(8) vSp = CONFIG.pxInt(8)
bSp = CONFIG.pxInt(12) bSp = CONFIG.pxInt(12)
pOptions = self.theProject.options pOptions = self.mainGui.project.options
spLevel = pOptions.getInt("GuiDocSplit", "spLevel", 3) spLevel = pOptions.getInt("GuiDocSplit", "spLevel", 3)
intoFolder = pOptions.getBool("GuiDocSplit", "intoFolder", True) intoFolder = pOptions.getBool("GuiDocSplit", "intoFolder", True)
docHierarchy = pOptions.getBool("GuiDocSplit", "docHierarchy", True) docHierarchy = pOptions.getBool("GuiDocSplit", "docHierarchy", True)
@@ -170,7 +169,7 @@ class GuiDocSplit(QDialog):
self._data["docHierarchy"] = docHierarchy self._data["docHierarchy"] = docHierarchy
self._data["moveToTrash"] = moveToTrash self._data["moveToTrash"] = moveToTrash
pOptions = self.theProject.options pOptions = self.mainGui.project.options
pOptions.setValue("GuiDocSplit", "spLevel", spLevel) pOptions.setValue("GuiDocSplit", "spLevel", spLevel)
pOptions.setValue("GuiDocSplit", "intoFolder", intoFolder) pOptions.setValue("GuiDocSplit", "intoFolder", intoFolder)
pOptions.setValue("GuiDocSplit", "docHierarchy", docHierarchy) pOptions.setValue("GuiDocSplit", "docHierarchy", docHierarchy)
@@ -200,13 +199,13 @@ class GuiDocSplit(QDialog):
self.listBox.clear() self.listBox.clear()
nwItem = self.theProject.tree[sHandle] nwItem = self.mainGui.project.tree[sHandle]
if nwItem is None or not nwItem.isFileType(): if nwItem is None or not nwItem.isFileType():
return return
spLevel = self.splitLevel.currentData() spLevel = self.splitLevel.currentData()
if not self._text: if not self._text:
inDoc = self.theProject.storage.getDocument(sHandle) inDoc = self.mainGui.project.storage.getDocument(sHandle)
self._text = (inDoc.readDocument() or "").splitlines() self._text = (inDoc.readDocument() or "").splitlines()
for lineNo, aLine in enumerate(self._text): for lineNo, aLine in enumerate(self._text):
+1 -2
View File
@@ -49,8 +49,7 @@ class GuiPreferences(NPagedDialog):
logger.debug("Create: GuiPreferences") logger.debug("Create: GuiPreferences")
self.setObjectName("GuiPreferences") self.setObjectName("GuiPreferences")
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
self.setWindowTitle(self.tr("Preferences")) self.setWindowTitle(self.tr("Preferences"))
+20 -22
View File
@@ -51,14 +51,13 @@ class GuiProjectDetails(NPagedDialog):
logger.debug("Create: GuiProjectDetails") logger.debug("Create: GuiProjectDetails")
self.setObjectName("GuiProjectDetails") self.setObjectName("GuiProjectDetails")
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
self.setWindowTitle(self.tr("Project Details")) self.setWindowTitle(self.tr("Project Details"))
wW = CONFIG.pxInt(600) wW = CONFIG.pxInt(600)
wH = CONFIG.pxInt(400) wH = CONFIG.pxInt(400)
pOptions = self.theProject.options pOptions = self.mainGui.project.options
self.setMinimumWidth(wW) self.setMinimumWidth(wW)
self.setMinimumHeight(wH) self.setMinimumHeight(wH)
@@ -67,8 +66,8 @@ class GuiProjectDetails(NPagedDialog):
CONFIG.pxInt(pOptions.getInt("GuiProjectDetails", "winHeight", wH)) CONFIG.pxInt(pOptions.getInt("GuiProjectDetails", "winHeight", wH))
) )
self.tabMain = GuiProjectDetailsMain(self.mainGui, self.theProject) self.tabMain = GuiProjectDetailsMain(self.mainGui)
self.tabContents = GuiProjectDetailsContents(self.mainGui, self.theProject) self.tabContents = GuiProjectDetailsContents(self.mainGui)
self.addTab(self.tabMain, self.tr("Overview")) self.addTab(self.tabMain, self.tr("Overview"))
self.addTab(self.tabContents, self.tr("Contents")) self.addTab(self.tabContents, self.tr("Contents"))
@@ -125,7 +124,7 @@ class GuiProjectDetails(NPagedDialog):
countFrom = self.tabContents.poValue.value() countFrom = self.tabContents.poValue.value()
clearDouble = self.tabContents.dblValue.isChecked() clearDouble = self.tabContents.dblValue.isChecked()
pOptions = self.theProject.options pOptions = self.mainGui.project.options
pOptions.setValue("GuiProjectDetails", "winWidth", winWidth) pOptions.setValue("GuiProjectDetails", "winWidth", winWidth)
pOptions.setValue("GuiProjectDetails", "winHeight", winHeight) pOptions.setValue("GuiProjectDetails", "winHeight", winHeight)
pOptions.setValue("GuiProjectDetails", "widthCol0", widthCol0) pOptions.setValue("GuiProjectDetails", "widthCol0", widthCol0)
@@ -144,11 +143,10 @@ class GuiProjectDetails(NPagedDialog):
class GuiProjectDetailsMain(QWidget): class GuiProjectDetailsMain(QWidget):
def __init__(self, mainGui, theProject): def __init__(self, mainGui):
super().__init__(parent=mainGui) super().__init__(parent=mainGui)
self.theProject = theProject self.mainGui = mainGui
self.mainGui = mainGui
fPx = CONFIG.theme.fontPixelSize fPx = CONFIG.theme.fontPixelSize
fPt = CONFIG.theme.fontPointSize fPt = CONFIG.theme.fontPointSize
@@ -246,22 +244,23 @@ class GuiProjectDetailsMain(QWidget):
def updateValues(self): def updateValues(self):
"""Set all the values. """Set all the values.
""" """
pIndex = self.theProject.index project = self.mainGui.project
pIndex = project.index
hCounts = pIndex.getNovelTitleCounts() hCounts = pIndex.getNovelTitleCounts()
nwCount = pIndex.getNovelWordCount() nwCount = pIndex.getNovelWordCount()
edTime = self.theProject.getCurrentEditTime() edTime = project.getCurrentEditTime()
self.bookTitle.setText(self.theProject.data.title or self.theProject.data.name) self.bookTitle.setText(project.data.title or project.data.name)
self.projName.setText(self.tr("Project: {0}").format(self.theProject.data.name)) self.projName.setText(self.tr("Project: {0}").format(project.data.name))
self.bookAuthors.setText(self.tr("By {0}").format(self.theProject.data.author)) self.bookAuthors.setText(self.tr("By {0}").format(project.data.author))
self.wordCountVal.setText(f"{nwCount:n}") self.wordCountVal.setText(f"{nwCount:n}")
self.chapCountVal.setText(f"{hCounts[2]:n}") self.chapCountVal.setText(f"{hCounts[2]:n}")
self.sceneCountVal.setText(f"{hCounts[3]:n}") self.sceneCountVal.setText(f"{hCounts[3]:n}")
self.revCountVal.setText(f"{self.theProject.data.saveCount:n}") self.revCountVal.setText(f"{project.data.saveCount:n}")
self.editTimeVal.setText(formatTime(edTime)) self.editTimeVal.setText(formatTime(edTime))
self.projPathVal.setText(str(self.theProject.storage.storagePath)) self.projPathVal.setText(str(project.storage.storagePath))
return return
@@ -276,11 +275,10 @@ class GuiProjectDetailsContents(QWidget):
C_PAGE = 3 C_PAGE = 3
C_PROG = 4 C_PROG = 4
def __init__(self, mainGui, theProject): def __init__(self, mainGui):
super().__init__(parent=mainGui) super().__init__(parent=mainGui)
self.theProject = theProject self.mainGui = mainGui
self.mainGui = mainGui
# Internal # Internal
self._theToC = [] self._theToC = []
@@ -289,14 +287,14 @@ class GuiProjectDetailsContents(QWidget):
iPx = CONFIG.theme.baseIconSize iPx = CONFIG.theme.baseIconSize
hPx = CONFIG.pxInt(12) hPx = CONFIG.pxInt(12)
vPx = CONFIG.pxInt(4) vPx = CONFIG.pxInt(4)
pOptions = self.theProject.options pOptions = self.mainGui.project.options
# Header # Header
# ====== # ======
self.tocLabel = QLabel("<b>%s</b>" % self.tr("Table of Contents")) self.tocLabel = QLabel("<b>%s</b>" % self.tr("Table of Contents"))
self.novelValue = NovelSelector(self, self.theProject, self.mainGui) self.novelValue = NovelSelector(self, self.mainGui)
self.novelValue.setMinimumWidth(CONFIG.pxInt(200)) self.novelValue.setMinimumWidth(CONFIG.pxInt(200))
self.novelValue.novelSelectionChanged.connect(self._novelValueChanged) self.novelValue.novelSelectionChanged.connect(self._novelValueChanged)
@@ -445,7 +443,7 @@ class GuiProjectDetailsContents(QWidget):
"""Extract the information from the project index. """Extract the information from the project index.
""" """
logger.debug("Populating ToC from handle '%s'", rootHandle) logger.debug("Populating ToC from handle '%s'", rootHandle)
self._theToC = self.theProject.index.getTableOfContents(rootHandle, 2) self._theToC = self.mainGui.project.index.getTableOfContents(rootHandle, 2)
self._theToC.append(("", 0, self.tr("END"), 0)) self._theToC.append(("", 0, self.tr("END"), 0))
return return
+29 -32
View File
@@ -60,15 +60,13 @@ class GuiProjectSettings(NPagedDialog):
logger.debug("Create: GuiProjectSettings") logger.debug("Create: GuiProjectSettings")
self.setObjectName("GuiProjectSettings") self.setObjectName("GuiProjectSettings")
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject self.mainGui.project.countStatus()
self.theProject.countStatus()
self.setWindowTitle(self.tr("Project Settings")) self.setWindowTitle(self.tr("Project Settings"))
wW = CONFIG.pxInt(570) wW = CONFIG.pxInt(570)
wH = CONFIG.pxInt(375) wH = CONFIG.pxInt(375)
pOptions = self.theProject.options pOptions = self.mainGui.project.options
self.setMinimumWidth(wW) self.setMinimumWidth(wW)
self.setMinimumHeight(wH) self.setMinimumHeight(wH)
@@ -117,34 +115,35 @@ class GuiProjectSettings(NPagedDialog):
def _doSave(self): def _doSave(self):
"""Save settings and close dialog. """Save settings and close dialog.
""" """
project = self.mainGui.project
projName = self.tabMain.editName.text() projName = self.tabMain.editName.text()
bookTitle = self.tabMain.editTitle.text() bookTitle = self.tabMain.editTitle.text()
bookAuthor = self.tabMain.editAuthor.text() bookAuthor = self.tabMain.editAuthor.text()
spellLang = self.tabMain.spellLang.currentData() spellLang = self.tabMain.spellLang.currentData()
doBackup = not self.tabMain.doBackup.isChecked() doBackup = not self.tabMain.doBackup.isChecked()
self.theProject.data.setName(projName) project.data.setName(projName)
self.theProject.data.setTitle(bookTitle) project.data.setTitle(bookTitle)
self.theProject.data.setAuthor(bookAuthor) project.data.setAuthor(bookAuthor)
self.theProject.data.setDoBackup(doBackup) project.data.setDoBackup(doBackup)
# Remember this as updating spell dictionary can be expensive # Remember this as updating spell dictionary can be expensive
self._spellChanged = self.theProject.data.setSpellLang(spellLang) self._spellChanged = project.data.setSpellLang(spellLang)
if self.tabStatus.colChanged: if self.tabStatus.colChanged:
newList, delList = self.tabStatus.getNewList() newList, delList = self.tabStatus.getNewList()
self.theProject.setStatusColours(newList, delList) project.setStatusColours(newList, delList)
if self.tabImport.colChanged: if self.tabImport.colChanged:
newList, delList = self.tabImport.getNewList() newList, delList = self.tabImport.getNewList()
self.theProject.setImportColours(newList, delList) project.setImportColours(newList, delList)
if self.tabStatus.colChanged or self.tabImport.colChanged: if self.tabStatus.colChanged or self.tabImport.colChanged:
self.mainGui.rebuildTrees() self.mainGui.rebuildTrees()
if self.tabReplace.arChanged: if self.tabReplace.arChanged:
newList = self.tabReplace.getNewList() newList = self.tabReplace.getNewList()
self.theProject.data.setAutoReplace(newList) project.data.setAutoReplace(newList)
self._saveGuiSettings() self._saveGuiSettings()
self.accept() self.accept()
@@ -184,7 +183,7 @@ class GuiProjectSettings(NPagedDialog):
statusColW = CONFIG.rpxInt(self.tabStatus.listBox.columnWidth(0)) statusColW = CONFIG.rpxInt(self.tabStatus.listBox.columnWidth(0))
importColW = CONFIG.rpxInt(self.tabImport.listBox.columnWidth(0)) importColW = CONFIG.rpxInt(self.tabImport.listBox.columnWidth(0))
pOptions = self.theProject.options pOptions = self.mainGui.project.options
pOptions.setValue("GuiProjectSettings", "winWidth", winWidth) pOptions.setValue("GuiProjectSettings", "winWidth", winWidth)
pOptions.setValue("GuiProjectSettings", "winHeight", winHeight) pOptions.setValue("GuiProjectSettings", "winHeight", winHeight)
pOptions.setValue("GuiProjectSettings", "replaceColW", replaceColW) pOptions.setValue("GuiProjectSettings", "replaceColW", replaceColW)
@@ -201,8 +200,7 @@ class GuiProjectEditMain(QWidget):
def __init__(self, projGui): def __init__(self, projGui):
super().__init__(parent=projGui) super().__init__(parent=projGui)
self.mainGui = projGui.mainGui self.mainGui = projGui.mainGui
self.theProject = projGui.theProject
# The Form # The Form
self.mainForm = NConfigLayout() self.mainForm = NConfigLayout()
@@ -212,11 +210,12 @@ class GuiProjectEditMain(QWidget):
self.mainForm.addGroupLabel(self.tr("Project Settings")) self.mainForm.addGroupLabel(self.tr("Project Settings"))
xW = CONFIG.pxInt(250) xW = CONFIG.pxInt(250)
pData = self.mainGui.project.data
self.editName = QLineEdit() self.editName = QLineEdit()
self.editName.setMaxLength(200) self.editName.setMaxLength(200)
self.editName.setMaximumWidth(xW) self.editName.setMaximumWidth(xW)
self.editName.setText(self.theProject.data.name) self.editName.setText(pData.name)
self.mainForm.addRow( self.mainForm.addRow(
self.tr("Project name"), self.tr("Project name"),
self.editName, self.editName,
@@ -226,7 +225,7 @@ class GuiProjectEditMain(QWidget):
self.editTitle = QLineEdit() self.editTitle = QLineEdit()
self.editTitle.setMaxLength(200) self.editTitle.setMaxLength(200)
self.editTitle.setMaximumWidth(xW) self.editTitle.setMaximumWidth(xW)
self.editTitle.setText(self.theProject.data.title) self.editTitle.setText(pData.title)
self.mainForm.addRow( self.mainForm.addRow(
self.tr("Novel title"), self.tr("Novel title"),
self.editTitle, self.editTitle,
@@ -236,7 +235,7 @@ class GuiProjectEditMain(QWidget):
self.editAuthor = QLineEdit() self.editAuthor = QLineEdit()
self.editAuthor.setMaxLength(200) self.editAuthor.setMaxLength(200)
self.editAuthor.setMaximumWidth(xW) self.editAuthor.setMaximumWidth(xW)
self.editAuthor.setText(self.theProject.data.author) self.editAuthor.setText(pData.author)
self.mainForm.addRow( self.mainForm.addRow(
self.tr("Author(s)"), self.tr("Author(s)"),
self.editAuthor, self.editAuthor,
@@ -259,13 +258,13 @@ class GuiProjectEditMain(QWidget):
) )
spellIdx = 0 spellIdx = 0
if self.theProject.data.spellLang is not None: if pData.spellLang is not None:
spellIdx = self.spellLang.findData(self.theProject.data.spellLang) spellIdx = self.spellLang.findData(pData.spellLang)
if spellIdx != -1: if spellIdx != -1:
self.spellLang.setCurrentIndex(spellIdx) self.spellLang.setCurrentIndex(spellIdx)
self.doBackup = NSwitch(self) self.doBackup = NSwitch(self)
self.doBackup.setChecked(not self.theProject.data.doBackup) self.doBackup.setChecked(not pData.doBackup)
self.mainForm.addRow( self.mainForm.addRow(
self.tr("No backup on close"), self.tr("No backup on close"),
self.doBackup, self.doBackup,
@@ -289,20 +288,19 @@ class GuiProjectEditStatus(QWidget):
def __init__(self, projGui, isStatus): def __init__(self, projGui, isStatus):
super().__init__(parent=projGui) super().__init__(parent=projGui)
self.mainGui = projGui.mainGui self.mainGui = projGui.mainGui
self.theProject = projGui.theProject
if isStatus: if isStatus:
self.theStatus = self.theProject.data.itemStatus self.theStatus = self.mainGui.project.data.itemStatus
pageLabel = self.tr("Novel File Status Levels") pageLabel = self.tr("Novel File Status Levels")
colSetting = "statusColW" colSetting = "statusColW"
else: else:
self.theStatus = self.theProject.data.itemImport self.theStatus = self.mainGui.project.data.itemImport
pageLabel = self.tr("Note File Importance Levels") pageLabel = self.tr("Note File Importance Levels")
colSetting = "importColW" colSetting = "importColW"
wCol0 = CONFIG.pxInt( wCol0 = CONFIG.pxInt(
self.theProject.options.getInt("GuiProjectSettings", colSetting, 130) self.mainGui.project.options.getInt("GuiProjectSettings", colSetting, 130)
) )
self.colDeleted = [] self.colDeleted = []
@@ -576,12 +574,11 @@ class GuiProjectEditReplace(QWidget):
def __init__(self, projGui): def __init__(self, projGui):
super().__init__(parent=projGui) super().__init__(parent=projGui)
self.mainGui = projGui.mainGui self.mainGui = projGui.mainGui
self.theProject = projGui.theProject self.arChanged = False
self.arChanged = False
wCol0 = CONFIG.pxInt( wCol0 = CONFIG.pxInt(
self.theProject.options.getInt("GuiProjectSettings", "replaceColW", 130) self.mainGui.project.options.getInt("GuiProjectSettings", "replaceColW", 130)
) )
pageLabel = self.tr("Text Replace List for Preview and Export") pageLabel = self.tr("Text Replace List for Preview and Export")
@@ -597,7 +594,7 @@ class GuiProjectEditReplace(QWidget):
self.listBox.setColumnWidth(self.COL_KEY, wCol0) self.listBox.setColumnWidth(self.COL_KEY, wCol0)
self.listBox.setIndentation(0) self.listBox.setIndentation(0)
for aKey, aVal in self.theProject.data.autoReplace.items(): for aKey, aVal in self.mainGui.project.data.autoReplace.items():
newItem = QTreeWidgetItem(["<%s>" % aKey, aVal]) newItem = QTreeWidgetItem(["<%s>" % aKey, aVal])
self.listBox.addTopLevelItem(newItem) self.listBox.addTopLevelItem(newItem)
+6 -8
View File
@@ -50,16 +50,14 @@ class GuiWordList(QDialog):
logger.debug("Create: GuiWordList") logger.debug("Create: GuiWordList")
self.setObjectName("GuiWordList") self.setObjectName("GuiWordList")
self.mainGui = mainGui
self.theProject = mainGui.theProject
self.setWindowTitle(self.tr("Project Word List")) self.setWindowTitle(self.tr("Project Word List"))
self.mainGui = mainGui
mS = CONFIG.pxInt(250) mS = CONFIG.pxInt(250)
wW = CONFIG.pxInt(320) wW = CONFIG.pxInt(320)
wH = CONFIG.pxInt(340) wH = CONFIG.pxInt(340)
pOptions = self.theProject.options pOptions = self.mainGui.project.options
self.setMinimumWidth(mS) self.setMinimumWidth(mS)
self.setMinimumHeight(mS) self.setMinimumHeight(mS)
@@ -151,7 +149,7 @@ class GuiWordList(QDialog):
def _doSave(self): def _doSave(self):
"""Save the new word list and close.""" """Save the new word list and close."""
self._saveGuiSettings() self._saveGuiSettings()
userDict = UserDictionary(self.theProject) userDict = UserDictionary(self.mainGui.project)
for i in range(self.listBox.count()): for i in range(self.listBox.count()):
item = self.listBox.item(i) item = self.listBox.item(i)
if isinstance(item, QListWidgetItem): if isinstance(item, QListWidgetItem):
@@ -174,7 +172,7 @@ class GuiWordList(QDialog):
def _loadWordList(self): def _loadWordList(self):
"""Load the project's word list, if it exists.""" """Load the project's word list, if it exists."""
userDict = UserDictionary(self.theProject) userDict = UserDictionary(self.mainGui.project)
userDict.load() userDict.load()
self.listBox.clear() self.listBox.clear()
for word in userDict: for word in userDict:
@@ -187,7 +185,7 @@ class GuiWordList(QDialog):
winWidth = CONFIG.rpxInt(self.width()) winWidth = CONFIG.rpxInt(self.width())
winHeight = CONFIG.rpxInt(self.height()) winHeight = CONFIG.rpxInt(self.height())
pOptions = self.theProject.options pOptions = self.mainGui.project.options
pOptions.setValue("GuiWordList", "winWidth", winWidth) pOptions.setValue("GuiWordList", "winWidth", winWidth)
pOptions.setValue("GuiWordList", "winHeight", winHeight) pOptions.setValue("GuiWordList", "winHeight", winHeight)
+2 -3
View File
@@ -41,11 +41,10 @@ class NovelSelector(QComboBox):
novelSelectionChanged = pyqtSignal(str) novelSelectionChanged = pyqtSignal(str)
def __init__(self, parent, project, mainGui): def __init__(self, parent, mainGui):
super().__init__(parent=parent) super().__init__(parent=parent)
self._mainGui = mainGui self._mainGui = mainGui
self._project = project
self._blockSignal = False self._blockSignal = False
self._firstHandle = None self._firstHandle = None
@@ -91,7 +90,7 @@ class NovelSelector(QComboBox):
icon = CONFIG.theme.getIcon(nwLabels.CLASS_ICON[nwItemClass.NOVEL]) icon = CONFIG.theme.getIcon(nwLabels.CLASS_ICON[nwItemClass.NOVEL])
handle = self.currentData() handle = self.currentData()
for tHandle, nwItem in self._project.tree.iterRoots(nwItemClass.NOVEL): for tHandle, nwItem in self._mainGui.project.tree.iterRoots(nwItemClass.NOVEL):
if prefix: if prefix:
name = prefix.format(nwItem.itemName) name = prefix.format(nwItem.itemName)
self.addItem(name, tHandle) self.addItem(name, tHandle)
+21 -24
View File
@@ -84,8 +84,7 @@ class GuiDocEditor(QTextEdit):
logger.debug("Create: GuiDocEditor") logger.debug("Create: GuiDocEditor")
# Class Variables # Class Variables
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
self._nwDocument = None self._nwDocument = None
self._nwItem = None self._nwItem = None
@@ -133,7 +132,7 @@ class GuiDocEditor(QTextEdit):
self.docSearch = GuiDocEditSearch(self) self.docSearch = GuiDocEditSearch(self)
# Syntax # Syntax
self.spEnchant = NWSpellEnchant(self.theProject) self.spEnchant = NWSpellEnchant(self.mainGui.project)
self.highLight = GuiDocHighlighter(qDoc, self.mainGui, self.spEnchant) self.highLight = GuiDocHighlighter(qDoc, self.mainGui, self.spEnchant)
# Context Menu # Context Menu
@@ -341,7 +340,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.
""" """
self._nwDocument = self.theProject.storage.getDocument(tHandle) self._nwDocument = self.mainGui.project.storage.getDocument(tHandle)
self._nwItem = self._nwDocument.getCurrentItem() self._nwItem = self._nwDocument.getCurrentItem()
theDoc = self._nwDocument.readDocument() theDoc = self._nwDocument.readDocument()
@@ -517,10 +516,10 @@ class GuiDocEditor(QTextEdit):
self.setDocumentChanged(False) self.setDocumentChanged(False)
oldHeader = self._nwItem.mainHeading oldHeader = self._nwItem.mainHeading
oldCount = self.theProject.index.getHandleHeaderCount(tHandle) oldCount = self.mainGui.project.index.getHandleHeaderCount(tHandle)
self.theProject.index.scanText(tHandle, docText) self.mainGui.project.index.scanText(tHandle, docText)
newHeader = self._nwItem.mainHeading newHeader = self._nwItem.mainHeading
newCount = self.theProject.index.getHandleHeaderCount(tHandle) newCount = self.mainGui.project.index.getHandleHeaderCount(tHandle)
if self._nwItem.itemClass == nwItemClass.NOVEL: if self._nwItem.itemClass == nwItemClass.NOVEL:
if oldCount == newCount: if oldCount == newCount:
@@ -699,10 +698,10 @@ class GuiDocEditor(QTextEdit):
"""Set the spell checker dictionary language, and emit the """Set the spell checker dictionary language, and emit the
dictionary changed signal. dictionary changed signal.
""" """
if self.theProject.data.spellLang is None: if self.mainGui.project.data.spellLang is None:
theLang = CONFIG.spellLanguage theLang = CONFIG.spellLanguage
else: else:
theLang = self.theProject.data.spellLang theLang = self.mainGui.project.data.spellLang
self.spEnchant.setLanguage(theLang) self.spEnchant.setLanguage(theLang)
_, theProvider = self.spEnchant.describeDict() _, theProvider = self.spEnchant.describeDict()
@@ -735,7 +734,7 @@ class GuiDocEditor(QTextEdit):
self._spellCheck = theMode self._spellCheck = theMode
self.mainGui.mainMenu.setSpellCheck(theMode) self.mainGui.mainMenu.setSpellCheck(theMode)
self.theProject.data.setSpellCheck(theMode) self.mainGui.project.data.setSpellCheck(theMode)
self.highLight.setSpellCheck(theMode) self.highLight.setSpellCheck(theMode)
if not self._bigDoc or theMode is False: if not self._bigDoc or theMode is False:
# We don't run the spell checker automatically on big docs # We don't run the spell checker automatically on big docs
@@ -1917,7 +1916,7 @@ class GuiDocEditor(QTextEdit):
if theText.startswith("@"): if theText.startswith("@"):
isGood, tBits, tPos = self.theProject.index.scanThis(theText) isGood, tBits, tPos = self.mainGui.project.index.scanThis(theText)
if not isGood: if not isGood:
return False return False
@@ -2222,9 +2221,8 @@ class GuiDocEditSearch(QFrame):
logger.debug("Create: GuiDocEditSearch") logger.debug("Create: GuiDocEditSearch")
self.docEditor = docEditor self.docEditor = docEditor
self.mainGui = docEditor.mainGui self.mainGui = docEditor.mainGui
self.theProject = docEditor.theProject
self.repVisible = False self.repVisible = False
self.isCaseSense = CONFIG.searchCase self.isCaseSense = CONFIG.searchCase
@@ -2636,9 +2634,8 @@ class GuiDocEditHeader(QWidget):
logger.debug("Create: GuiDocEditHeader") logger.debug("Create: GuiDocEditHeader")
self.docEditor = docEditor self.docEditor = docEditor
self.mainGui = docEditor.mainGui self.mainGui = docEditor.mainGui
self.theProject = docEditor.theProject
self._docHandle = None self._docHandle = None
@@ -2775,17 +2772,18 @@ class GuiDocEditHeader(QWidget):
self.minmaxButton.setVisible(False) self.minmaxButton.setVisible(False)
return True return True
pTree = self.mainGui.project.tree
if CONFIG.showFullPath: if CONFIG.showFullPath:
tTitle = [] tTitle = []
tTree = self.theProject.tree.getItemPath(tHandle) tTree = pTree.getItemPath(tHandle)
for aHandle in reversed(tTree): for aHandle in reversed(tTree):
nwItem = self.theProject.tree[aHandle] nwItem = pTree[aHandle]
if nwItem is not None: if nwItem is not None:
tTitle.append(nwItem.itemName) tTitle.append(nwItem.itemName)
sSep = " %s " % nwUnicode.U_RSAQUO sSep = " %s " % nwUnicode.U_RSAQUO
self.theTitle.setText(sSep.join(tTitle)) self.theTitle.setText(sSep.join(tTitle))
else: else:
nwItem = self.theProject.tree[tHandle] nwItem = pTree[tHandle]
if nwItem is None: if nwItem is None:
return False return False
self.theTitle.setText(nwItem.itemName) self.theTitle.setText(nwItem.itemName)
@@ -2870,9 +2868,8 @@ class GuiDocEditFooter(QWidget):
logger.debug("Create: GuiDocEditFooter") logger.debug("Create: GuiDocEditFooter")
self.docEditor = docEditor self.docEditor = docEditor
self.mainGui = docEditor.mainGui self.mainGui = docEditor.mainGui
self.theProject = docEditor.theProject
self._theItem = None self._theItem = None
self._docHandle = None self._docHandle = None
@@ -3003,7 +3000,7 @@ class GuiDocEditFooter(QWidget):
logger.debug("No handle set, so clearing the editor footer") logger.debug("No handle set, so clearing the editor footer")
self._theItem = None self._theItem = None
else: else:
self._theItem = self.theProject.tree[self._docHandle] self._theItem = self.mainGui.project.tree[self._docHandle]
self.setHasSelection(False) self.setHasSelection(False)
self.updateInfo() self.updateInfo()
+2 -3
View File
@@ -54,7 +54,6 @@ class GuiDocHighlighter(QSyntaxHighlighter):
self.theDoc = theDoc self.theDoc = theDoc
self.spEnchant = spEnchant self.spEnchant = spEnchant
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
self.theHandle = None self.theHandle = None
self.spellCheck = False self.spellCheck = False
self.spellRx = None self.spellRx = None
@@ -286,8 +285,8 @@ class GuiDocHighlighter(QSyntaxHighlighter):
if theText.startswith("@"): # Keywords and commands if theText.startswith("@"): # Keywords and commands
self.setCurrentBlockState(self.BLOCK_META) self.setCurrentBlockState(self.BLOCK_META)
pIndex = self.theProject.index pIndex = self.mainGui.project.index
tItem = self.mainGui.theProject.tree[self.theHandle] tItem = self.mainGui.project.tree[self.theHandle]
isValid, theBits, thePos = pIndex.scanThis(theText) isValid, theBits, thePos = pIndex.scanThis(theText)
isGood = pIndex.checkThese(theBits, tItem) isGood = pIndex.checkThese(theBits, tItem)
if isValid: if isValid:
+13 -15
View File
@@ -59,8 +59,7 @@ class GuiDocViewer(QTextBrowser):
logger.debug("Create: GuiDocViewer") logger.debug("Create: GuiDocViewer")
# Class Variables # Class Variables
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
# Internal Variables # Internal Variables
self._docHandle = None self._docHandle = None
@@ -163,7 +162,7 @@ class GuiDocViewer(QTextBrowser):
def loadText(self, tHandle, updateHistory=True): def loadText(self, tHandle, updateHistory=True):
"""Load text into the viewer from an item handle. """Load text into the viewer from an item handle.
""" """
if not self.theProject.tree.checkType(tHandle, nwItemType.FILE): if not self.mainGui.project.tree.checkType(tHandle, nwItemType.FILE):
logger.warning("Item not found") logger.warning("Item not found")
return False return False
@@ -171,7 +170,7 @@ class GuiDocViewer(QTextBrowser):
qApp.setOverrideCursor(QCursor(Qt.WaitCursor)) qApp.setOverrideCursor(QCursor(Qt.WaitCursor))
sPos = self.verticalScrollBar().value() sPos = self.verticalScrollBar().value()
aDoc = ToHtml(self.theProject) aDoc = ToHtml(self.mainGui.project)
aDoc.setPreview(CONFIG.viewComments, CONFIG.viewSynopsis) aDoc.setPreview(CONFIG.viewComments, CONFIG.viewSynopsis)
aDoc.setLinkHeaders(True) aDoc.setLinkHeaders(True)
@@ -211,7 +210,7 @@ class GuiDocViewer(QTextBrowser):
self.verticalScrollBar().setValue(sPos) self.verticalScrollBar().setValue(sPos)
self._docHandle = tHandle self._docHandle = tHandle
self.theProject._data.setLastHandle(tHandle, "viewer") self.mainGui.project.data.setLastHandle(tHandle, "viewer")
self.docHeader.setTitleFromHandle(self._docHandle) self.docHeader.setTitleFromHandle(self._docHandle)
self.updateDocMargins() self.updateDocMargins()
@@ -680,9 +679,8 @@ class GuiDocViewHeader(QWidget):
logger.debug("Create: GuiDocViewHeader") logger.debug("Create: GuiDocViewHeader")
self.docViewer = docViewer self.docViewer = docViewer
self.mainGui = docViewer.mainGui self.mainGui = docViewer.mainGui
self.theProject = docViewer.theProject
# Internal Variables # Internal Variables
self._docHandle = None self._docHandle = None
@@ -821,17 +819,18 @@ class GuiDocViewHeader(QWidget):
self.refreshButton.setVisible(False) self.refreshButton.setVisible(False)
return True return True
pTree = self.mainGui.project.tree
if CONFIG.showFullPath: if CONFIG.showFullPath:
tTitle = [] tTitle = []
tTree = self.theProject.tree.getItemPath(tHandle) tTree = pTree.getItemPath(tHandle)
for aHandle in reversed(tTree): for aHandle in reversed(tTree):
nwItem = self.theProject.tree[aHandle] nwItem = pTree[aHandle]
if nwItem is not None: if nwItem is not None:
tTitle.append(nwItem.itemName) tTitle.append(nwItem.itemName)
sSep = " %s " % nwUnicode.U_RSAQUO sSep = " %s " % nwUnicode.U_RSAQUO
self.theTitle.setText(sSep.join(tTitle)) self.theTitle.setText(sSep.join(tTitle))
else: else:
nwItem = self.theProject.tree[tHandle] nwItem = pTree[tHandle]
if nwItem is None: if nwItem is None:
return False return False
self.theTitle.setText(nwItem.itemName) self.theTitle.setText(nwItem.itemName)
@@ -1138,8 +1137,7 @@ class GuiDocViewDetails(QScrollArea):
logger.debug("Create: GuiDocViewDetails") logger.debug("Create: GuiDocViewDetails")
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
self.refList = QLabel("") self.refList = QLabel("")
self.refList.setWordWrap(True) self.refList.setWordWrap(True)
@@ -1174,10 +1172,10 @@ class GuiDocViewDetails(QScrollArea):
if self.mainGui.docViewer.stickyRef: if self.mainGui.docViewer.stickyRef:
return return
theRefs = self.theProject.index.getBackReferenceList(tHandle) theRefs = self.mainGui.project.index.getBackReferenceList(tHandle)
theList = [] theList = []
for tHandle in theRefs: for tHandle in theRefs:
tItem = self.theProject.tree[tHandle] tItem = self.mainGui.project.tree[tHandle]
if tItem is not None: if tItem is not None:
theList.append("<a href='%s#%s' %s>%s</a>" % ( theList.append("<a href='%s#%s' %s>%s</a>" % (
tHandle, theRefs[tHandle], self.linkStyle, tItem.itemName tHandle, theRefs[tHandle], self.linkStyle, tItem.itemName
+2 -3
View File
@@ -42,8 +42,7 @@ class GuiItemDetails(QWidget):
logger.debug("Create: GuiItemDetails") logger.debug("Create: GuiItemDetails")
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
# Internal Variables # Internal Variables
self._itemHandle = None self._itemHandle = None
@@ -234,7 +233,7 @@ class GuiItemDetails(QWidget):
self.clearDetails() self.clearDetails()
return return
nwItem = self.theProject.tree[tHandle] nwItem = self.mainGui.project.tree[tHandle]
if nwItem is None: if nwItem is None:
self.clearDetails() self.clearDetails()
return return
+13 -14
View File
@@ -51,8 +51,7 @@ class GuiMainMenu(QMenuBar):
logger.debug("Create: GuiMainMenu") logger.debug("Create: GuiMainMenu")
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
# Build Menu # Build Menu
self._buildProjectMenu() self._buildProjectMenu()
@@ -380,10 +379,10 @@ class GuiMainMenu(QMenuBar):
"""Assemble the Insert menu. """Assemble the Insert menu.
""" """
# Insert # Insert
self.insertMenu = self.addMenu(self.tr("&Insert")) self.insMenu = self.addMenu(self.tr("&Insert"))
# Insert > Dashes and Dots # Insert > Dashes and Dots
self.mInsDashes = self.insertMenu.addMenu(self.tr("Dashes")) self.mInsDashes = self.insMenu.addMenu(self.tr("Dashes"))
# Insert > Short Dash # Insert > Short Dash
self.aInsENDash = QAction(self.tr("Short Dash"), self) self.aInsENDash = QAction(self.tr("Short Dash"), self)
@@ -410,7 +409,7 @@ class GuiMainMenu(QMenuBar):
self.mInsDashes.addAction(self.aInsFigDash) self.mInsDashes.addAction(self.aInsFigDash)
# Insert > Quote Marks # Insert > Quote Marks
self.mInsQuotes = self.insertMenu.addMenu(self.tr("Quote Marks")) self.mInsQuotes = self.insMenu.addMenu(self.tr("Quote Marks"))
# Insert > Left Single Quote # Insert > Left Single Quote
self.aInsQuoteLS = QAction(self.tr("Left Single Quote"), self) self.aInsQuoteLS = QAction(self.tr("Left Single Quote"), self)
@@ -443,7 +442,7 @@ class GuiMainMenu(QMenuBar):
self.mInsQuotes.addAction(self.aInsMSApos) self.mInsQuotes.addAction(self.aInsMSApos)
# Insert > Symbols # Insert > Symbols
self.mInsPunct = self.insertMenu.addMenu(self.tr("General Punctuation")) self.mInsPunct = self.insMenu.addMenu(self.tr("General Punctuation"))
# Insert > Ellipsis # Insert > Ellipsis
self.aInsEllipsis = QAction(self.tr("Ellipsis"), self) self.aInsEllipsis = QAction(self.tr("Ellipsis"), self)
@@ -464,7 +463,7 @@ class GuiMainMenu(QMenuBar):
self.mInsPunct.addAction(self.aInsDPrime) self.mInsPunct.addAction(self.aInsDPrime)
# Insert > White Spaces # Insert > White Spaces
self.mInsSpace = self.insertMenu.addMenu(self.tr("White Spaces")) self.mInsSpace = self.insMenu.addMenu(self.tr("White Spaces"))
# Insert > Non-Breaking Space # Insert > Non-Breaking Space
self.aInsNBSpace = QAction(self.tr("Non-Breaking Space"), self) self.aInsNBSpace = QAction(self.tr("Non-Breaking Space"), self)
@@ -485,7 +484,7 @@ class GuiMainMenu(QMenuBar):
self.mInsSpace.addAction(self.aInsThinNBSpace) self.mInsSpace.addAction(self.aInsThinNBSpace)
# Insert > Symbols # Insert > Symbols
self.mInsSymbol = self.insertMenu.addMenu(self.tr("Other Symbols")) self.mInsSymbol = self.insMenu.addMenu(self.tr("Other Symbols"))
# Insert > List Bullet # Insert > List Bullet
self.aInsBullet = QAction(self.tr("List Bullet"), self) self.aInsBullet = QAction(self.tr("List Bullet"), self)
@@ -536,7 +535,7 @@ class GuiMainMenu(QMenuBar):
self.mInsSymbol.addAction(self.aInsDivide) self.mInsSymbol.addAction(self.aInsDivide)
# Insert > Tags and References # Insert > Tags and References
self.mInsKeywords = self.insertMenu.addMenu(self.tr("Tags and References")) self.mInsKeywords = self.insMenu.addMenu(self.tr("Tags and References"))
self.mInsKWItems = {} self.mInsKWItems = {}
self.mInsKWItems[nwKeyWords.TAG_KEY] = (QAction(self.mInsKeywords), "Ctrl+K, G") self.mInsKWItems[nwKeyWords.TAG_KEY] = (QAction(self.mInsKeywords), "Ctrl+K, G")
self.mInsKWItems[nwKeyWords.POV_KEY] = (QAction(self.mInsKeywords), "Ctrl+K, V") self.mInsKWItems[nwKeyWords.POV_KEY] = (QAction(self.mInsKeywords), "Ctrl+K, V")
@@ -557,7 +556,7 @@ class GuiMainMenu(QMenuBar):
self.mInsKeywords.addAction(self.mInsKWItems[keyWord][0]) self.mInsKeywords.addAction(self.mInsKWItems[keyWord][0])
# Insert > Special Comments # Insert > Special Comments
self.mInsComments = self.insertMenu.addMenu(self.tr("Special Comments")) self.mInsComments = self.insMenu.addMenu(self.tr("Special Comments"))
# Insert > Synopsis Comment # Insert > Synopsis Comment
self.aInsSynopsis = QAction(self.tr("Synopsis Comment"), self) self.aInsSynopsis = QAction(self.tr("Synopsis Comment"), self)
@@ -566,7 +565,7 @@ class GuiMainMenu(QMenuBar):
self.mInsComments.addAction(self.aInsSynopsis) self.mInsComments.addAction(self.aInsSynopsis)
# Insert > Symbols # Insert > Symbols
self.mInsBreaks = self.insertMenu.addMenu(self.tr("Page Break and Space")) self.mInsBreaks = self.insMenu.addMenu(self.tr("Page Break and Space"))
# Insert > New Page # Insert > New Page
self.aInsNewPage = QAction(self.tr("Page Break"), self) self.aInsNewPage = QAction(self.tr("Page Break"), self)
@@ -586,7 +585,7 @@ class GuiMainMenu(QMenuBar):
# Insert > Placeholder Text # Insert > Placeholder Text
self.aLipsumText = QAction(self.tr("Placeholder Text"), self) self.aLipsumText = QAction(self.tr("Placeholder Text"), self)
self.aLipsumText.triggered.connect(lambda: self.mainGui.showLoremIpsumDialog()) self.aLipsumText.triggered.connect(lambda: self.mainGui.showLoremIpsumDialog())
self.insertMenu.addAction(self.aLipsumText) self.insMenu.addAction(self.aLipsumText)
return return
@@ -796,7 +795,7 @@ class GuiMainMenu(QMenuBar):
# Tools > Check Spelling # Tools > Check Spelling
self.aSpellCheck = QAction(self.tr("Check Spelling"), self) self.aSpellCheck = QAction(self.tr("Check Spelling"), self)
self.aSpellCheck.setCheckable(True) self.aSpellCheck.setCheckable(True)
self.aSpellCheck.setChecked(self.theProject.data.spellCheck) self.aSpellCheck.setChecked(self.mainGui.project.data.spellCheck)
self.aSpellCheck.triggered.connect(self._toggleSpellCheck) # triggered, not toggled! self.aSpellCheck.triggered.connect(self._toggleSpellCheck) # triggered, not toggled!
self.aSpellCheck.setShortcut("Ctrl+F7") self.aSpellCheck.setShortcut("Ctrl+F7")
self.toolsMenu.addAction(self.aSpellCheck) self.toolsMenu.addAction(self.aSpellCheck)
@@ -826,7 +825,7 @@ class GuiMainMenu(QMenuBar):
# Tools > Backup Project # Tools > Backup Project
self.aBackupProject = QAction(self.tr("Backup Project"), self) self.aBackupProject = QAction(self.tr("Backup Project"), self)
self.aBackupProject.triggered.connect(lambda: self.theProject.backupProject(True)) self.aBackupProject.triggered.connect(lambda: self.mainGui.project.backupProject(True))
self.toolsMenu.addAction(self.aBackupProject) self.toolsMenu.addAction(self.aBackupProject)
# Tools > Build Manuscript # Tools > Build Manuscript
+24 -26
View File
@@ -66,8 +66,7 @@ class GuiNovelView(QWidget):
def __init__(self, mainGui): def __init__(self, mainGui):
super().__init__(parent=mainGui) super().__init__(parent=mainGui)
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
# Build GUI # Build GUI
self.novelTree = GuiNovelTree(self) self.novelTree = GuiNovelTree(self)
@@ -118,16 +117,16 @@ class GuiNovelView(QWidget):
def openProjectTasks(self): def openProjectTasks(self):
"""Run open project tasks. """Run open project tasks.
""" """
lastNovel = self.theProject.data.getLastHandle("novelTree") lastNovel = self.mainGui.project.data.getLastHandle("novelTree")
if lastNovel not in self.theProject.tree: if lastNovel not in self.mainGui.project.tree:
lastNovel = self.theProject.tree.findRoot(nwItemClass.NOVEL) lastNovel = self.mainGui.project.tree.findRoot(nwItemClass.NOVEL)
logger.debug("Setting novel tree to root item '%s'", lastNovel) logger.debug("Setting novel tree to root item '%s'", lastNovel)
lastCol = self.theProject.options.getEnum( lastCol = self.mainGui.project.options.getEnum(
"GuiNovelView", "lastCol", NovelTreeColumn, NovelTreeColumn.HIDDEN "GuiNovelView", "lastCol", NovelTreeColumn, NovelTreeColumn.HIDDEN
) )
lastColSize = self.theProject.options.getInt( lastColSize = self.mainGui.project.options.getInt(
"GuiNovelView", "lastColSize", 25 "GuiNovelView", "lastColSize", 25
) )
@@ -147,8 +146,9 @@ class GuiNovelView(QWidget):
""" """
lastColType = self.novelTree.lastColType lastColType = self.novelTree.lastColType
lastColSize = self.novelTree.lastColSize lastColSize = self.novelTree.lastColSize
self.theProject.options.setValue("GuiNovelView", "lastCol", lastColType) pOptions = self.mainGui.project.options
self.theProject.options.setValue("GuiNovelView", "lastColSize", lastColSize) pOptions.setValue("GuiNovelView", "lastCol", lastColType)
pOptions.setValue("GuiNovelView", "lastColSize", lastColSize)
return return
def setTreeFocus(self): def setTreeFocus(self):
@@ -170,7 +170,7 @@ class GuiNovelView(QWidget):
def refreshTree(self): def refreshTree(self):
"""Refresh the current tree. """Refresh the current tree.
""" """
self.novelTree.refreshTree(rootHandle=self.theProject.data.getLastHandle("novelTree")) self.novelTree.refreshTree(rootHandle=self.mainGui.project.data.getLastHandle("novelTree"))
return return
@pyqtSlot(str) @pyqtSlot(str)
@@ -198,9 +198,8 @@ class GuiNovelToolBar(QWidget):
logger.debug("Create: GuiNovelToolBar") logger.debug("Create: GuiNovelToolBar")
self.novelView = novelView self.novelView = novelView
self.mainGui = novelView.mainGui self.mainGui = novelView.mainGui
self.theProject = novelView.mainGui.theProject
iPx = CONFIG.theme.baseIconSize iPx = CONFIG.theme.baseIconSize
mPx = CONFIG.pxInt(2) mPx = CONFIG.pxInt(2)
@@ -212,7 +211,7 @@ class GuiNovelToolBar(QWidget):
selFont = self.font() selFont = self.font()
selFont.setWeight(QFont.Bold) selFont.setWeight(QFont.Bold)
self.novelPrefix = self.tr("Outline of {0}") self.novelPrefix = self.tr("Outline of {0}")
self.novelValue = NovelSelector(self, self.theProject, self.mainGui) self.novelValue = NovelSelector(self, self.mainGui)
self.novelValue.setFont(selFont) self.novelValue.setFont(selFont)
self.novelValue.setMinimumWidth(CONFIG.pxInt(150)) self.novelValue.setMinimumWidth(CONFIG.pxInt(150))
self.novelValue.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.novelValue.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
@@ -346,7 +345,7 @@ class GuiNovelToolBar(QWidget):
def _refreshNovelTree(self): def _refreshNovelTree(self):
"""Rebuild the current tree. """Rebuild the current tree.
""" """
rootHandle = self.theProject.data.getLastHandle("novelTree") rootHandle = self.mainGui.project.data.getLastHandle("novelTree")
self.novelView.novelTree.refreshTree(rootHandle=rootHandle, overRide=True) self.novelView.novelTree.refreshTree(rootHandle=rootHandle, overRide=True)
return return
@@ -398,9 +397,8 @@ class GuiNovelTree(QTreeWidget):
logger.debug("Create: GuiNovelTree") logger.debug("Create: GuiNovelTree")
self.novelView = novelView self.novelView = novelView
self.mainGui = novelView.mainGui self.mainGui = novelView.mainGui
self.theProject = novelView.mainGui.theProject
# Internal Variables # Internal Variables
self._treeMap = {} self._treeMap = {}
@@ -516,10 +514,10 @@ class GuiNovelTree(QTreeWidget):
""" """
logger.debug("Requesting refresh of the novel tree") logger.debug("Requesting refresh of the novel tree")
if rootHandle is None: if rootHandle is None:
rootHandle = self.theProject.tree.findRoot(nwItemClass.NOVEL) rootHandle = self.mainGui.project.tree.findRoot(nwItemClass.NOVEL)
treeChanged = self.mainGui.projView.changedSince(self._lastBuild) treeChanged = self.mainGui.projView.changedSince(self._lastBuild)
indexChanged = self.theProject.index.rootChangedSince(rootHandle, self._lastBuild) indexChanged = self.mainGui.project.index.rootChangedSince(rootHandle, self._lastBuild)
if not (treeChanged or indexChanged or overRide): if not (treeChanged or indexChanged or overRide):
logger.debug("No changes have been made to the novel index") logger.debug("No changes have been made to the novel index")
return return
@@ -530,7 +528,7 @@ class GuiNovelTree(QTreeWidget):
titleKey = selItem[0].data(self.C_DATA, self.D_KEY) titleKey = selItem[0].data(self.C_DATA, self.D_KEY)
self._populateTree(rootHandle) self._populateTree(rootHandle)
self.theProject.data.setLastHandle(rootHandle, "novelTree") self.mainGui.project.data.setLastHandle(rootHandle, "novelTree")
if titleKey is not None and titleKey in self._treeMap: if titleKey is not None and titleKey in self._treeMap:
self._treeMap[titleKey].setSelected(True) self._treeMap[titleKey].setSelected(True)
@@ -540,7 +538,7 @@ class GuiNovelTree(QTreeWidget):
def refreshHandle(self, tHandle): def refreshHandle(self, tHandle):
"""Refresh the data for a given handle. """Refresh the data for a given handle.
""" """
idxData = self.theProject.index.getItemData(tHandle) idxData = self.mainGui.project.index.getItemData(tHandle)
if idxData is None: if idxData is None:
return return
@@ -577,7 +575,7 @@ class GuiNovelTree(QTreeWidget):
self._lastCol = colType self._lastCol = colType
self.setColumnHidden(self.C_EXTRA, colType == NovelTreeColumn.HIDDEN) self.setColumnHidden(self.C_EXTRA, colType == NovelTreeColumn.HIDDEN)
if doRefresh: if doRefresh:
lastNovel = self.theProject.data.getLastHandle("novelTree") lastNovel = self.mainGui.project.data.getLastHandle("novelTree")
self.refreshTree(rootHandle=lastNovel, overRide=True) self.refreshTree(rootHandle=lastNovel, overRide=True)
return return
@@ -709,7 +707,7 @@ class GuiNovelTree(QTreeWidget):
tStart = time() tStart = time()
logger.debug("Building novel tree for root item '%s'", rootHandle) logger.debug("Building novel tree for root item '%s'", rootHandle)
novStruct = self.theProject.index.novelStructure(rootHandle=rootHandle, skipExcl=True) novStruct = self.mainGui.project.index.novelStructure(rootHandle=rootHandle, skipExcl=True)
for tKey, tHandle, sTitle, novIdx in novStruct: for tKey, tHandle, sTitle, novIdx in novStruct:
if novIdx.level == "H0": if novIdx.level == "H0":
continue continue
@@ -761,7 +759,7 @@ class GuiNovelTree(QTreeWidget):
refData = [] refData = []
refName = "" refName = ""
theRefs = self.theProject.index.getReferences(tHandle, sTitle) theRefs = self.mainGui.project.index.getReferences(tHandle, sTitle)
if self._lastCol == NovelTreeColumn.POV: if self._lastCol == NovelTreeColumn.POV:
refData = theRefs[nwKeyWords.POV_KEY] refData = theRefs[nwKeyWords.POV_KEY]
refName = self._povLabel refName = self._povLabel
@@ -785,7 +783,7 @@ class GuiNovelTree(QTreeWidget):
""" """
logger.debug("Generating meta data tooltip for '%s:%s'", tHandle, sTitle) logger.debug("Generating meta data tooltip for '%s:%s'", tHandle, sTitle)
pIndex = self.theProject.index pIndex = self.mainGui.project.index
novIdx = pIndex.getItemHeader(tHandle, sTitle) novIdx = pIndex.getItemHeader(tHandle, sTitle)
refTags = pIndex.getReferences(tHandle, sTitle) refTags = pIndex.getReferences(tHandle, sTitle)
+17 -21
View File
@@ -62,8 +62,7 @@ class GuiOutlineView(QWidget):
def __init__(self, mainGui): def __init__(self, mainGui):
super().__init__(parent=mainGui) super().__init__(parent=mainGui)
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
# Build GUI # Build GUI
self.outlineTree = GuiOutlineTree(self) self.outlineTree = GuiOutlineTree(self)
@@ -118,7 +117,7 @@ class GuiOutlineView(QWidget):
def refreshTree(self): def refreshTree(self):
"""Refresh the current tree. """Refresh the current tree.
""" """
self.outlineTree.refreshTree(rootHandle=self.theProject.data.getLastHandle("outline")) self.outlineTree.refreshTree(rootHandle=self.mainGui.project.data.getLastHandle("outline"))
return return
def clearProject(self): def clearProject(self):
@@ -131,9 +130,9 @@ class GuiOutlineView(QWidget):
def openProjectTasks(self): def openProjectTasks(self):
"""Run open project tasks. """Run open project tasks.
""" """
lastOutline = self.theProject.data.getLastHandle("outline") lastOutline = self.mainGui.project.data.getLastHandle("outline")
if not (lastOutline in self.theProject.tree or lastOutline is None): if not (lastOutline in self.mainGui.project.tree or lastOutline is None):
lastOutline = self.theProject.tree.findRoot(nwItemClass.NOVEL) lastOutline = self.mainGui.project.tree.findRoot(nwItemClass.NOVEL)
logger.debug("Setting outline tree to root item '%s'", lastOutline) logger.debug("Setting outline tree to root item '%s'", lastOutline)
@@ -215,8 +214,7 @@ class GuiOutlineToolBar(QToolBar):
logger.debug("Create: GuiOutlineToolBar") logger.debug("Create: GuiOutlineToolBar")
self.mainGui = theOutline.mainGui self.mainGui = theOutline.mainGui
self.theProject = theOutline.mainGui.theProject
iPx = CONFIG.pxInt(22) iPx = CONFIG.pxInt(22)
mPx = CONFIG.pxInt(12) mPx = CONFIG.pxInt(12)
@@ -232,7 +230,7 @@ class GuiOutlineToolBar(QToolBar):
self.novelLabel = QLabel(self.tr("Outline of")) self.novelLabel = QLabel(self.tr("Outline of"))
self.novelLabel.setContentsMargins(0, 0, mPx, 0) self.novelLabel.setContentsMargins(0, 0, mPx, 0)
self.novelValue = NovelSelector(self, self.theProject, self.mainGui) self.novelValue = NovelSelector(self, self.mainGui)
self.novelValue.setMinimumWidth(CONFIG.pxInt(200)) self.novelValue.setMinimumWidth(CONFIG.pxInt(200))
self.novelValue.novelSelectionChanged.connect(self._novelValueChanged) self.novelValue.novelSelectionChanged.connect(self._novelValueChanged)
@@ -373,7 +371,6 @@ class GuiOutlineTree(QTreeWidget):
self.outlineView = outlineView self.outlineView = outlineView
self.mainGui = outlineView.mainGui self.mainGui = outlineView.mainGui
self.theProject = outlineView.mainGui.theProject
self.setUniformRowHeights(True) self.setUniformRowHeights(True)
self.setFrameStyle(QFrame.NoFrame) self.setFrameStyle(QFrame.NoFrame)
@@ -491,13 +488,13 @@ class GuiOutlineTree(QTreeWidget):
# If the novel index or novel tree has changed since the tree # If the novel index or novel tree has changed since the tree
# was last built, we rebuild the tree from the updated index. # was last built, we rebuild the tree from the updated index.
indexChanged = self.theProject.index.rootChangedSince(rootHandle, self._lastBuild) indexChanged = self.mainGui.project.index.rootChangedSince(rootHandle, self._lastBuild)
if not (novelChanged or indexChanged or overRide): if not (novelChanged or indexChanged or overRide):
logger.debug("No changes have been made to the novel index") logger.debug("No changes have been made to the novel index")
return return
self._populateTree(rootHandle) self._populateTree(rootHandle)
self.theProject.data.setLastHandle(rootHandle or None, "outline") self.mainGui.project.data.setLastHandle(rootHandle or None, "outline")
return return
@@ -577,7 +574,7 @@ class GuiOutlineTree(QTreeWidget):
""" """
# Load whatever we saved last time, regardless of wether it # Load whatever we saved last time, regardless of wether it
# contains the correct names or number of columns. # contains the correct names or number of columns.
colState = self.theProject.options.getValue("GuiOutline", "columnState", {}) colState = self.mainGui.project.options.getValue("GuiOutline", "columnState", {})
tmpOrder = [] tmpOrder = []
tmpHidden = {} tmpHidden = {}
@@ -628,7 +625,7 @@ class GuiOutlineTree(QTreeWidget):
logHidden, orgWidth if logHidden and logWidth == 0 else logWidth logHidden, orgWidth if logHidden and logWidth == 0 else logWidth
] ]
pOptions = self.theProject.options pOptions = self.mainGui.project.options
pOptions.setValue("GuiOutline", "columnState", colState) pOptions.setValue("GuiOutline", "columnState", colState)
pOptions.saveSettings() pOptions.saveSettings()
@@ -664,7 +661,7 @@ class GuiOutlineTree(QTreeWidget):
headItem.setTextAlignment(self._colIdx[nwOutline.WCOUNT], Qt.AlignRight) headItem.setTextAlignment(self._colIdx[nwOutline.WCOUNT], Qt.AlignRight)
headItem.setTextAlignment(self._colIdx[nwOutline.PCOUNT], Qt.AlignRight) headItem.setTextAlignment(self._colIdx[nwOutline.PCOUNT], Qt.AlignRight)
novStruct = self.theProject.index.novelStructure(rootHandle=rootHandle, skipExcl=True) novStruct = self.mainGui.project.index.novelStructure(rootHandle=rootHandle, skipExcl=True)
for _, tHandle, sTitle, novIdx in novStruct: for _, tHandle, sTitle, novIdx in novStruct:
iLevel = nwHeaders.H_LEVEL.get(novIdx.level, 0) iLevel = nwHeaders.H_LEVEL.get(novIdx.level, 0)
@@ -672,7 +669,7 @@ class GuiOutlineTree(QTreeWidget):
continue continue
trItem = QTreeWidgetItem() trItem = QTreeWidgetItem()
nwItem = self.theProject.tree[tHandle] nwItem = self.mainGui.project.tree[tHandle]
hDec = CONFIG.theme.getHeaderDecoration(iLevel) hDec = CONFIG.theme.getHeaderDecoration(iLevel)
trItem.setData(self._colIdx[nwOutline.TITLE], Qt.DecorationRole, hDec) trItem.setData(self._colIdx[nwOutline.TITLE], Qt.DecorationRole, hDec)
@@ -692,7 +689,7 @@ class GuiOutlineTree(QTreeWidget):
trItem.setTextAlignment(self._colIdx[nwOutline.WCOUNT], Qt.AlignRight) trItem.setTextAlignment(self._colIdx[nwOutline.WCOUNT], Qt.AlignRight)
trItem.setTextAlignment(self._colIdx[nwOutline.PCOUNT], Qt.AlignRight) trItem.setTextAlignment(self._colIdx[nwOutline.PCOUNT], Qt.AlignRight)
refs = self.theProject.index.getReferences(tHandle, sTitle) refs = self.mainGui.project.index.getReferences(tHandle, sTitle)
trItem.setText(self._colIdx[nwOutline.POV], ", ".join(refs[nwKeyWords.POV_KEY])) trItem.setText(self._colIdx[nwOutline.POV], ", ".join(refs[nwKeyWords.POV_KEY]))
trItem.setText(self._colIdx[nwOutline.FOCUS], ", ".join(refs[nwKeyWords.FOCUS_KEY])) trItem.setText(self._colIdx[nwOutline.FOCUS], ", ".join(refs[nwKeyWords.FOCUS_KEY]))
trItem.setText(self._colIdx[nwOutline.CHAR], ", ".join(refs[nwKeyWords.CHAR_KEY])) trItem.setText(self._colIdx[nwOutline.CHAR], ", ".join(refs[nwKeyWords.CHAR_KEY]))
@@ -774,7 +771,6 @@ class GuiOutlineDetails(QScrollArea):
self.theOutline = theOutline self.theOutline = theOutline
self.mainGui = theOutline.mainGui self.mainGui = theOutline.mainGui
self.theProject = theOutline.mainGui.theProject
# Sizes # Sizes
minTitle = 30*CONFIG.theme.textNWidth minTitle = 30*CONFIG.theme.textNWidth
@@ -1009,8 +1005,8 @@ class GuiOutlineDetails(QScrollArea):
"""Update the content of the tree with the given handle and line """Update the content of the tree with the given handle and line
number pointing to a header. number pointing to a header.
""" """
pIndex = self.theProject.index pIndex = self.mainGui.project.index
nwItem = self.theProject.tree[tHandle] nwItem = self.mainGui.project.tree[tHandle]
novIdx = pIndex.getItemHeader(tHandle, sTitle) novIdx = pIndex.getItemHeader(tHandle, sTitle)
theRefs = pIndex.getReferences(tHandle, sTitle) theRefs = pIndex.getReferences(tHandle, sTitle)
if nwItem is None or novIdx is None: if nwItem is None or novIdx is None:
@@ -1053,7 +1049,7 @@ class GuiOutlineDetails(QScrollArea):
def updateClasses(self): def updateClasses(self):
"""Update the visibility status of class details. """Update the visibility status of class details.
""" """
usedClasses = self.theProject.tree.rootClasses() usedClasses = self.mainGui.project.tree.rootClasses()
pltVisible = nwItemClass.PLOT in usedClasses pltVisible = nwItemClass.PLOT in usedClasses
timVisible = nwItemClass.TIMELINE in usedClasses timVisible = nwItemClass.TIMELINE in usedClasses
+60 -62
View File
@@ -233,10 +233,9 @@ class GuiProjectToolBar(QWidget):
logger.debug("Create: GuiProjectToolBar") logger.debug("Create: GuiProjectToolBar")
self.projView = projView self.projView = projView
self.projTree = projView.projTree self.projTree = projView.projTree
self.mainGui = projView.mainGui self.mainGui = projView.mainGui
self.theProject = projView.mainGui.theProject
iPx = CONFIG.theme.baseIconSize iPx = CONFIG.theme.baseIconSize
mPx = CONFIG.pxInt(2) mPx = CONFIG.pxInt(2)
@@ -394,7 +393,7 @@ class GuiProjectToolBar(QWidget):
"""Build the quick link menu.""" """Build the quick link menu."""
logger.debug("Rebuilding quick links menu") logger.debug("Rebuilding quick links menu")
self.mQuick.clear() self.mQuick.clear()
for n, (tHandle, nwItem) in enumerate(self.theProject.tree.iterRoots(None)): for n, (tHandle, nwItem) in enumerate(self.mainGui.project.tree.iterRoots(None)):
aRoot = self.mQuick.addAction(nwItem.itemName) aRoot = self.mQuick.addAction(nwItem.itemName)
aRoot.setData(tHandle) aRoot.setData(tHandle)
aRoot.setIcon(CONFIG.theme.getIcon(nwLabels.CLASS_ICON[nwItem.itemClass])) aRoot.setIcon(CONFIG.theme.getIcon(nwLabels.CLASS_ICON[nwItem.itemClass]))
@@ -440,7 +439,7 @@ class GuiProjectToolBar(QWidget):
documents. They should only be visible if novel documents can documents. They should only be visible if novel documents can
actually be added. actually be added.
""" """
nwItem = self.theProject.tree[tHandle] nwItem = self.mainGui.project.tree[tHandle]
allowDoc = isinstance(nwItem, NWItem) and nwItem.documentAllowed() allowDoc = isinstance(nwItem, NWItem) and nwItem.documentAllowed()
self.aAddEmpty.setVisible(allowDoc) self.aAddEmpty.setVisible(allowDoc)
self.aAddChap.setVisible(allowDoc) self.aAddChap.setVisible(allowDoc)
@@ -466,9 +465,8 @@ class GuiProjectTree(QTreeWidget):
logger.debug("Create: GuiProjectTree") logger.debug("Create: GuiProjectTree")
self.projView = projView self.projView = projView
self.mainGui = projView.mainGui self.mainGui = projView.mainGui
self.theProject = projView.mainGui.theProject
# Internal Variables # Internal Variables
self._treeMap = {} self._treeMap = {}
@@ -575,15 +573,15 @@ class GuiProjectTree(QTreeWidget):
if itemType == nwItemType.ROOT and isinstance(itemClass, nwItemClass): if itemType == nwItemType.ROOT and isinstance(itemClass, nwItemClass):
tHandle = self.theProject.newRoot(itemClass) tHandle = self.mainGui.project.newRoot(itemClass)
sHandle = self.getSelectedHandle() sHandle = self.getSelectedHandle()
pItem = self.theProject.tree[sHandle] if sHandle else None pItem = self.mainGui.project.tree[sHandle] if sHandle else None
nHandle = pItem.itemRoot if pItem else None nHandle = pItem.itemRoot if pItem else None
elif itemType in (nwItemType.FILE, nwItemType.FOLDER): elif itemType in (nwItemType.FILE, nwItemType.FOLDER):
sHandle = self.getSelectedHandle() sHandle = self.getSelectedHandle()
pItem = self.theProject.tree[sHandle] if sHandle else None pItem = self.mainGui.project.tree[sHandle] if sHandle else None
if sHandle is None or pItem is None: if sHandle is None or pItem is None:
self.mainGui.makeAlert(self.tr( self.mainGui.makeAlert(self.tr(
"Did not find anywhere to add the file or folder!" "Did not find anywhere to add the file or folder!"
@@ -595,7 +593,7 @@ class GuiProjectTree(QTreeWidget):
sLevel = nwHeaders.H_LEVEL.get(pItem.mainHeading, 0) sLevel = nwHeaders.H_LEVEL.get(pItem.mainHeading, 0)
sIsParent = False if qItem is None else qItem.childCount() > 0 sIsParent = False if qItem is None else qItem.childCount() > 0
if self.theProject.tree.isTrash(sHandle): if self.mainGui.project.tree.isTrash(sHandle):
self.mainGui.makeAlert(self.tr( self.mainGui.makeAlert(self.tr(
"Cannot add new files or folders to the Trash folder." "Cannot add new files or folders to the Trash folder."
), level=nwAlert.ERROR) ), level=nwAlert.ERROR)
@@ -638,9 +636,9 @@ class GuiProjectTree(QTreeWidget):
# Add the file or folder # Add the file or folder
if itemType == nwItemType.FILE: if itemType == nwItemType.FILE:
tHandle = self.theProject.newFile(newLabel, sHandle) tHandle = self.mainGui.project.newFile(newLabel, sHandle)
else: else:
tHandle = self.theProject.newFolder(newLabel, sHandle) tHandle = self.mainGui.project.newFolder(newLabel, sHandle)
else: else:
logger.error("Failed to add new item") logger.error("Failed to add new item")
@@ -653,7 +651,7 @@ class GuiProjectTree(QTreeWidget):
# Handle new file creation # Handle new file creation
if itemType == nwItemType.FILE and hLevel > 0: if itemType == nwItemType.FILE and hLevel > 0:
self.theProject.writeNewFile(tHandle, hLevel, not isNote) self.mainGui.project.writeNewFile(tHandle, hLevel, not isNote)
# Add the new item to the project tree # Add the new item to the project tree
self.revealNewTreeItem(tHandle, nHandle=nHandle, wordCount=True) self.revealNewTreeItem(tHandle, nHandle=nHandle, wordCount=True)
@@ -664,7 +662,7 @@ class GuiProjectTree(QTreeWidget):
def revealNewTreeItem(self, tHandle: str | None, nHandle: str | None = None, def revealNewTreeItem(self, tHandle: str | None, nHandle: str | None = None,
wordCount: bool = False) -> bool: wordCount: bool = False) -> bool:
"""Reveal a newly added project item in the project tree.""" """Reveal a newly added project item in the project tree."""
nwItem = self.theProject.tree[tHandle] if tHandle else None nwItem = self.mainGui.project.tree[tHandle] if tHandle else None
if tHandle is None or nwItem is None: if tHandle is None or nwItem is None:
return False return False
@@ -673,7 +671,7 @@ class GuiProjectTree(QTreeWidget):
return False return False
if nwItem.isFileType() and wordCount: if nwItem.isFileType() and wordCount:
wC = self.theProject.index.getCounts(tHandle)[1] wC = self.mainGui.project.index.getCounts(tHandle)[1]
self.propagateCount(tHandle, wC) self.propagateCount(tHandle, wC)
self.projView.wordCountsChanged.emit() self.projView.wordCountsChanged.emit()
@@ -748,7 +746,7 @@ class GuiProjectTree(QTreeWidget):
def renameTreeItem(self, tHandle: str) -> bool: def renameTreeItem(self, tHandle: str) -> bool:
"""Open a dialog to edit the label of an item.""" """Open a dialog to edit the label of an item."""
tItem = self.theProject.tree[tHandle] tItem = self.mainGui.project.tree[tHandle]
if tItem is None: if tItem is None:
return False return False
@@ -772,7 +770,7 @@ class GuiProjectTree(QTreeWidget):
if isinstance(item, QTreeWidgetItem): if isinstance(item, QTreeWidgetItem):
theList = self._scanChildren(theList, item, i) theList = self._scanChildren(theList, item, i)
logger.debug("Saving project tree item order") logger.debug("Saving project tree item order")
self.theProject.setTreeOrder(theList) self.mainGui.project.setTreeOrder(theList)
return return
def getTreeFromHandle(self, tHandle: str) -> list[str]: def getTreeFromHandle(self, tHandle: str) -> list[str]:
@@ -805,16 +803,16 @@ class GuiProjectTree(QTreeWidget):
logger.error("There is no item to delete") logger.error("There is no item to delete")
return False return False
trashHandle = self.theProject.tree.trashRoot() trashHandle = self.mainGui.project.tree.trashRoot()
if tHandle == trashHandle: if tHandle == trashHandle:
logger.error("Cannot delete the Trash folder") logger.error("Cannot delete the Trash folder")
return False return False
nwItem = self.theProject.tree[tHandle] nwItem = self.mainGui.project.tree[tHandle]
if nwItem is None: if nwItem is None:
return False return False
if self.theProject.tree.isTrash(tHandle) or nwItem.isRootType(): if self.mainGui.project.tree.isTrash(tHandle) or nwItem.isRootType():
status = self.permDeleteItem(tHandle) status = self.permDeleteItem(tHandle)
else: else:
status = self.moveItemToTrash(tHandle) status = self.moveItemToTrash(tHandle)
@@ -830,7 +828,7 @@ class GuiProjectTree(QTreeWidget):
logger.error("No project open") logger.error("No project open")
return False return False
trashHandle = self.theProject.tree.trashRoot() trashHandle = self.mainGui.project.tree.trashRoot()
logger.debug("Emptying Trash folder") logger.debug("Emptying Trash folder")
if trashHandle is None: if trashHandle is None:
@@ -873,13 +871,13 @@ class GuiProjectTree(QTreeWidget):
so such a request is cancelled. so such a request is cancelled.
""" """
trItemS = self._getTreeItem(tHandle) trItemS = self._getTreeItem(tHandle)
nwItemS = self.theProject.tree[tHandle] nwItemS = self.mainGui.project.tree[tHandle]
if trItemS is None or nwItemS is None: if trItemS is None or nwItemS is None:
logger.error("Could not find tree item for deletion") logger.error("Could not find tree item for deletion")
return False return False
if self.theProject.tree.isTrash(tHandle): if self.mainGui.project.tree.isTrash(tHandle):
logger.error("Item is already in the Trash folder") logger.error("Item is already in the Trash folder")
return False return False
@@ -923,7 +921,7 @@ class GuiProjectTree(QTreeWidget):
Root items are handled a little different than other items. Root items are handled a little different than other items.
""" """
trItemS = self._getTreeItem(tHandle) trItemS = self._getTreeItem(tHandle)
nwItemS = self.theProject.tree[tHandle] nwItemS = self.mainGui.project.tree[tHandle]
if trItemS is None or nwItemS is None: if trItemS is None or nwItemS is None:
logger.error("Could not find tree item for deletion") logger.error("Could not find tree item for deletion")
return False return False
@@ -940,7 +938,7 @@ class GuiProjectTree(QTreeWidget):
tIndex = self.indexOfTopLevelItem(trItemS) tIndex = self.indexOfTopLevelItem(trItemS)
self.takeTopLevelItem(tIndex) self.takeTopLevelItem(tIndex)
self.theProject.removeItem(tHandle) self.mainGui.project.removeItem(tHandle)
self._treeMap.pop(tHandle, None) self._treeMap.pop(tHandle, None)
self._alertTreeChange(tHandle, flush=True) self._alertTreeChange(tHandle, flush=True)
@@ -969,7 +967,7 @@ class GuiProjectTree(QTreeWidget):
for dHandle in reversed(self.getTreeFromHandle(tHandle)): for dHandle in reversed(self.getTreeFromHandle(tHandle)):
if self.mainGui.docEditor.docHandle() == dHandle: if self.mainGui.docEditor.docHandle() == dHandle:
self.mainGui.closeDocument() self.mainGui.closeDocument()
self.theProject.removeItem(dHandle) self.mainGui.project.removeItem(dHandle)
self._treeMap.pop(dHandle, None) self._treeMap.pop(dHandle, None)
self._alertTreeChange(tHandle, flush=flush) self._alertTreeChange(tHandle, flush=flush)
@@ -987,7 +985,7 @@ class GuiProjectTree(QTreeWidget):
already coming from the project tree. already coming from the project tree.
""" """
trItem = self._getTreeItem(tHandle) trItem = self._getTreeItem(tHandle)
nwItem = self.theProject.tree[tHandle] nwItem = self.mainGui.project.tree[tHandle]
if trItem is None or nwItem is None: if trItem is None or nwItem is None:
return return
@@ -1049,10 +1047,10 @@ class GuiProjectTree(QTreeWidget):
pHandle = pItem.data(self.C_DATA, self.D_HANDLE) pHandle = pItem.data(self.C_DATA, self.D_HANDLE)
if pHandle: if pHandle:
if self.theProject.tree.checkType(pHandle, nwItemType.FILE): if self.mainGui.project.tree.checkType(pHandle, nwItemType.FILE):
# A file has an internal word count we need to account # A file has an internal word count we need to account
# for, but a folder always has 0 words on its own. # for, but a folder always has 0 words on its own.
pCount += self.theProject.index.getCounts(pHandle)[1] pCount += self.mainGui.project.index.getCounts(pHandle)[1]
self.propagateCount(pHandle, pCount, countChildren=False) self.propagateCount(pHandle, pCount, countChildren=False)
@@ -1067,7 +1065,7 @@ class GuiProjectTree(QTreeWidget):
logger.debug("Building the project tree ...") logger.debug("Building the project tree ...")
self.clearTree() self.clearTree()
count = 0 count = 0
for nwItem in self.theProject.getProjectItems(): for nwItem in self.mainGui.project.getProjectItems():
count += 1 count += 1
self._addTreeItem(nwItem) self._addTreeItem(nwItem)
if count > 0: if count > 0:
@@ -1180,7 +1178,7 @@ class GuiProjectTree(QTreeWidget):
if tHandle is None: if tHandle is None:
return return
tItem = self.theProject.tree[tHandle] tItem = self.mainGui.project.tree[tHandle]
if tItem is None: if tItem is None:
return return
@@ -1202,7 +1200,7 @@ class GuiProjectTree(QTreeWidget):
selItem = self.itemAt(clickPos) selItem = self.itemAt(clickPos)
if isinstance(selItem, QTreeWidgetItem): if isinstance(selItem, QTreeWidgetItem):
tHandle = selItem.data(self.C_DATA, self.D_HANDLE) tHandle = selItem.data(self.C_DATA, self.D_HANDLE)
tItem = self.theProject.tree[tHandle] tItem = self.mainGui.project.tree[tHandle]
hasChild = selItem.childCount() > 0 hasChild = selItem.childCount() > 0
if tItem is None or tHandle is None: if tItem is None or tHandle is None:
@@ -1214,7 +1212,7 @@ class GuiProjectTree(QTreeWidget):
# Trash Folder # Trash Folder
# ============ # ============
trashHandle = self.theProject.tree.trashRoot() trashHandle = self.mainGui.project.tree.trashRoot()
if tItem.itemHandle == trashHandle and trashHandle is not None: if tItem.itemHandle == trashHandle and trashHandle is not None:
# The trash folder only has one option # The trash folder only has one option
aEmptyTrash = ctxMenu.addAction(self.tr("Empty Trash")) aEmptyTrash = ctxMenu.addAction(self.tr("Empty Trash"))
@@ -1253,7 +1251,7 @@ class GuiProjectTree(QTreeWidget):
checkMark = f" ({nwUnicode.U_CHECK})" checkMark = f" ({nwUnicode.U_CHECK})"
if tItem.isNovelLike(): if tItem.isNovelLike():
mStatus = ctxMenu.addMenu(self.tr("Set Status to ...")) mStatus = ctxMenu.addMenu(self.tr("Set Status to ..."))
for n, (key, entry) in enumerate(self.theProject.data.itemStatus.items()): for n, (key, entry) in enumerate(self.mainGui.project.data.itemStatus.items()):
entryName = entry["name"] + (checkMark if tItem.itemStatus == key else "") entryName = entry["name"] + (checkMark if tItem.itemStatus == key else "")
aStatus = mStatus.addAction(entry["icon"], entryName) aStatus = mStatus.addAction(entry["icon"], entryName)
aStatus.triggered.connect( aStatus.triggered.connect(
@@ -1266,7 +1264,7 @@ class GuiProjectTree(QTreeWidget):
) )
else: else:
mImport = ctxMenu.addMenu(self.tr("Set Importance to ...")) mImport = ctxMenu.addMenu(self.tr("Set Importance to ..."))
for n, (key, entry) in enumerate(self.theProject.data.itemImport.items()): for n, (key, entry) in enumerate(self.mainGui.project.data.itemImport.items()):
entryName = entry["name"] + (checkMark if tItem.itemImport == key else "") entryName = entry["name"] + (checkMark if tItem.itemImport == key else "")
aImport = mImport.addAction(entry["icon"], entryName) aImport = mImport.addAction(entry["icon"], entryName)
aImport.triggered.connect( aImport.triggered.connect(
@@ -1378,7 +1376,7 @@ class GuiProjectTree(QTreeWidget):
return return
tHandle = selItem.data(self.C_DATA, self.D_HANDLE) tHandle = selItem.data(self.C_DATA, self.D_HANDLE)
tItem = self.theProject.tree[tHandle] tItem = self.mainGui.project.tree[tHandle]
if tItem is None: if tItem is None:
return return
@@ -1422,7 +1420,7 @@ class GuiProjectTree(QTreeWidget):
def _postItemMove(self, tHandle: str, wCount: int) -> bool: def _postItemMove(self, tHandle: str, wCount: int) -> bool:
"""Run various maintenance tasks for a moved item.""" """Run various maintenance tasks for a moved item."""
trItemS = self._getTreeItem(tHandle) trItemS = self._getTreeItem(tHandle)
nwItemS = self.theProject.tree[tHandle] nwItemS = self.mainGui.project.tree[tHandle]
trItemP = trItemS.parent() if trItemS else None trItemP = trItemS.parent() if trItemS else None
if trItemP is None or nwItemS is None: if trItemP is None or nwItemS is None:
logger.error("Failed to find new parent item of '%s'", tHandle) logger.error("Failed to find new parent item of '%s'", tHandle)
@@ -1439,13 +1437,13 @@ class GuiProjectTree(QTreeWidget):
logger.debug("A total of %d item(s) were moved", len(mHandles)) logger.debug("A total of %d item(s) were moved", len(mHandles))
for mHandle in mHandles: for mHandle in mHandles:
logger.debug("Updating item '%s'", mHandle) logger.debug("Updating item '%s'", mHandle)
self.theProject.tree.updateItemData(mHandle) self.mainGui.project.tree.updateItemData(mHandle)
# Update the index # Update the index
if nwItemS.isInactiveClass(): if nwItemS.isInactiveClass():
self.theProject.index.deleteHandle(mHandle) self.mainGui.project.index.deleteHandle(mHandle)
else: else:
self.theProject.index.reIndexHandle(mHandle) self.mainGui.project.index.reIndexHandle(mHandle)
self.setTreeItemValues(mHandle) self.setTreeItemValues(mHandle)
@@ -1465,7 +1463,7 @@ class GuiProjectTree(QTreeWidget):
def _toggleItemActive(self, tHandle: str) -> None: def _toggleItemActive(self, tHandle: str) -> None:
"""Toggle the active status of an item.""" """Toggle the active status of an item."""
tItem = self.theProject.tree[tHandle] tItem = self.mainGui.project.tree[tHandle]
if tItem is not None: if tItem is not None:
tItem.setActive(not tItem.isActive) tItem.setActive(not tItem.isActive)
self.setTreeItemValues(tItem.itemHandle) self.setTreeItemValues(tItem.itemHandle)
@@ -1486,7 +1484,7 @@ class GuiProjectTree(QTreeWidget):
def _changeItemStatus(self, tHandle: str, tStatus: str) -> None: def _changeItemStatus(self, tHandle: str, tStatus: str) -> None:
"""Set a new status value of an item.""" """Set a new status value of an item."""
tItem = self.theProject.tree[tHandle] tItem = self.mainGui.project.tree[tHandle]
if tItem is not None: if tItem is not None:
tItem.setStatus(tStatus) tItem.setStatus(tStatus)
self.setTreeItemValues(tItem.itemHandle) self.setTreeItemValues(tItem.itemHandle)
@@ -1495,7 +1493,7 @@ class GuiProjectTree(QTreeWidget):
def _changeItemImport(self, tHandle: str, tImport: str) -> None: def _changeItemImport(self, tHandle: str, tImport: str) -> None:
"""Set a new importance value of an item.""" """Set a new importance value of an item."""
tItem = self.theProject.tree[tHandle] tItem = self.mainGui.project.tree[tHandle]
if tItem is not None: if tItem is not None:
tItem.setImport(tImport) tItem.setImport(tImport)
self.setTreeItemValues(tItem.itemHandle) self.setTreeItemValues(tItem.itemHandle)
@@ -1504,7 +1502,7 @@ class GuiProjectTree(QTreeWidget):
def _changeItemLayout(self, tHandle: str, itemLayout: nwItemLayout) -> None: def _changeItemLayout(self, tHandle: str, itemLayout: nwItemLayout) -> None:
"""Set a new item layout value of an item.""" """Set a new item layout value of an item."""
tItem = self.theProject.tree[tHandle] tItem = self.mainGui.project.tree[tHandle]
if tItem is not None: if tItem is not None:
if itemLayout == nwItemLayout.DOCUMENT and tItem.documentAllowed(): if itemLayout == nwItemLayout.DOCUMENT and tItem.documentAllowed():
tItem.setLayout(nwItemLayout.DOCUMENT) tItem.setLayout(nwItemLayout.DOCUMENT)
@@ -1518,7 +1516,7 @@ class GuiProjectTree(QTreeWidget):
def _covertFolderToFile(self, tHandle: str, itemLayout: nwItemLayout) -> None: def _covertFolderToFile(self, tHandle: str, itemLayout: nwItemLayout) -> None:
"""Convert a folder to a note or document.""" """Convert a folder to a note or document."""
tItem = self.theProject.tree[tHandle] tItem = self.mainGui.project.tree[tHandle]
if tItem is not None and tItem.isFolderType(): if tItem is not None and tItem.isFolderType():
msgYes = self.mainGui.askQuestion(self.tr( msgYes = self.mainGui.askQuestion(self.tr(
"Do you want to convert the folder to a {0}? " "Do you want to convert the folder to a {0}? "
@@ -1543,7 +1541,7 @@ class GuiProjectTree(QTreeWidget):
logger.info("Request to merge items under handle '%s'", tHandle) logger.info("Request to merge items under handle '%s'", tHandle)
itemList = self.getTreeFromHandle(tHandle) itemList = self.getTreeFromHandle(tHandle)
tItem = self.theProject.tree[tHandle] tItem = self.mainGui.project.tree[tHandle]
if tItem is None: if tItem is None:
return False return False
@@ -1569,7 +1567,7 @@ class GuiProjectTree(QTreeWidget):
self.mainGui.saveDocument() self.mainGui.saveDocument()
# Create merge object, and append docs # Create merge object, and append docs
docMerger = DocMerger(self.theProject) docMerger = DocMerger(self.mainGui.project)
mLabel = self.tr("Merged") mLabel = self.tr("Merged")
if newFile: if newFile:
@@ -1591,7 +1589,7 @@ class GuiProjectTree(QTreeWidget):
) )
return False return False
self.theProject.index.reIndexHandle(mHandle) self.mainGui.project.index.reIndexHandle(mHandle)
if newFile: if newFile:
self.revealNewTreeItem(mHandle, nHandle=tHandle, wordCount=True) self.revealNewTreeItem(mHandle, nHandle=tHandle, wordCount=True)
@@ -1616,7 +1614,7 @@ class GuiProjectTree(QTreeWidget):
"""Split a document into multiple documents.""" """Split a document into multiple documents."""
logger.info("Request to split items with handle '%s'", tHandle) logger.info("Request to split items with handle '%s'", tHandle)
tItem = self.theProject.tree[tHandle] tItem = self.mainGui.project.tree[tHandle]
if tItem is None: if tItem is None:
return False return False
@@ -1635,7 +1633,7 @@ class GuiProjectTree(QTreeWidget):
intoFolder = splitData.get("intoFolder", False) intoFolder = splitData.get("intoFolder", False)
docHierarchy = splitData.get("docHierarchy", False) docHierarchy = splitData.get("docHierarchy", False)
docSplit = DocSplitter(self.theProject, tHandle) docSplit = DocSplitter(self.mainGui.project, tHandle)
if intoFolder: if intoFolder:
fHandle = docSplit.newParentFolder(tItem.itemParent, tItem.itemName) fHandle = docSplit.newParentFolder(tItem.itemParent, tItem.itemName)
self.revealNewTreeItem(fHandle, nHandle=tHandle) self.revealNewTreeItem(fHandle, nHandle=tHandle)
@@ -1645,7 +1643,7 @@ class GuiProjectTree(QTreeWidget):
docSplit.splitDocument(headerList, splitText) docSplit.splitDocument(headerList, splitText)
for writeOk, dHandle, nHandle in docSplit.writeDocuments(docHierarchy): for writeOk, dHandle, nHandle in docSplit.writeDocuments(docHierarchy):
self.theProject.index.reIndexHandle(dHandle) self.mainGui.project.index.reIndexHandle(dHandle)
self.revealNewTreeItem(dHandle, nHandle=nHandle, wordCount=True) self.revealNewTreeItem(dHandle, nHandle=nHandle, wordCount=True)
self._alertTreeChange(dHandle, flush=False) self._alertTreeChange(dHandle, flush=False)
if not writeOk: if not writeOk:
@@ -1679,10 +1677,10 @@ class GuiProjectTree(QTreeWidget):
if not self.mainGui.askQuestion(question): if not self.mainGui.askQuestion(question):
return False return False
docDup = DocDuplicator(self.theProject) docDup = DocDuplicator(self.mainGui.project)
dupCount = 0 dupCount = 0
for dHandle, nHandle in docDup.duplicate(itemTree): for dHandle, nHandle in docDup.duplicate(itemTree):
self.theProject.index.reIndexHandle(dHandle) self.mainGui.project.index.reIndexHandle(dHandle)
self.revealNewTreeItem(dHandle, nHandle=nHandle, wordCount=True) self.revealNewTreeItem(dHandle, nHandle=nHandle, wordCount=True)
self._alertTreeChange(dHandle, flush=False) self._alertTreeChange(dHandle, flush=False)
dupCount += 1 dupCount += 1
@@ -1702,7 +1700,7 @@ class GuiProjectTree(QTreeWidget):
cCount = tItem.childCount() cCount = tItem.childCount()
# Update tree-related meta data # Update tree-related meta data
nwItem = self.theProject.tree[tHandle] nwItem = self.mainGui.project.tree[tHandle]
if nwItem is not None: if nwItem is not None:
nwItem.setExpanded(tItem.isExpanded() and cCount > 0) nwItem.setExpanded(tItem.isExpanded() and cCount > 0)
nwItem.setOrder(tIndex) nwItem.setOrder(tIndex)
@@ -1769,13 +1767,13 @@ class GuiProjectTree(QTreeWidget):
"""Adds the trash root folder if it doesn't already exist in the """Adds the trash root folder if it doesn't already exist in the
project tree. project tree.
""" """
trashHandle = self.theProject.trashFolder() trashHandle = self.mainGui.project.trashFolder()
if trashHandle is None: if trashHandle is None:
return None return None
trItem = self._getTreeItem(trashHandle) trItem = self._getTreeItem(trashHandle)
if trItem is None: if trItem is None:
trItem = self._addTreeItem(self.theProject.tree[trashHandle]) trItem = self._addTreeItem(self.mainGui.project.tree[trashHandle])
if trItem is not None: if trItem is not None:
trItem.setExpanded(True) trItem.setExpanded(True)
self._alertTreeChange(trashHandle, flush=True) self._alertTreeChange(trashHandle, flush=True)
@@ -1788,14 +1786,14 @@ class GuiProjectTree(QTreeWidget):
deleted. deleted.
""" """
self._timeChanged = time() self._timeChanged = time()
self.theProject.setProjectChanged(True) self.mainGui.project.setProjectChanged(True)
if flush: if flush:
self.saveTreeOrder() self.saveTreeOrder()
if tHandle is None or tHandle not in self.theProject.tree: if tHandle is None or tHandle not in self.mainGui.project.tree:
return return
tItem = self.theProject.tree[tHandle] tItem = self.mainGui.project.tree[tHandle]
if tItem and tItem.isRootType(): if tItem and tItem.isRootType():
self.projView.rootFolderChanged.emit(tHandle) self.projView.rootFolderChanged.emit(tHandle)
+44 -35
View File
@@ -114,7 +114,7 @@ class GuiMain(QMainWindow):
# Core Classes # Core Classes
CONFIG.setThemeInstance(GuiTheme()) CONFIG.setThemeInstance(GuiTheme())
self.theProject = NWProject(self) self._project = NWProject(self)
# Core Settings # Core Settings
self.hasProject = False self.hasProject = False
@@ -238,7 +238,7 @@ class GuiMain(QMainWindow):
# Connect Signals # Connect Signals
# =============== # ===============
self.theProject.projectStatusChanged.connect(self.mainStatus.doUpdateProjectStatus) self._project.projectStatusChanged.connect(self.mainStatus.doUpdateProjectStatus)
self.viewsBar.viewChangeRequested.connect(self._changeView) self.viewsBar.viewChangeRequested.connect(self._changeView)
@@ -382,6 +382,15 @@ class GuiMain(QMainWindow):
return return
##
# Properties
##
@property
def project(self) -> NWProject:
"""The project instance."""
return self._project
## ##
# Project Actions # Project Actions
## ##
@@ -444,7 +453,7 @@ class GuiMain(QMainWindow):
saveOK = self.saveProject() saveOK = self.saveProject()
doBackup = False doBackup = False
if self.theProject.data.doBackup and CONFIG.backupOnClose: if self._project.data.doBackup and CONFIG.backupOnClose:
doBackup = True doBackup = True
if CONFIG.askBeforeBackup: if CONFIG.askBeforeBackup:
msgYes = self.askQuestion(self.tr("Backup the current project?")) msgYes = self.askQuestion(self.tr("Backup the current project?"))
@@ -452,7 +461,7 @@ class GuiMain(QMainWindow):
doBackup = False doBackup = False
if doBackup: if doBackup:
self.theProject.backupProject(False) self._project.backupProject(False)
if saveOK: if saveOK:
self.closeDocument() self.closeDocument()
@@ -460,7 +469,7 @@ class GuiMain(QMainWindow):
self.outlineView.closeProjectTasks() self.outlineView.closeProjectTasks()
self.novelView.closeProjectTasks() self.novelView.closeProjectTasks()
self.theProject.closeProject(self.idleTime) self._project.closeProject(self.idleTime)
self.idleRefTime = time() self.idleRefTime = time()
self.idleTime = 0.0 self.idleTime = 0.0
@@ -484,9 +493,9 @@ class GuiMain(QMainWindow):
self._changeView(nwView.PROJECT) self._changeView(nwView.PROJECT)
# Try to open the project # Try to open the project
if not self.theProject.openProject(projFile): if not self._project.openProject(projFile):
# The project open failed. # The project open failed.
lockStatus = self.theProject.getLockStatus() lockStatus = self._project.getLockStatus()
if lockStatus is None: if lockStatus is None:
# The project is not locked, so failed for some other # The project is not locked, so failed for some other
# reason handled by the project class. # reason handled by the project class.
@@ -516,7 +525,7 @@ class GuiMain(QMainWindow):
lockDetails = "" lockDetails = ""
if self.askQuestion(lockText, info=lockInfo, details=lockDetails, level=nwAlert.WARN): if self.askQuestion(lockText, info=lockInfo, details=lockDetails, level=nwAlert.WARN):
if not self.theProject.openProject(projFile, overrideLock=True): if not self._project.openProject(projFile, overrideLock=True):
return False return False
else: else:
return False return False
@@ -527,11 +536,11 @@ class GuiMain(QMainWindow):
self.idleTime = 0.0 self.idleTime = 0.0
# Update GUI # Update GUI
self._updateWindowTitle(self.theProject.data.name) self._updateWindowTitle(self._project.data.name)
self.rebuildTrees() self.rebuildTrees()
self.docEditor.setDictionaries() self.docEditor.setDictionaries()
self.docEditor.toggleSpellCheck(self.theProject.data.spellCheck) self.docEditor.toggleSpellCheck(self._project.data.spellCheck)
self.mainStatus.setRefTime(self.theProject.projOpened) self.mainStatus.setRefTime(self._project.projOpened)
self.projView.openProjectTasks() self.projView.openProjectTasks()
self.novelView.openProjectTasks() self.novelView.openProjectTasks()
self.outlineView.openProjectTasks() self.outlineView.openProjectTasks()
@@ -539,9 +548,9 @@ class GuiMain(QMainWindow):
# Restore previously open documents, if any # Restore previously open documents, if any
# If none was recorded, open the first document found # If none was recorded, open the first document found
lastEdited = self.theProject.data.getLastHandle("editor") lastEdited = self._project.data.getLastHandle("editor")
if lastEdited is None: if lastEdited is None:
for nwItem in self.theProject.tree: for nwItem in self._project.tree:
if nwItem and nwItem.isFileType(): if nwItem and nwItem.isFileType():
lastEdited = nwItem.itemHandle lastEdited = nwItem.itemHandle
break break
@@ -549,19 +558,19 @@ class GuiMain(QMainWindow):
if lastEdited is not None: if lastEdited is not None:
self.openDocument(lastEdited, doScroll=True) self.openDocument(lastEdited, doScroll=True)
lastViewed = self.theProject.data.getLastHandle("viewer") lastViewed = self._project.data.getLastHandle("viewer")
if lastViewed is not None: if lastViewed is not None:
self.viewDocument(lastViewed) self.viewDocument(lastViewed)
# Check if we need to rebuild the index # Check if we need to rebuild the index
if self.theProject.index.indexBroken: if self._project.index.indexBroken:
self.makeAlert(self.tr("The project index is outdated or broken. Rebuilding index.")) self.makeAlert(self.tr("The project index is outdated or broken. Rebuilding index."))
self.rebuildIndex() self.rebuildIndex()
# Make sure the changed status is set to false on things opened # Make sure the changed status is set to false on things opened
qApp.processEvents() qApp.processEvents()
self.docEditor.setDocumentChanged(False) self.docEditor.setDocumentChanged(False)
self.theProject.setProjectChanged(False) self._project.setProjectChanged(False)
logger.debug("Project load complete") logger.debug("Project load complete")
@@ -573,7 +582,7 @@ class GuiMain(QMainWindow):
logger.error("No project open") logger.error("No project open")
return False return False
self.projView.saveProjectTasks() self.projView.saveProjectTasks()
self.theProject.saveProject(autoSave=autoSave) self._project.saveProject(autoSave=autoSave)
return True return True
## ##
@@ -606,7 +615,7 @@ class GuiMain(QMainWindow):
logger.error("No project open") logger.error("No project open")
return False return False
if not tHandle or not self.theProject.tree.checkType(tHandle, nwItemType.FILE): if not tHandle or not self._project.tree.checkType(tHandle, nwItemType.FILE):
logger.debug("Requested item '%s' is not a document", tHandle) logger.debug("Requested item '%s' is not a document", tHandle)
return False return False
@@ -620,7 +629,7 @@ class GuiMain(QMainWindow):
self.closeDocument(beforeOpen=True) self.closeDocument(beforeOpen=True)
if self.docEditor.loadText(tHandle, tLine): if self.docEditor.loadText(tHandle, tLine):
self.theProject.data.setLastHandle(tHandle, "editor") self._project.data.setLastHandle(tHandle, "editor")
self.projView.setSelectedHandle(tHandle, doScroll=doScroll) self.projView.setSelectedHandle(tHandle, doScroll=doScroll)
self.novelView.setActiveHandle(tHandle) self.novelView.setActiveHandle(tHandle)
if changeFocus: if changeFocus:
@@ -641,7 +650,7 @@ class GuiMain(QMainWindow):
nHandle = None # The next handle after tHandle nHandle = None # The next handle after tHandle
fHandle = None # The first file handle we encounter fHandle = None # The first file handle we encounter
foundIt = False # We've found tHandle, pick the next we see foundIt = False # We've found tHandle, pick the next we see
for tItem in self.theProject.tree: for tItem in self._project.tree:
if not tItem.isFileType(): if not tItem.isFileType():
continue continue
if fHandle is None: if fHandle is None:
@@ -687,7 +696,7 @@ class GuiMain(QMainWindow):
tHandle = self.projView.getSelectedHandle() tHandle = self.projView.getSelectedHandle()
if tHandle is None: if tHandle is None:
tHandle = self.theProject.data.getLastHandle("viewer") tHandle = self._project.data.getLastHandle("viewer")
if tHandle is None: if tHandle is None:
logger.debug("No document to view, giving up") logger.debug("No document to view, giving up")
@@ -806,7 +815,7 @@ class GuiMain(QMainWindow):
return False return False
if tHandle is not None and sTitle is not None: if tHandle is not None and sTitle is not None:
hItem = self.theProject.index.getItemHeader(tHandle, sTitle) hItem = self._project.index.getItemHeader(tHandle, sTitle)
if hItem is not None: if hItem is not None:
tLine = hItem.line tLine = hItem.line
@@ -843,7 +852,7 @@ class GuiMain(QMainWindow):
tStart = time() tStart = time()
self.projView.saveProjectTasks() self.projView.saveProjectTasks()
self.theProject.index.rebuildIndex() self._project.index.rebuildIndex()
self.projView.populateTree() self.projView.populateTree()
self.novelView.refreshTree() self.novelView.refreshTree()
@@ -951,7 +960,7 @@ class GuiMain(QMainWindow):
if dlgProj.spellChanged: if dlgProj.spellChanged:
self.docEditor.setDictionaries() self.docEditor.setDictionaries()
self.itemDetails.refreshDetails() self.itemDetails.refreshDetails()
self._updateWindowTitle(self.theProject.data.name) self._updateWindowTitle(self._project.data.name)
return True return True
@@ -1197,7 +1206,7 @@ class GuiMain(QMainWindow):
def closeDocEditor(self) -> None: def closeDocEditor(self) -> None:
"""Close the document editor. This does not hide the editor.""" """Close the document editor. This does not hide the editor."""
self.closeDocument() self.closeDocument()
self.theProject.data.setLastHandle(None, "editor") self._project.data.setLastHandle(None, "editor")
return return
def closeDocViewer(self, byUser: bool = True) -> bool: def closeDocViewer(self, byUser: bool = True) -> bool:
@@ -1205,7 +1214,7 @@ class GuiMain(QMainWindow):
self.docViewer.clearViewer() self.docViewer.clearViewer()
if byUser: if byUser:
# Only reset the last handle if the user called this # Only reset the last handle if the user called this
self.theProject.data.setLastHandle(None, "viewer") self._project.data.setLastHandle(None, "viewer")
# Hide the panel # Hide the panel
bPos = self.splitMain.sizes() bPos = self.splitMain.sizes()
@@ -1391,7 +1400,7 @@ class GuiMain(QMainWindow):
"""Handle the index lookup of a tag and display an alert if the """Handle the index lookup of a tag and display an alert if the
tag cannot be found. tag cannot be found.
""" """
tHandle, sTitle = self.theProject.index.getTagSource(tag) tHandle, sTitle = self._project.index.getTagSource(tag)
if tHandle is None: if tHandle is None:
self.makeAlert(self.tr( self.makeAlert(self.tr(
"Could not find the reference for tag '{0}'. It either doesn't " "Could not find the reference for tag '{0}'. It either doesn't "
@@ -1438,7 +1447,7 @@ class GuiMain(QMainWindow):
if tHandle is not None: if tHandle is not None:
if mode == nwDocMode.EDIT: if mode == nwDocMode.EDIT:
tLine = None tLine = None
hItem = self.theProject.index.getItemHeader(tHandle, sTitle) hItem = self._project.index.getItemHeader(tHandle, sTitle)
if hItem is not None: if hItem is not None:
tLine = hItem.line tLine = hItem.line
self.openDocument(tHandle, tLine=tLine, changeFocus=setFocus) self.openDocument(tHandle, tLine=tLine, changeFocus=setFocus)
@@ -1491,8 +1500,8 @@ class GuiMain(QMainWindow):
def _autoSaveProject(self) -> None: def _autoSaveProject(self) -> None:
"""Autosave of the project. This is a timer-activated slot.""" """Autosave of the project. This is a timer-activated slot."""
doSave = self.hasProject doSave = self.hasProject
doSave &= self.theProject.projChanged doSave &= self._project.projChanged
doSave &= self.theProject.storage.isOpen() doSave &= self._project.storage.isOpen()
if doSave: if doSave:
logger.debug("Autosaving project") logger.debug("Autosaving project")
self.saveProject(autoSave=True) self.saveProject(autoSave=True)
@@ -1512,14 +1521,14 @@ class GuiMain(QMainWindow):
if not self.hasProject: if not self.hasProject:
self.mainStatus.setProjectStats(0, 0) self.mainStatus.setProjectStats(0, 0)
self.theProject.updateWordCounts() self._project.updateWordCounts()
if CONFIG.incNotesWCount: if CONFIG.incNotesWCount:
iTotal = sum(self.theProject.data.initCounts) iTotal = sum(self._project.data.initCounts)
cTotal = sum(self.theProject.data.currCounts) cTotal = sum(self._project.data.currCounts)
self.mainStatus.setProjectStats(cTotal, cTotal - iTotal) self.mainStatus.setProjectStats(cTotal, cTotal - iTotal)
else: else:
iNovel, _ = self.theProject.data.initCounts iNovel, _ = self._project.data.initCounts
cNovel, _ = self.theProject.data.currCounts cNovel, _ = self._project.data.currCounts
self.mainStatus.setProjectStats(cNovel, cNovel - iNovel) self.mainStatus.setProjectStats(cNovel, cNovel - iNovel)
return return
+8 -9
View File
@@ -65,8 +65,7 @@ class GuiManuscriptBuild(QDialog):
logger.debug("Create: GuiManuscriptBuild") logger.debug("Create: GuiManuscriptBuild")
self.setObjectName("GuiManuscriptBuild") self.setObjectName("GuiManuscriptBuild")
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
self._parent = parent self._parent = parent
self._build = build self._build = build
@@ -82,7 +81,7 @@ class GuiManuscriptBuild(QDialog):
wWin = CONFIG.pxInt(620) wWin = CONFIG.pxInt(620)
hWin = CONFIG.pxInt(360) hWin = CONFIG.pxInt(360)
pOptions = self.theProject.options pOptions = self.mainGui.project.options
self.resize( self.resize(
CONFIG.pxInt(pOptions.getInt("GuiManuscriptBuild", "winWidth", wWin)), CONFIG.pxInt(pOptions.getInt("GuiManuscriptBuild", "winWidth", wWin)),
CONFIG.pxInt(pOptions.getInt("GuiManuscriptBuild", "winHeight", hWin)) CONFIG.pxInt(pOptions.getInt("GuiManuscriptBuild", "winHeight", hWin))
@@ -280,7 +279,7 @@ class GuiManuscriptBuild(QDialog):
@pyqtSlot() @pyqtSlot()
def _doResetBuildName(self): def _doResetBuildName(self):
"""Generate a default build name.""" """Generate a default build name."""
bName = f"{self.theProject.data.name} - {self._build.name}" bName = f"{self.mainGui.project.data.name} - {self._build.name}"
self.buildName.setText(bName) self.buildName.setText(bName)
self._build.setLastBuildName(bName) self._build.setLastBuildName(bName)
return return
@@ -321,7 +320,7 @@ class GuiManuscriptBuild(QDialog):
): ):
return False return False
docBuild = NWBuildDocument(self.theProject, self._build) docBuild = NWBuildDocument(self.mainGui.project, self._build)
docBuild.queueAll() docBuild.queueAll()
self.buildProgress.setMaximum(len(docBuild)) self.buildProgress.setMaximum(len(docBuild))
@@ -354,7 +353,7 @@ class GuiManuscriptBuild(QDialog):
fmtWidth = CONFIG.rpxInt(mainSplit[0]) fmtWidth = CONFIG.rpxInt(mainSplit[0])
sumWidth = CONFIG.rpxInt(mainSplit[1]) sumWidth = CONFIG.rpxInt(mainSplit[1])
pOptions = self.theProject.options pOptions = self.mainGui.project.options
pOptions.setValue("GuiManuscriptBuild", "winWidth", winWidth) pOptions.setValue("GuiManuscriptBuild", "winWidth", winWidth)
pOptions.setValue("GuiManuscriptBuild", "winHeight", winHeight) pOptions.setValue("GuiManuscriptBuild", "winHeight", winHeight)
pOptions.setValue("GuiManuscriptBuild", "fmtWidth", fmtWidth) pOptions.setValue("GuiManuscriptBuild", "fmtWidth", fmtWidth)
@@ -366,9 +365,9 @@ class GuiManuscriptBuild(QDialog):
def _populateContentList(self): def _populateContentList(self):
"""Build the content list.""" """Build the content list."""
rootMap = {} rootMap = {}
filtered = self._build.buildItemFilter(self.theProject) filtered = self._build.buildItemFilter(self.mainGui.project)
self.listContent.clear() self.listContent.clear()
for nwItem in self.theProject.tree: for nwItem in self.mainGui.project.tree:
tHandle = nwItem.itemHandle tHandle = nwItem.itemHandle
rHandle = nwItem.itemRoot rHandle = nwItem.itemRoot
@@ -377,7 +376,7 @@ class GuiManuscriptBuild(QDialog):
if filtered.get(tHandle, (False, 0))[0]: if filtered.get(tHandle, (False, 0))[0]:
if rHandle not in rootMap: if rHandle not in rootMap:
rItem = self.theProject.tree[rHandle] rItem = self.mainGui.project.tree[rHandle]
if isinstance(rItem, NWItem): if isinstance(rItem, NWItem):
rootMap[rHandle] = rItem.itemName rootMap[rHandle] = rItem.itemName
+12 -14
View File
@@ -72,10 +72,9 @@ class GuiManuscript(QDialog):
if CONFIG.osDarwin: if CONFIG.osDarwin:
self.setWindowFlag(Qt.WindowType.Tool) self.setWindowFlag(Qt.WindowType.Tool)
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
self._builds = BuildCollection(self.theProject) self._builds = BuildCollection(self.mainGui.project)
self._buildMap: dict[str, QListWidgetItem] = {} self._buildMap: dict[str, QListWidgetItem] = {}
self.setWindowTitle(self.tr("Build Manuscript")) self.setWindowTitle(self.tr("Build Manuscript"))
@@ -86,7 +85,7 @@ class GuiManuscript(QDialog):
wWin = CONFIG.pxInt(900) wWin = CONFIG.pxInt(900)
hWin = CONFIG.pxInt(600) hWin = CONFIG.pxInt(600)
pOptions = self.theProject.options pOptions = self.mainGui.project.options
self.resize( self.resize(
CONFIG.pxInt(pOptions.getInt("GuiManuscript", "winWidth", wWin)), CONFIG.pxInt(pOptions.getInt("GuiManuscript", "winWidth", wWin)),
CONFIG.pxInt(pOptions.getInt("GuiManuscript", "winHeight", hWin)) CONFIG.pxInt(pOptions.getInt("GuiManuscript", "winHeight", hWin))
@@ -211,7 +210,7 @@ class GuiManuscript(QDialog):
self._updateBuildsList() self._updateBuildsList()
logger.debug("Loading build cache") logger.debug("Loading build cache")
cache = CONFIG.dataPath("cache") / f"build_{self.theProject.data.uuid}.json" cache = CONFIG.dataPath("cache") / f"build_{self.mainGui.project.data.uuid}.json"
if cache.is_file(): if cache.is_file():
try: try:
with open(cache, mode="r", encoding="utf-8") as fObj: with open(cache, mode="r", encoding="utf-8") as fObj:
@@ -290,7 +289,7 @@ class GuiManuscript(QDialog):
if build is None: if build is None:
return return
docBuild = NWBuildDocument(self.theProject, build) docBuild = NWBuildDocument(self.mainGui.project, build)
docBuild.queueAll() docBuild.queueAll()
self.docPreview.beginNewBuild(len(docBuild)) self.docPreview.beginNewBuild(len(docBuild))
@@ -310,7 +309,7 @@ class GuiManuscript(QDialog):
self._updatePreview(result, build) self._updatePreview(result, build)
logger.debug("Saving build cache") logger.debug("Saving build cache")
cache = CONFIG.dataPath("cache") / f"build_{self.theProject.data.uuid}.json" cache = CONFIG.dataPath("cache") / f"build_{self.mainGui.project.data.uuid}.json"
try: try:
with open(cache, mode="w+", encoding="utf-8") as outFile: with open(cache, mode="w+", encoding="utf-8") as outFile:
outFile.write(json.dumps(result, indent=2)) outFile.write(json.dumps(result, indent=2))
@@ -391,7 +390,7 @@ class GuiManuscript(QDialog):
optsWidth = CONFIG.rpxInt(mainSplit[0]) optsWidth = CONFIG.rpxInt(mainSplit[0])
viewWidth = CONFIG.rpxInt(mainSplit[1]) viewWidth = CONFIG.rpxInt(mainSplit[1])
pOptions = self.theProject.options pOptions = self.mainGui.project.options
pOptions.setValue("GuiManuscript", "winWidth", winWidth) pOptions.setValue("GuiManuscript", "winWidth", winWidth)
pOptions.setValue("GuiManuscript", "winHeight", winHeight) pOptions.setValue("GuiManuscript", "winHeight", winHeight)
pOptions.setValue("GuiManuscript", "optsWidth", optsWidth) pOptions.setValue("GuiManuscript", "optsWidth", optsWidth)
@@ -450,8 +449,7 @@ class _PreviewWidget(QTextBrowser):
def __init__(self, mainGui: GuiMain): def __init__(self, mainGui: GuiMain):
super().__init__(parent=mainGui) super().__init__(parent=mainGui)
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
self._docTime = 0 self._docTime = 0
self._buildName = "" self._buildName = ""
@@ -524,12 +522,12 @@ class _PreviewWidget(QTextBrowser):
def setJustify(self, state: bool): def setJustify(self, state: bool):
"""Enable/disable the justify text option.""" """Enable/disable the justify text option."""
options = self.document().defaultTextOption() pOptions = self.document().defaultTextOption()
if state: if state:
options.setAlignment(Qt.AlignJustify) pOptions.setAlignment(Qt.AlignJustify)
else: else:
options.setAlignment(Qt.AlignAbsolute) pOptions.setAlignment(Qt.AlignAbsolute)
self.document().setDefaultTextOption(options) self.document().setDefaultTextOption(pOptions)
return return
def setTextFont(self, family: str, size: int): def setTextFont(self, family: str, size: int):
+9 -12
View File
@@ -76,8 +76,7 @@ class GuiBuildSettings(QDialog):
if CONFIG.osDarwin: if CONFIG.osDarwin:
self.setWindowFlag(Qt.WindowType.Tool) self.setWindowFlag(Qt.WindowType.Tool)
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
self._build = build self._build = build
@@ -89,7 +88,7 @@ class GuiBuildSettings(QDialog):
wWin = CONFIG.pxInt(750) wWin = CONFIG.pxInt(750)
hWin = CONFIG.pxInt(550) hWin = CONFIG.pxInt(550)
pOptions = self.theProject.options pOptions = self.mainGui.project.options
self.resize( self.resize(
CONFIG.pxInt(pOptions.getInt("GuiBuildSettings", "winWidth", wWin)), CONFIG.pxInt(pOptions.getInt("GuiBuildSettings", "winWidth", wWin)),
CONFIG.pxInt(pOptions.getInt("GuiBuildSettings", "winHeight", hWin)) CONFIG.pxInt(pOptions.getInt("GuiBuildSettings", "winHeight", hWin))
@@ -263,7 +262,7 @@ class GuiBuildSettings(QDialog):
treeWidth, filterWidth = self.optTabSelect.mainSplitSizes() treeWidth, filterWidth = self.optTabSelect.mainSplitSizes()
pOptions = self.theProject.options pOptions = self.mainGui.project.options
pOptions.setValue("GuiBuildSettings", "winWidth", winWidth) pOptions.setValue("GuiBuildSettings", "winWidth", winWidth)
pOptions.setValue("GuiBuildSettings", "winHeight", winHeight) pOptions.setValue("GuiBuildSettings", "winHeight", winHeight)
pOptions.setValue("GuiBuildSettings", "treeWidth", treeWidth) pOptions.setValue("GuiBuildSettings", "treeWidth", treeWidth)
@@ -304,8 +303,7 @@ class _FilterTab(QWidget):
def __init__(self, buildMain: GuiBuildSettings, build: BuildSettings) -> None: def __init__(self, buildMain: GuiBuildSettings, build: BuildSettings) -> None:
super().__init__(parent=buildMain) super().__init__(parent=buildMain)
self.mainGui = buildMain.mainGui self.mainGui = buildMain.mainGui
self.theProject = buildMain.mainGui.theProject
self._treeMap: dict[str, QTreeWidgetItem] = {} self._treeMap: dict[str, QTreeWidgetItem] = {}
self._build = build self._build = build
@@ -381,7 +379,7 @@ class _FilterTab(QWidget):
# Assemble GUI # Assemble GUI
# ============ # ============
pOptions = self.theProject.options pOptions = self.mainGui.project.options
self.selectionBox = QVBoxLayout() self.selectionBox = QVBoxLayout()
self.selectionBox.addWidget(self.optTree) self.selectionBox.addWidget(self.optTree)
@@ -447,7 +445,7 @@ class _FilterTab(QWidget):
logger.debug("Building project tree") logger.debug("Building project tree")
self._treeMap = {} self._treeMap = {}
self.optTree.clear() self.optTree.clear()
for nwItem in self.theProject.getProjectItems(): for nwItem in self.mainGui.project.getProjectItems():
tHandle = nwItem.itemHandle tHandle = nwItem.itemHandle
pHandle = nwItem.itemParent pHandle = nwItem.itemParent
@@ -523,7 +521,7 @@ class _FilterTab(QWidget):
# Root Classes # Root Classes
self.filterOpt.addLabel(self.tr("Select Root Folders")) self.filterOpt.addLabel(self.tr("Select Root Folders"))
for tHandle, nwItem in self.theProject.tree.iterRoots(None): for tHandle, nwItem in self.mainGui.project.tree.iterRoots(None):
if not nwItem.isInactiveClass(): if not nwItem.isInactiveClass():
itemIcon = CONFIG.theme.getItemIcon( itemIcon = CONFIG.theme.getItemIcon(
nwItem.itemType, nwItem.itemClass, nwItem.itemLayout nwItem.itemType, nwItem.itemClass, nwItem.itemLayout
@@ -559,7 +557,7 @@ class _FilterTab(QWidget):
def _setTreeItemMode(self) -> None: def _setTreeItemMode(self) -> None:
"""Update the filtered mode icon on all items.""" """Update the filtered mode icon on all items."""
filtered = self._build.buildItemFilter(self.theProject) filtered = self._build.buildItemFilter(self.mainGui.project)
for tHandle, item in self._treeMap.items(): for tHandle, item in self._treeMap.items():
allow, mode = filtered.get(tHandle, (False, FilterMode.UNKNOWN)) allow, mode = filtered.get(tHandle, (False, FilterMode.UNKNOWN))
if mode == FilterMode.INCLUDED: if mode == FilterMode.INCLUDED:
@@ -599,8 +597,7 @@ class _HeadingsTab(QWidget):
def __init__(self, buildMain: GuiBuildSettings, build: BuildSettings) -> None: def __init__(self, buildMain: GuiBuildSettings, build: BuildSettings) -> None:
super().__init__(parent=buildMain) super().__init__(parent=buildMain)
self.mainGui = buildMain.mainGui self.mainGui = buildMain.mainGui
self.theProject = buildMain.mainGui.theProject
self._build = build self._build = build
self._editing = 0 self._editing = 0
+4 -5
View File
@@ -72,15 +72,14 @@ class GuiWritingStats(QDialog):
if CONFIG.osDarwin: if CONFIG.osDarwin:
self.setWindowFlag(Qt.WindowType.Tool) self.setWindowFlag(Qt.WindowType.Tool)
self.mainGui = mainGui self.mainGui = mainGui
self.theProject = mainGui.theProject
self.logData = [] self.logData = []
self.filterData = [] self.filterData = []
self.timeFilter = 0.0 self.timeFilter = 0.0
self.wordOffset = 0 self.wordOffset = 0
pOptions = self.theProject.options pOptions = self.mainGui.project.options
self.setWindowTitle(self.tr("Writing Statistics")) self.setWindowTitle(self.tr("Writing Statistics"))
self.setMinimumWidth(CONFIG.pxInt(420)) self.setMinimumWidth(CONFIG.pxInt(420))
@@ -334,7 +333,7 @@ class GuiWritingStats(QDialog):
showIdleTime = self.showIdleTime.isChecked() showIdleTime = self.showIdleTime.isChecked()
histMax = self.histMax.value() histMax = self.histMax.value()
pOptions = self.theProject.options pOptions = self.mainGui.project.options
pOptions.setValue("GuiWritingStats", "winWidth", winWidth) pOptions.setValue("GuiWritingStats", "winWidth", winWidth)
pOptions.setValue("GuiWritingStats", "winHeight", winHeight) pOptions.setValue("GuiWritingStats", "winHeight", winHeight)
pOptions.setValue("GuiWritingStats", "widthCol0", widthCol0) pOptions.setValue("GuiWritingStats", "widthCol0", widthCol0)
@@ -442,7 +441,7 @@ class GuiWritingStats(QDialog):
ttTime = 0 ttTime = 0
ttIdle = 0 ttIdle = 0
for record in self.theProject.session.iterRecords(): for record in self.mainGui.project.session.iterRecords():
rType = record.get("type") rType = record.get("type")
if rType == "initial": if rType == "initial":
self.wordOffset = checkInt(record.get("offset"), 0) self.wordOffset = checkInt(record.get("offset"), 0)
+6 -1
View File
@@ -31,8 +31,9 @@ class MockGuiMain(QObject):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self._project = None
self.hasProject = True self.hasProject = True
self.theProject = None
self.mainStatus = MockStatusBar() self.mainStatus = MockStatusBar()
self.projPath = "" self.projPath = ""
@@ -43,6 +44,10 @@ class MockGuiMain(QObject):
return return
@property
def project(self):
return self._project
def postLaunchTasks(self, cmdOpen): def postLaunchTasks(self, cmdOpen):
return return
+1 -1
View File
@@ -35,7 +35,7 @@ def testDlgSplit_Main(qtbot, monkeypatch, nwGUI, projPath, mockRnd):
# Create a new project # Create a new project
buildTestProject(nwGUI, projPath) buildTestProject(nwGUI, projPath)
theProject = nwGUI.theProject theProject = nwGUI.project
projTree = nwGUI.projView.projTree projTree = nwGUI.projView.projTree
docText = ( docText = (
+1 -1
View File
@@ -54,7 +54,7 @@ def testDlgProjDetails_Dialog(qtbot, nwGUI, prjLipsum):
assert projDet.tabMain.wordCountVal.text() == f"{3000:n}" assert projDet.tabMain.wordCountVal.text() == f"{3000:n}"
assert projDet.tabMain.chapCountVal.text() == f"{3:n}" assert projDet.tabMain.chapCountVal.text() == f"{3:n}"
assert projDet.tabMain.sceneCountVal.text() == f"{5:n}" assert projDet.tabMain.sceneCountVal.text() == f"{5:n}"
assert projDet.tabMain.revCountVal.text() == f"{nwGUI.theProject.data.saveCount:n}" assert projDet.tabMain.revCountVal.text() == f"{nwGUI.project.data.saveCount:n}"
assert projDet.tabMain.projPathVal.text() == str(prjLipsum) assert projDet.tabMain.projPathVal.text() == str(prjLipsum)
+4 -4
View File
@@ -51,7 +51,7 @@ def testDlgProjSettings_Dialog(qtbot, monkeypatch, nwGUI):
# Pretend we have a project # Pretend we have a project
nwGUI.hasProject = True nwGUI.hasProject = True
nwGUI.theProject.data.setSpellLang("en") nwGUI.project.data.setSpellLang("en")
# Get the dialog object # Get the dialog object
nwGUI.mainMenu.aProjectSettings.activate(QAction.Trigger) nwGUI.mainMenu.aProjectSettings.activate(QAction.Trigger)
@@ -95,7 +95,7 @@ def testDlgProjSettings_Main(qtbot, monkeypatch, nwGUI, fncPath, projPath, mockR
CONFIG.setBackupPath(fncPath) CONFIG.setBackupPath(fncPath)
# Set some values # Set some values
theProject = nwGUI.theProject theProject = nwGUI.project
theProject.data.setSpellLang("en") theProject.data.setSpellLang("en")
theProject.data.setAuthor("Jane Smith") theProject.data.setAuthor("Jane Smith")
theProject.data.setAutoReplace({"A": "B", "C": "D"}) theProject.data.setAutoReplace({"A": "B", "C": "D"})
@@ -160,7 +160,7 @@ def testDlgProjSettings_StatusImport(qtbot, monkeypatch, nwGUI, fncPath, projPat
CONFIG.setBackupPath(fncPath) CONFIG.setBackupPath(fncPath)
# Set some values # Set some values
theProject = nwGUI.theProject theProject = nwGUI.project
theProject.tree[C.hTitlePage].setStatus(C.sFinished) theProject.tree[C.hTitlePage].setStatus(C.sFinished)
theProject.tree[C.hChapterDoc].setStatus(C.sDraft) theProject.tree[C.hChapterDoc].setStatus(C.sDraft)
theProject.tree[C.hSceneDoc].setStatus(C.sDraft) theProject.tree[C.hSceneDoc].setStatus(C.sDraft)
@@ -361,7 +361,7 @@ def testDlgProjSettings_Replace(qtbot, monkeypatch, nwGUI, fncPath, projPath, mo
CONFIG.setBackupPath(fncPath) CONFIG.setBackupPath(fncPath)
# Set some values # Set some values
theProject = nwGUI.theProject theProject = nwGUI.project
theProject.data.setAutoReplace({ theProject.data.setAutoReplace({
"A": "B", "C": "D" "A": "B", "C": "D"
}) })
+1 -1
View File
@@ -55,7 +55,7 @@ def testDlgWordList_Dialog(qtbot, monkeypatch, nwGUI, projPath):
assert wList.listBox.count() == 0 assert wList.listBox.count() == 0
# Add words # Add words
userDict = UserDictionary(nwGUI.theProject) userDict = UserDictionary(nwGUI.project)
userDict.add("word_a") userDict.add("word_a")
userDict.add("word_c") userDict.add("word_c")
userDict.add("word_g") userDict.add("word_g")
+10 -10
View File
@@ -163,10 +163,10 @@ def testGuiEditor_SaveText(qtbot, monkeypatch, caplog, nwGUI, projPath, ipsumTex
assert "Could not save document." in caplog.text assert "Could not save document." in caplog.text
# Change header level # Change header level
assert nwGUI.theProject.tree[C.hSceneDoc].itemLayout == nwItemLayout.DOCUMENT assert nwGUI.project.tree[C.hSceneDoc].itemLayout == nwItemLayout.DOCUMENT
nwGUI.docEditor.replaceText(longText[1:]) nwGUI.docEditor.replaceText(longText[1:])
assert nwGUI.docEditor.saveText() is True assert nwGUI.docEditor.saveText() is True
assert nwGUI.theProject.tree[C.hSceneDoc].itemLayout == nwItemLayout.DOCUMENT assert nwGUI.project.tree[C.hSceneDoc].itemLayout == nwItemLayout.DOCUMENT
# Regular save # Regular save
assert nwGUI.docEditor.saveText() is True assert nwGUI.docEditor.saveText() is True
@@ -203,9 +203,9 @@ def testGuiEditor_MetaData(qtbot, nwGUI, projPath, mockRnd):
assert nwGUI.docEditor.setCursorPosition(None) is False assert nwGUI.docEditor.setCursorPosition(None) is False
assert nwGUI.docEditor.setCursorPosition(10) is True assert nwGUI.docEditor.setCursorPosition(10) is True
assert nwGUI.docEditor.getCursorPosition() == 10 assert nwGUI.docEditor.getCursorPosition() == 10
assert nwGUI.theProject.tree[C.hSceneDoc].cursorPos != 10 assert nwGUI.project.tree[C.hSceneDoc].cursorPos != 10
nwGUI.docEditor.saveCursorPosition() nwGUI.docEditor.saveCursorPosition()
assert nwGUI.theProject.tree[C.hSceneDoc].cursorPos == 10 assert nwGUI.project.tree[C.hSceneDoc].cursorPos == 10
assert nwGUI.docEditor.setCursorLine(None) is False assert nwGUI.docEditor.setCursorLine(None) is False
assert nwGUI.docEditor.setCursorLine(3) is True assert nwGUI.docEditor.setCursorLine(3) is True
@@ -1067,7 +1067,7 @@ def testGuiEditor_Tags(qtbot, nwGUI, projPath, ipsumText, mockRnd):
# Create Character # Create Character
theText = "### Jane Doe\n\n@tag: Jane\n\n" + ipsumText[1] + "\n\n" theText = "### Jane Doe\n\n@tag: Jane\n\n" + ipsumText[1] + "\n\n"
cHandle = nwGUI.theProject.newFile("Jane Doe", C.hCharRoot) cHandle = nwGUI.project.newFile("Jane Doe", C.hCharRoot)
assert nwGUI.openDocument(cHandle) is True assert nwGUI.openDocument(cHandle) is True
assert nwGUI.docEditor.replaceText(theText) is True assert nwGUI.docEditor.replaceText(theText) is True
assert nwGUI.saveDocument() is True assert nwGUI.saveDocument() is True
@@ -1145,8 +1145,8 @@ def testGuiEditor_WordCounters(qtbot, monkeypatch, nwGUI, projPath, ipsumText, m
assert nwGUI.docEditor.docFooter.wordsText.text() == "Words: 0 (+0)" assert nwGUI.docEditor.docFooter.wordsText.text() == "Words: 0 (+0)"
# Open a document and populate it # Open a document and populate it
nwGUI.theProject.tree[C.hSceneDoc]._initCount = 0 # Clear item's count nwGUI.project.tree[C.hSceneDoc]._initCount = 0 # Clear item's count
nwGUI.theProject.tree[C.hSceneDoc]._wordCount = 0 # Clear item's count nwGUI.project.tree[C.hSceneDoc]._wordCount = 0 # Clear item's count
assert nwGUI.openDocument(C.hSceneDoc) is True assert nwGUI.openDocument(C.hSceneDoc) is True
theText = "\n\n".join(ipsumText) theText = "\n\n".join(ipsumText)
@@ -1170,9 +1170,9 @@ def testGuiEditor_WordCounters(qtbot, monkeypatch, nwGUI, projPath, ipsumText, m
nwGUI.docEditor.wCounterDoc.run() nwGUI.docEditor.wCounterDoc.run()
# nwGUI.docEditor._updateDocCounts(cC, wC, pC) # nwGUI.docEditor._updateDocCounts(cC, wC, pC)
assert nwGUI.theProject.tree[C.hSceneDoc]._charCount == cC assert nwGUI.project.tree[C.hSceneDoc]._charCount == cC
assert nwGUI.theProject.tree[C.hSceneDoc]._wordCount == wC assert nwGUI.project.tree[C.hSceneDoc]._wordCount == wC
assert nwGUI.theProject.tree[C.hSceneDoc]._paraCount == pC assert nwGUI.project.tree[C.hSceneDoc]._paraCount == pC
assert nwGUI.docEditor.docFooter.wordsText.text() == f"Words: {wC} (+{wC})" assert nwGUI.docEditor.docFooter.wordsText.text() == f"Words: {wC} (+{wC})"
# Select all text # Select all text
+3 -3
View File
@@ -40,8 +40,8 @@ def testGuiViewer_Main(qtbot, monkeypatch, nwGUI, prjLipsum):
# Rebuild the index # Rebuild the index
nwGUI.mainMenu.aRebuildIndex.activate(QAction.Trigger) nwGUI.mainMenu.aRebuildIndex.activate(QAction.Trigger)
assert nwGUI.theProject.index._tagsIndex._tags != {} assert nwGUI.project.index._tagsIndex._tags != {}
assert nwGUI.theProject.index._itemIndex._items != {} assert nwGUI.project.index._itemIndex._items != {}
# Select a document in the project tree # Select a document in the project tree
nwGUI.projView.setSelectedHandle("88243afbe5ed8") nwGUI.projView.setSelectedHandle("88243afbe5ed8")
@@ -128,7 +128,7 @@ def testGuiViewer_Main(qtbot, monkeypatch, nwGUI, prjLipsum):
nwGUI.docViewer.reloadText() nwGUI.docViewer.reloadText()
# Change document title # Change document title
nwItem = nwGUI.theProject.tree["4c4f28287af27"] nwItem = nwGUI.project.tree["4c4f28287af27"]
nwItem.setName("Test Title") nwItem.setName("Test Title")
assert nwItem.itemName == "Test Title" assert nwItem.itemName == "Test Title"
nwGUI.docViewer.updateDocInfo("4c4f28287af27") nwGUI.docViewer.updateDocInfo("4c4f28287af27")
+16 -16
View File
@@ -202,14 +202,14 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, projPath, tstPaths, mockRnd):
assert nwGUI.saveProject() assert nwGUI.saveProject()
assert nwGUI.closeProject() assert nwGUI.closeProject()
assert len(nwGUI.theProject.tree) == 0 assert len(nwGUI.project.tree) == 0
assert len(nwGUI.theProject.tree._treeOrder) == 0 assert len(nwGUI.project.tree._treeOrder) == 0
assert len(nwGUI.theProject.tree._treeRoots) == 0 assert len(nwGUI.project.tree._treeRoots) == 0
assert nwGUI.theProject.tree.trashRoot() is None assert nwGUI.project.tree.trashRoot() is None
assert nwGUI.theProject.data.name == "" assert nwGUI.project.data.name == ""
assert nwGUI.theProject.data.title == "" assert nwGUI.project.data.title == ""
assert nwGUI.theProject.data.author == "" assert nwGUI.project.data.author == ""
assert nwGUI.theProject.data.spellCheck is False assert nwGUI.project.data.spellCheck is False
# Check the files # Check the files
projFile = projPath / "nwProject.nwx" projFile = projPath / "nwProject.nwx"
@@ -222,14 +222,14 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, projPath, tstPaths, mockRnd):
assert nwGUI.openProject(projPath) assert nwGUI.openProject(projPath)
# Check that we loaded the data # Check that we loaded the data
assert len(nwGUI.theProject.tree) == 8 assert len(nwGUI.project.tree) == 8
assert len(nwGUI.theProject.tree._treeOrder) == 8 assert len(nwGUI.project.tree._treeOrder) == 8
assert len(nwGUI.theProject.tree._treeRoots) == 4 assert len(nwGUI.project.tree._treeRoots) == 4
assert nwGUI.theProject.tree.trashRoot() is None assert nwGUI.project.tree.trashRoot() is None
assert nwGUI.theProject.data.name == "New Project" assert nwGUI.project.data.name == "New Project"
assert nwGUI.theProject.data.title == "New Novel" assert nwGUI.project.data.title == "New Novel"
assert nwGUI.theProject.data.author == "Jane Doe" assert nwGUI.project.data.author == "Jane Doe"
assert nwGUI.theProject.data.spellCheck is False assert nwGUI.project.data.spellCheck is False
# Check that tree items have been created # Check that tree items have been created
assert nwGUI.projView.projTree._getTreeItem(C.hNovelRoot) is not None assert nwGUI.projView.projTree._getTreeItem(C.hNovelRoot) is not None
+1 -1
View File
@@ -48,7 +48,7 @@ def testGuiNovelTree_TreeItems(qtbot, monkeypatch, nwGUI, projPath, mockRnd):
nwGUI.projView.projTree._getTreeItem(C.hCharRoot).setSelected(True) nwGUI.projView.projTree._getTreeItem(C.hCharRoot).setSelected(True)
nwGUI.projView.projTree.newTreeItem(nwItemType.FILE) nwGUI.projView.projTree.newTreeItem(nwItemType.FILE)
contentPath = nwGUI.theProject.storage.contentPath contentPath = nwGUI.project.storage.contentPath
assert isinstance(contentPath, Path) assert isinstance(contentPath, Path)
(contentPath / "0000000000010.nwd").write_text( (contentPath / "0000000000010.nwd").write_text(
+3 -3
View File
@@ -71,7 +71,7 @@ def testGuiOutline_Main(qtbot, monkeypatch, nwGUI, projPath):
# Option State # Option State
# ============ # ============
pOptions = nwGUI.theProject.options pOptions = nwGUI.project.options
colNames = [h.name for h in nwOutline] colNames = [h.name for h in nwOutline]
colItems = [h for h in nwOutline] colItems = [h for h in nwOutline]
colWidth = {h: outlineTree.DEF_WIDTH[h] for h in nwOutline} colWidth = {h: outlineTree.DEF_WIDTH[h] for h in nwOutline}
@@ -181,7 +181,7 @@ def testGuiOutline_Content(qtbot, nwGUI, prjLipsum):
assert outlineBar.novelValue.itemData(2) == "" # All novels assert outlineBar.novelValue.itemData(2) == "" # All novels
# Add a second novel folder # Add a second novel folder
newHandle = nwGUI.theProject.newRoot(nwItemClass.NOVEL) newHandle = nwGUI.project.newRoot(nwItemClass.NOVEL)
nwGUI.projView.projTree.revealNewTreeItem(newHandle) nwGUI.projView.projTree.revealNewTreeItem(newHandle)
# Check new values in dropdown list # Check new values in dropdown list
@@ -198,7 +198,7 @@ def testGuiOutline_Content(qtbot, nwGUI, prjLipsum):
("Section 4", 4), ("Section 4", 4),
] ]
for dTitle, hLevel in docList: for dTitle, hLevel in docList:
aHandle = nwGUI.theProject.newFile(dTitle, newHandle) aHandle = nwGUI.project.newFile(dTitle, newHandle)
hHash = "#"*hLevel hHash = "#"*hLevel
writeFile(prjLipsum / "content" / f"{aHandle}.nwd", f"{hHash} {dTitle}\n\n") writeFile(prjLipsum / "content" / f"{aHandle}.nwd", f"{hHash} {dTitle}\n\n")
nwGUI.projView.projTree.revealNewTreeItem(aHandle) nwGUI.projView.projTree.revealNewTreeItem(aHandle)
+33 -33
View File
@@ -46,7 +46,7 @@ def testGuiProjTree_NewItems(qtbot, caplog, monkeypatch, nwGUI, projPath, mockRn
projView = nwGUI.projView projView = nwGUI.projView
projTree = nwGUI.projView.projTree projTree = nwGUI.projView.projTree
theProject = nwGUI.theProject theProject = nwGUI.project
# Try to add item with no project # Try to add item with no project
assert projView.projTree.newTreeItem(nwItemType.FILE) is False assert projView.projTree.newTreeItem(nwItemType.FILE) is False
@@ -260,19 +260,19 @@ def testGuiProjTree_MoveItems(qtbot, monkeypatch, nwGUI, projPath, mockRnd):
# =========== # ===========
projView.setSelectedHandle(C.hNovelRoot) projView.setSelectedHandle(C.hNovelRoot)
assert nwGUI.theProject.tree._treeOrder.index(C.hNovelRoot) == 0 assert nwGUI.project.tree._treeOrder.index(C.hNovelRoot) == 0
# Move novel folder up # Move novel folder up
assert projTree.moveTreeItem(-1) is False assert projTree.moveTreeItem(-1) is False
assert nwGUI.theProject.tree._treeOrder.index(C.hNovelRoot) == 0 assert nwGUI.project.tree._treeOrder.index(C.hNovelRoot) == 0
# Move novel folder down # Move novel folder down
assert projTree.moveTreeItem(1) is True assert projTree.moveTreeItem(1) is True
assert nwGUI.theProject.tree._treeOrder.index(C.hNovelRoot) == 1 assert nwGUI.project.tree._treeOrder.index(C.hNovelRoot) == 1
# Move novel folder up again # Move novel folder up again
assert projTree.moveTreeItem(-1) is True assert projTree.moveTreeItem(-1) is True
assert nwGUI.theProject.tree._treeOrder.index(C.hNovelRoot) == 0 assert nwGUI.project.tree._treeOrder.index(C.hNovelRoot) == 0
# Clean up # Clean up
# qtbot.stop() # qtbot.stop()
@@ -348,7 +348,7 @@ def testGuiProjTree_RequestDeleteItem(qtbot, caplog, monkeypatch, nwGUI, projPat
C.hChapterDir, C.hChapterDoc, C.hSceneDoc, C.hChapterDir, C.hChapterDoc, C.hSceneDoc,
"0000000000010" "0000000000010"
] ]
trashHandle = nwGUI.theProject.tree.trashRoot() trashHandle = nwGUI.project.tree.trashRoot()
assert projTree.getTreeFromHandle(trashHandle) == [ assert projTree.getTreeFromHandle(trashHandle) == [
trashHandle, "0000000000012", "0000000000011" trashHandle, "0000000000012", "0000000000011"
] ]
@@ -368,7 +368,7 @@ def testGuiProjTree_MoveItemToTrash(qtbot, caplog, monkeypatch, nwGUI, projPath,
"""Test moving items to Trash.""" """Test moving items to Trash."""
monkeypatch.setattr(GuiEditLabel, "getLabel", lambda *a, text: (text, True)) monkeypatch.setattr(GuiEditLabel, "getLabel", lambda *a, text: (text, True))
theProject = nwGUI.theProject theProject = nwGUI.project
projTree = nwGUI.projView.projTree projTree = nwGUI.projView.projTree
# Create a project # Create a project
@@ -420,7 +420,7 @@ def testGuiProjTree_PermanentlyDeleteItem(qtbot, caplog, monkeypatch, nwGUI, pro
"""Test permanently deleting items.""" """Test permanently deleting items."""
monkeypatch.setattr(GuiEditLabel, "getLabel", lambda *a, text: (text, True)) monkeypatch.setattr(GuiEditLabel, "getLabel", lambda *a, text: (text, True))
theProject = nwGUI.theProject theProject = nwGUI.project
projTree = nwGUI.projView.projTree projTree = nwGUI.projView.projTree
# Create a project # Create a project
@@ -471,7 +471,7 @@ def testGuiProjTree_EmptyTrash(qtbot, caplog, monkeypatch, nwGUI, projPath, mock
"""Test emptying Trash.""" """Test emptying Trash."""
monkeypatch.setattr(GuiEditLabel, "getLabel", lambda *a, text: (text, True)) monkeypatch.setattr(GuiEditLabel, "getLabel", lambda *a, text: (text, True))
theProject = nwGUI.theProject theProject = nwGUI.project
projTree = nwGUI.projView.projTree projTree = nwGUI.projView.projTree
# No project open # No project open
@@ -541,16 +541,16 @@ def testGuiProjTree_ContextMenu(qtbot, monkeypatch, nwGUI, projPath, mockRnd):
projTree.setExpandedFromHandle(None, True) projTree.setExpandedFromHandle(None, True)
projTree._addTrashRoot() projTree._addTrashRoot()
hTrashRoot = projTree.theProject.tree.trashRoot() hTrashRoot = nwGUI.project.tree.trashRoot()
projTree.setSelectedHandle(C.hCharRoot) projTree.setSelectedHandle(C.hCharRoot)
projTree.newTreeItem(nwItemType.FILE) projTree.newTreeItem(nwItemType.FILE)
projTree.setSelectedHandle(C.hNovelRoot) projTree.setSelectedHandle(C.hNovelRoot)
projTree.newTreeItem(nwItemType.FILE, isNote=True) projTree.newTreeItem(nwItemType.FILE, isNote=True)
nwGUI.theProject.newFile("SubNote", hNovelNote) nwGUI.project.newFile("SubNote", hNovelNote)
projTree.revealNewTreeItem(hSubNote) projTree.revealNewTreeItem(hSubNote)
assert nwGUI.theProject.tree[hSubNote].itemParent == hNovelNote assert nwGUI.project.tree[hSubNote].itemParent == hNovelNote
def itemPos(tHandle): def itemPos(tHandle):
return projTree.visualItemRect(projTree._getTreeItem(tHandle)).center() return projTree.visualItemRect(projTree._getTreeItem(tHandle)).center()
@@ -578,7 +578,7 @@ def testGuiProjTree_ContextMenu(qtbot, monkeypatch, nwGUI, projPath, mockRnd):
# Direct Edit Functions # Direct Edit Functions
# ===================== # =====================
# Trigger the dedicated functions the menu entries connect to # Trigger the dedicated functions the menu entries connect to
nwItem = projTree.theProject.tree[hNovelNote] nwItem = nwGUI.project.tree[hNovelNote]
# Toggle active flag # Toggle active flag
assert nwItem.isActive is True assert nwItem.isActive is True
@@ -619,17 +619,17 @@ def testGuiProjTree_ContextMenu(qtbot, monkeypatch, nwGUI, projPath, mockRnd):
with monkeypatch.context() as mp: with monkeypatch.context() as mp:
mp.setattr(QMessageBox, "result", lambda *a: QMessageBox.No) mp.setattr(QMessageBox, "result", lambda *a: QMessageBox.No)
projTree._covertFolderToFile(hNewFolderOne, nwItemLayout.DOCUMENT) projTree._covertFolderToFile(hNewFolderOne, nwItemLayout.DOCUMENT)
assert nwGUI.theProject.tree[hNewFolderOne].isFolderType() assert nwGUI.project.tree[hNewFolderOne].isFolderType()
# Convert the first folder to a document # Convert the first folder to a document
projTree._covertFolderToFile(hNewFolderOne, nwItemLayout.DOCUMENT) projTree._covertFolderToFile(hNewFolderOne, nwItemLayout.DOCUMENT)
assert nwGUI.theProject.tree[hNewFolderOne].isFileType() assert nwGUI.project.tree[hNewFolderOne].isFileType()
assert nwGUI.theProject.tree[hNewFolderOne].isDocumentLayout() assert nwGUI.project.tree[hNewFolderOne].isDocumentLayout()
# Convert the second folder to a note # Convert the second folder to a note
projTree._covertFolderToFile(hNewFolderTwo, nwItemLayout.NOTE) projTree._covertFolderToFile(hNewFolderTwo, nwItemLayout.NOTE)
assert nwGUI.theProject.tree[hNewFolderTwo].isFileType() assert nwGUI.project.tree[hNewFolderTwo].isFileType()
assert nwGUI.theProject.tree[hNewFolderTwo].isNoteLayout() assert nwGUI.project.tree[hNewFolderTwo].isNoteLayout()
# qtbot.stop() # qtbot.stop()
@@ -649,7 +649,7 @@ def testGuiProjTree_MergeDocuments(qtbot, monkeypatch, nwGUI, projPath, mockRnd,
# Create a project # Create a project
buildTestProject(nwGUI, projPath) buildTestProject(nwGUI, projPath)
theProject = nwGUI.theProject theProject = nwGUI.project
projTree = nwGUI.projView.projTree projTree = nwGUI.projView.projTree
mergedDoc1 = "0000000000014" mergedDoc1 = "0000000000014"
@@ -751,7 +751,7 @@ def testGuiProjTree_SplitDocument(qtbot, monkeypatch, nwGUI, projPath, mockRnd,
# Create a project # Create a project
buildTestProject(nwGUI, projPath) buildTestProject(nwGUI, projPath)
theProject = nwGUI.theProject theProject = nwGUI.project
projTree = nwGUI.projView.projTree projTree = nwGUI.projView.projTree
docText = ( docText = (
@@ -852,7 +852,7 @@ def testGuiProjTree_Duplicate(qtbot, monkeypatch, nwGUI: GuiMain, projPath, mock
"""Test the duplicate items function.""" """Test the duplicate items function."""
# Create a project # Create a project
buildTestProject(nwGUI, projPath) buildTestProject(nwGUI, projPath)
assert len(nwGUI.theProject.tree) == 8 assert len(nwGUI.project.tree) == 8
projTree = nwGUI.projView.projTree projTree = nwGUI.projView.projTree
projTree._getTreeItem(C.hNovelRoot).setExpanded(True) # type: ignore projTree._getTreeItem(C.hNovelRoot).setExpanded(True) # type: ignore
@@ -860,28 +860,28 @@ def testGuiProjTree_Duplicate(qtbot, monkeypatch, nwGUI: GuiMain, projPath, mock
# Nothing to do # Nothing to do
assert projTree._duplicateFromHandle(C.hInvalid) is False assert projTree._duplicateFromHandle(C.hInvalid) is False
assert len(nwGUI.theProject.tree) == 8 assert len(nwGUI.project.tree) == 8
# Duplicate title page, but select no # Duplicate title page, but select no
with monkeypatch.context() as mp: with monkeypatch.context() as mp:
mp.setattr(QMessageBox, "result", lambda *a: QMessageBox.No) mp.setattr(QMessageBox, "result", lambda *a: QMessageBox.No)
assert projTree._duplicateFromHandle(C.hTitlePage) is False assert projTree._duplicateFromHandle(C.hTitlePage) is False
assert len(nwGUI.theProject.tree) == 8 assert len(nwGUI.project.tree) == 8
# Duplicate title page # Duplicate title page
assert projTree._duplicateFromHandle(C.hTitlePage) is True assert projTree._duplicateFromHandle(C.hTitlePage) is True
assert len(nwGUI.theProject.tree) == 9 assert len(nwGUI.project.tree) == 9
# Duplicate folder # Duplicate folder
assert projTree._duplicateFromHandle(C.hChapterDir) is True assert projTree._duplicateFromHandle(C.hChapterDir) is True
assert len(nwGUI.theProject.tree) == 12 assert len(nwGUI.project.tree) == 12
# Duplicate novel root # Duplicate novel root
assert projTree._duplicateFromHandle(C.hNovelRoot) is True assert projTree._duplicateFromHandle(C.hNovelRoot) is True
assert len(nwGUI.theProject.tree) == 21 assert len(nwGUI.project.tree) == 21
# Check tree order that all items are next to eachother # Check tree order that all items are next to eachother
assert nwGUI.theProject.tree._treeOrder == [ assert nwGUI.project.tree._treeOrder == [
C.hNovelRoot, C.hTitlePage, "0000000000010", C.hChapterDir, C.hChapterDoc, C.hSceneDoc, C.hNovelRoot, C.hTitlePage, "0000000000010", C.hChapterDir, C.hChapterDoc, C.hSceneDoc,
"0000000000011", "0000000000012", "0000000000013", "0000000000014", "0000000000015", "0000000000011", "0000000000012", "0000000000013", "0000000000014", "0000000000015",
"0000000000016", "0000000000017", "0000000000018", "0000000000019", "000000000001a", "0000000000016", "0000000000017", "0000000000018", "0000000000019", "000000000001a",
@@ -889,7 +889,7 @@ def testGuiProjTree_Duplicate(qtbot, monkeypatch, nwGUI: GuiMain, projPath, mock
] ]
# Make the duplicator stop early # Make the duplicator stop early
content = nwGUI.theProject.storage.contentPath content = nwGUI.project.storage.contentPath
assert isinstance(content, Path) assert isinstance(content, Path)
(content / "000000000001e.nwd").touch() (content / "000000000001e.nwd").touch()
assert (content / "000000000001e.nwd").exists() assert (content / "000000000001e.nwd").exists()
@@ -897,7 +897,7 @@ def testGuiProjTree_Duplicate(qtbot, monkeypatch, nwGUI: GuiMain, projPath, mock
# Should only create the folder, and skip the two files because the # Should only create the folder, and skip the two files because the
# next handle is already a file # next handle is already a file
assert projTree._duplicateFromHandle(C.hChapterDir) is True assert projTree._duplicateFromHandle(C.hChapterDir) is True
assert len(nwGUI.theProject.tree) == 22 assert len(nwGUI.project.tree) == 22
# qtbot.stop() # qtbot.stop()
@@ -938,13 +938,13 @@ def testGuiProjTree_Other(qtbot, monkeypatch, nwGUI: GuiMain, projPath, mockRnd)
assert projTree.revealNewTreeItem(C.hInvalid) is False assert projTree.revealNewTreeItem(C.hInvalid) is False
# Try to add an orphaned file to the tree # Try to add an orphaned file to the tree
nHandle = nwGUI.theProject.newFile("Test", C.hNovelRoot) nHandle = nwGUI.project.newFile("Test", C.hNovelRoot)
nwGUI.theProject.tree[nHandle].setParent(None) # type: ignore nwGUI.project.tree[nHandle].setParent(None) # type: ignore
assert projTree.revealNewTreeItem(nHandle) is False assert projTree.revealNewTreeItem(nHandle) is False
# Try to add an item with unknown parent to the tree # Try to add an item with unknown parent to the tree
nHandle = nwGUI.theProject.newFile("Test", C.hNovelRoot) nHandle = nwGUI.project.newFile("Test", C.hNovelRoot)
nwGUI.theProject.tree[nHandle].setParent(C.hInvalid) # type: ignore nwGUI.project.tree[nHandle].setParent(C.hInvalid) # type: ignore
assert projTree.revealNewTreeItem(nHandle) is False assert projTree.revealNewTreeItem(nHandle) is False
# Method: undoLastMove # Method: undoLastMove
+2 -2
View File
@@ -33,8 +33,8 @@ def testGuiStatusBar_Main(qtbot, nwGUI, projPath, mockRnd):
"""Test the the various features of the status bar. """Test the the various features of the status bar.
""" """
buildTestProject(nwGUI, projPath) buildTestProject(nwGUI, projPath)
cHandle = nwGUI.theProject.newFile("A Note", C.hCharRoot) cHandle = nwGUI.project.newFile("A Note", C.hCharRoot)
newDoc = nwGUI.theProject.storage.getDocument(cHandle) newDoc = nwGUI.project.storage.getDocument(cHandle)
newDoc.writeDocument("# A Note\n\n") newDoc.writeDocument("# A Note\n\n")
nwGUI.projView.projTree.revealNewTreeItem(cHandle) nwGUI.projView.projTree.revealNewTreeItem(cHandle)
nwGUI.rebuildIndex(beQuiet=True) nwGUI.rebuildIndex(beQuiet=True)
+2 -2
View File
@@ -45,7 +45,7 @@ def testManuscript_Init(monkeypatch, qtbot: QtBot, nwGUI: GuiMain, projPath: Pat
"""Test the init/main functionality of the GuiManuscript dialog.""" """Test the init/main functionality of the GuiManuscript dialog."""
buildTestProject(nwGUI, projPath) buildTestProject(nwGUI, projPath)
nwGUI.openProject(projPath) nwGUI.openProject(projPath)
nwGUI.theProject.storage.getDocument(C.hChapterDoc).writeDocument("## A Chapter\n\n\t\tHi") nwGUI.project.storage.getDocument(C.hChapterDoc).writeDocument("## A Chapter\n\n\t\tHi")
allText = "New Novel\nBy Jane Doe\nA Chapter\n\t\tHi\n* * *" allText = "New Novel\nBy Jane Doe\nA Chapter\n\t\tHi\n* * *"
manus = GuiManuscript(nwGUI) manus = GuiManuscript(nwGUI)
@@ -159,7 +159,7 @@ def testManuscript_Features(monkeypatch, qtbot: QtBot, nwGUI: GuiMain, projPath:
manus.show() manus.show()
manus.loadContent() manus.loadContent()
cacheFile = CONFIG.dataPath("cache") / f"build_{nwGUI.theProject.data.uuid}.json" cacheFile = CONFIG.dataPath("cache") / f"build_{nwGUI.project.data.uuid}.json"
manus.buildList.setCurrentRow(0) manus.buildList.setCurrentRow(0)
build = manus._getSelectedBuild() build = manus._getSelectedBuild()
assert isinstance(build, BuildSettings) assert isinstance(build, BuildSettings)
+13 -13
View File
@@ -128,11 +128,11 @@ def testBuildSettings_Filter(qtbot: QtBot, nwGUI: GuiMain, projPath: Path, mockR
"worldRoot": 9, "worldRoot": 9,
} }
hPlotDoc = nwGUI.theProject.newFile("Main Plot", C.hPlotRoot) hPlotDoc = nwGUI.project.newFile("Main Plot", C.hPlotRoot)
hCharDoc = nwGUI.theProject.newFile("Jane Doe", C.hCharRoot) hCharDoc = nwGUI.project.newFile("Jane Doe", C.hCharRoot)
nwGUI.projView.projTree.revealNewTreeItem(hPlotDoc) nwGUI.projView.projTree.revealNewTreeItem(hPlotDoc)
nwGUI.projView.projTree.revealNewTreeItem(hCharDoc) nwGUI.projView.projTree.revealNewTreeItem(hCharDoc)
nwGUI.theProject.tree[hPlotDoc].setActive(False) # type: ignore nwGUI.project.tree[hPlotDoc].setActive(False) # type: ignore
# Create the dialog and populate it # Create the dialog and populate it
bSettings = GuiBuildSettings(nwGUI, build) bSettings = GuiBuildSettings(nwGUI, build)
@@ -167,7 +167,7 @@ def testBuildSettings_Filter(qtbot: QtBot, nwGUI: GuiMain, projPath: Path, mockR
# Switch off novel docs # Switch off novel docs
filterTab.filterOpt._widgets[switchMap["incNovel"]].setChecked(False) filterTab.filterOpt._widgets[switchMap["incNovel"]].setChecked(False)
assert build.buildItemFilter(nwGUI.theProject) == { assert build.buildItemFilter(nwGUI.project) == {
C.hNovelRoot: (False, FilterMode.SKIPPED), C.hNovelRoot: (False, FilterMode.SKIPPED),
C.hTitlePage: (False, FilterMode.FILTERED), C.hTitlePage: (False, FilterMode.FILTERED),
C.hChapterDir: (False, FilterMode.SKIPPED), C.hChapterDir: (False, FilterMode.SKIPPED),
@@ -182,7 +182,7 @@ def testBuildSettings_Filter(qtbot: QtBot, nwGUI: GuiMain, projPath: Path, mockR
# Switch on note docs # Switch on note docs
filterTab.filterOpt._widgets[switchMap["incNotes"]].setChecked(True) filterTab.filterOpt._widgets[switchMap["incNotes"]].setChecked(True)
assert build.buildItemFilter(nwGUI.theProject) == { assert build.buildItemFilter(nwGUI.project) == {
C.hNovelRoot: (False, FilterMode.SKIPPED), C.hNovelRoot: (False, FilterMode.SKIPPED),
C.hTitlePage: (False, FilterMode.FILTERED), C.hTitlePage: (False, FilterMode.FILTERED),
C.hChapterDir: (False, FilterMode.SKIPPED), C.hChapterDir: (False, FilterMode.SKIPPED),
@@ -197,7 +197,7 @@ def testBuildSettings_Filter(qtbot: QtBot, nwGUI: GuiMain, projPath: Path, mockR
# Switch on inactive docs # Switch on inactive docs
filterTab.filterOpt._widgets[switchMap["incInactive"]].setChecked(True) filterTab.filterOpt._widgets[switchMap["incInactive"]].setChecked(True)
assert build.buildItemFilter(nwGUI.theProject) == { assert build.buildItemFilter(nwGUI.project) == {
C.hNovelRoot: (False, FilterMode.SKIPPED), C.hNovelRoot: (False, FilterMode.SKIPPED),
C.hTitlePage: (False, FilterMode.FILTERED), C.hTitlePage: (False, FilterMode.FILTERED),
C.hChapterDir: (False, FilterMode.SKIPPED), C.hChapterDir: (False, FilterMode.SKIPPED),
@@ -214,7 +214,7 @@ def testBuildSettings_Filter(qtbot: QtBot, nwGUI: GuiMain, projPath: Path, mockR
filterTab._treeMap[C.hChapterDoc].setSelected(True) filterTab._treeMap[C.hChapterDoc].setSelected(True)
filterTab._treeMap[C.hSceneDoc].setSelected(True) filterTab._treeMap[C.hSceneDoc].setSelected(True)
filterTab.includedButton.click() filterTab.includedButton.click()
assert build.buildItemFilter(nwGUI.theProject) == { assert build.buildItemFilter(nwGUI.project) == {
C.hNovelRoot: (False, FilterMode.SKIPPED), C.hNovelRoot: (False, FilterMode.SKIPPED),
C.hTitlePage: (False, FilterMode.FILTERED), C.hTitlePage: (False, FilterMode.FILTERED),
C.hChapterDir: (False, FilterMode.SKIPPED), C.hChapterDir: (False, FilterMode.SKIPPED),
@@ -232,7 +232,7 @@ def testBuildSettings_Filter(qtbot: QtBot, nwGUI: GuiMain, projPath: Path, mockR
filterTab._treeMap[hPlotDoc].setSelected(True) # type: ignore filterTab._treeMap[hPlotDoc].setSelected(True) # type: ignore
filterTab._treeMap[hCharDoc].setSelected(True) # type: ignore filterTab._treeMap[hCharDoc].setSelected(True) # type: ignore
filterTab.excludedButton.click() filterTab.excludedButton.click()
assert build.buildItemFilter(nwGUI.theProject) == { assert build.buildItemFilter(nwGUI.project) == {
C.hNovelRoot: (False, FilterMode.SKIPPED), C.hNovelRoot: (False, FilterMode.SKIPPED),
C.hTitlePage: (False, FilterMode.FILTERED), C.hTitlePage: (False, FilterMode.FILTERED),
C.hChapterDir: (False, FilterMode.SKIPPED), C.hChapterDir: (False, FilterMode.SKIPPED),
@@ -247,7 +247,7 @@ def testBuildSettings_Filter(qtbot: QtBot, nwGUI: GuiMain, projPath: Path, mockR
# Switch on novel docs # Switch on novel docs
filterTab.filterOpt._widgets[switchMap["incNovel"]].setChecked(True) filterTab.filterOpt._widgets[switchMap["incNovel"]].setChecked(True)
assert build.buildItemFilter(nwGUI.theProject) == { assert build.buildItemFilter(nwGUI.project) == {
C.hNovelRoot: (False, FilterMode.SKIPPED), C.hNovelRoot: (False, FilterMode.SKIPPED),
C.hTitlePage: (True, FilterMode.FILTERED), # Now enabled C.hTitlePage: (True, FilterMode.FILTERED), # Now enabled
C.hChapterDir: (False, FilterMode.SKIPPED), C.hChapterDir: (False, FilterMode.SKIPPED),
@@ -264,7 +264,7 @@ def testBuildSettings_Filter(qtbot: QtBot, nwGUI: GuiMain, projPath: Path, mockR
filterTab.optTree.clearSelection() filterTab.optTree.clearSelection()
filterTab._treeMap[C.hNovelRoot].setSelected(True) filterTab._treeMap[C.hNovelRoot].setSelected(True)
filterTab.resetButton.click() filterTab.resetButton.click()
assert build.buildItemFilter(nwGUI.theProject) == { assert build.buildItemFilter(nwGUI.project) == {
C.hNovelRoot: (False, FilterMode.SKIPPED), C.hNovelRoot: (False, FilterMode.SKIPPED),
C.hTitlePage: (True, FilterMode.FILTERED), C.hTitlePage: (True, FilterMode.FILTERED),
C.hChapterDir: (False, FilterMode.SKIPPED), C.hChapterDir: (False, FilterMode.SKIPPED),
@@ -284,7 +284,7 @@ def testBuildSettings_Filter(qtbot: QtBot, nwGUI: GuiMain, projPath: Path, mockR
filterTab._treeMap[hPlotDoc].setSelected(True) # type: ignore filterTab._treeMap[hPlotDoc].setSelected(True) # type: ignore
filterTab._treeMap[hCharDoc].setSelected(True) # type: ignore filterTab._treeMap[hCharDoc].setSelected(True) # type: ignore
filterTab.resetButton.click() filterTab.resetButton.click()
assert build.buildItemFilter(nwGUI.theProject) == { assert build.buildItemFilter(nwGUI.project) == {
C.hNovelRoot: (False, FilterMode.SKIPPED), C.hNovelRoot: (False, FilterMode.SKIPPED),
C.hTitlePage: (True, FilterMode.FILTERED), C.hTitlePage: (True, FilterMode.FILTERED),
C.hChapterDir: (False, FilterMode.SKIPPED), C.hChapterDir: (False, FilterMode.SKIPPED),
@@ -302,8 +302,8 @@ def testBuildSettings_Filter(qtbot: QtBot, nwGUI: GuiMain, projPath: Path, mockR
C.hNovelRoot, C.hTitlePage, C.hChapterDir, C.hChapterDoc, C.hSceneDoc, C.hNovelRoot, C.hTitlePage, C.hChapterDir, C.hChapterDoc, C.hSceneDoc,
C.hPlotRoot, hPlotDoc, C.hCharRoot, hCharDoc, C.hPlotRoot, hPlotDoc, C.hCharRoot, hCharDoc,
] ]
nwGUI.theProject.tree[hCharDoc].setRoot(None) # type: ignore nwGUI.project.tree[hCharDoc].setRoot(None) # type: ignore
nwGUI.theProject.tree[hPlotDoc].setParent(None) # type: ignore nwGUI.project.tree[hPlotDoc].setParent(None) # type: ignore
filterTab._populateTree() filterTab._populateTree()
assert list(filterTab._treeMap.keys()) == [ assert list(filterTab._treeMap.keys()) == [
C.hNovelRoot, C.hTitlePage, C.hChapterDir, C.hChapterDoc, C.hSceneDoc, C.hNovelRoot, C.hTitlePage, C.hChapterDir, C.hChapterDoc, C.hSceneDoc,
+1 -1
View File
@@ -39,7 +39,7 @@ def testToolWritingStats_Main(qtbot, monkeypatch, nwGUI, projPath, tstPaths):
""" """
# Create a project to work on # Create a project to work on
buildTestProject(nwGUI, projPath) buildTestProject(nwGUI, projPath)
project = nwGUI.theProject project = nwGUI.project
qtbot.wait(100) qtbot.wait(100)
assert nwGUI.saveProject() assert nwGUI.saveProject()
+36 -36
View File
@@ -154,59 +154,59 @@ def cleanProject(path: str | Path):
return return
def buildTestProject(theObject, projPath): def buildTestProject(obj, projPath):
"""Build a standard test project in projPath using theProject """Build a standard test project in projPath using the project
object as the parent. object as the parent.
""" """
from novelwriter.enum import nwItemClass from novelwriter.enum import nwItemClass
from novelwriter.core.project import NWProject from novelwriter.core.project import NWProject
if isinstance(theObject, NWProject): if isinstance(obj, NWProject):
theGUI = None nwGUI = None
theProject = theObject project = obj
else: else:
theGUI = theObject nwGUI = obj
theProject = theObject.theProject project = obj.project
theProject.clearProject() project.clearProject()
theProject.storage.openProjectInPlace(projPath) project.storage.openProjectInPlace(projPath)
theProject.setDefaultStatusImport() project.setDefaultStatusImport()
theProject.data.setUuid("d0f3fe10-c6e6-4310-8bfd-181eb4224eed") project.data.setUuid("d0f3fe10-c6e6-4310-8bfd-181eb4224eed")
theProject.data.setName("New Project") project.data.setName("New Project")
theProject.data.setTitle("New Novel") project.data.setTitle("New Novel")
theProject.data.setAuthor("Jane Doe") project.data.setAuthor("Jane Doe")
# 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.
xHandle = {} xHandle = {}
xHandle[1] = theProject.newRoot(nwItemClass.NOVEL, "Novel") xHandle[1] = project.newRoot(nwItemClass.NOVEL, "Novel")
xHandle[2] = theProject.newRoot(nwItemClass.PLOT, "Plot") xHandle[2] = project.newRoot(nwItemClass.PLOT, "Plot")
xHandle[3] = theProject.newRoot(nwItemClass.CHARACTER, "Characters") xHandle[3] = project.newRoot(nwItemClass.CHARACTER, "Characters")
xHandle[4] = theProject.newRoot(nwItemClass.WORLD, "World") xHandle[4] = project.newRoot(nwItemClass.WORLD, "World")
xHandle[5] = theProject.newFile("Title Page", xHandle[1]) xHandle[5] = project.newFile("Title Page", xHandle[1])
xHandle[6] = theProject.newFolder("New Chapter", xHandle[1]) xHandle[6] = project.newFolder("New Chapter", xHandle[1])
xHandle[7] = theProject.newFile("New Chapter", xHandle[6]) xHandle[7] = project.newFile("New Chapter", xHandle[6])
xHandle[8] = theProject.newFile("New Scene", xHandle[6]) xHandle[8] = project.newFile("New Scene", xHandle[6])
aDoc = theProject.storage.getDocument(xHandle[5]) aDoc = project.storage.getDocument(xHandle[5])
aDoc.writeDocument("#! New Novel\n\n>> By Jane Doe <<\n") aDoc.writeDocument("#! New Novel\n\n>> By Jane Doe <<\n")
theProject.index.reIndexHandle(xHandle[5]) project.index.reIndexHandle(xHandle[5])
aDoc = theProject.storage.getDocument(xHandle[7]) aDoc = project.storage.getDocument(xHandle[7])
aDoc.writeDocument("## %s\n\n" % theProject.tr("New Chapter")) aDoc.writeDocument("## %s\n\n" % project.tr("New Chapter"))
theProject.index.reIndexHandle(xHandle[7]) project.index.reIndexHandle(xHandle[7])
aDoc = theProject.storage.getDocument(xHandle[8]) aDoc = project.storage.getDocument(xHandle[8])
aDoc.writeDocument("### %s\n\n" % theProject.tr("New Scene")) aDoc.writeDocument("### %s\n\n" % project.tr("New Scene"))
theProject.index.reIndexHandle(xHandle[8]) project.index.reIndexHandle(xHandle[8])
theProject.session.startSession() project.session.startSession()
theProject.setProjectChanged(True) project.setProjectChanged(True)
theProject.saveProject(autoSave=True) project.saveProject(autoSave=True)
if theGUI is not None: if nwGUI is not None:
theGUI.hasProject = True nwGUI.hasProject = True
theGUI.rebuildTrees() nwGUI.rebuildTrees()
return return