Remove QMessageBox dependency in NWProject class

This commit is contained in:
Veronica K. B. Olsen
2020-12-05 19:13:36 +01:00
parent 57397fa2bc
commit c17d4de0a5
3 changed files with 49 additions and 47 deletions
+40 -46
View File
@@ -28,12 +28,10 @@
import nw import nw
import logging import logging
import os import os
import shutil
from lxml import etree from lxml import etree
from time import time from time import time
from shutil import make_archive, unpack_archive, copyfile
from PyQt5.QtWidgets import QMessageBox
from nw.core.tree import NWTree from nw.core.tree import NWTree
from nw.core.item import NWItem from nw.core.item import NWItem
@@ -436,26 +434,15 @@ class NWProject():
xRoot = nwXML.getroot() xRoot = nwXML.getroot()
nwxRoot = xRoot.tag nwxRoot = xRoot.tag
appVersion = "Unknown" appVersion = xRoot.attrib.get("appVersion", "Unknown")
hexVersion = "0x0" hexVersion = xRoot.attrib.get("hexVersion", "0x0")
fileVersion = "Unknown" fileVersion = xRoot.attrib.get("fileVersion", "Unknown")
self.saveCount = 0
self.autoCount = 0
if "appVersion" in xRoot.attrib:
appVersion = xRoot.attrib["appVersion"]
if "hexVersion" in xRoot.attrib:
hexVersion = xRoot.attrib["hexVersion"]
if "fileVersion" in xRoot.attrib:
fileVersion = xRoot.attrib["fileVersion"]
# The following are deprecated and will be removed # The following are deprecated and will be removed
if "saveCount" in xRoot.attrib: # The settings have been moved to the <project> tag
self.saveCount = checkInt(xRoot.attrib["saveCount"], 0, False) self.saveCount = checkInt(xRoot.attrib.get("saveCount", 0), 0, False)
if "autoCount" in xRoot.attrib: self.autoCount = checkInt(xRoot.attrib.get("autoCount", 0), 0, False)
self.autoCount = checkInt(xRoot.attrib["autoCount"], 0, False) self.editTime = checkInt(xRoot.attrib.get("editTime", 0), 0, False)
if "editTime" in xRoot.attrib:
self.editTime = checkInt(xRoot.attrib["editTime"], 0, False)
logger.verbose("XML root is %s" % nwxRoot) logger.verbose("XML root is %s" % nwxRoot)
logger.verbose("File version is %s" % fileVersion) logger.verbose("File version is %s" % fileVersion)
@@ -483,20 +470,19 @@ class NWProject():
# parser will lose the autoReplace settings if allowed to # parser will lose the autoReplace settings if allowed to
# read the file. Introduced in version 0.10. # read the file. Introduced in version 0.10.
if fileVersion == "1.0" and self.mainConf.showGUI: if fileVersion == "1.0":
msgBox = QMessageBox() msgRes = self.theParent.askQuestion("Old Project Version", (
msgRes = msgBox.question(self.theParent, "Old Project Version", (
"The project file and data is created by a novelWriter version " "The project file and data is created by a novelWriter version "
"lower than 0.7. Do you want to upgrade the project to the " "lower than 0.7. Do you want to upgrade the project to the "
"most recent format?<br><br>Note that after the upgrade, you " "most recent format?<br><br>Note that after the upgrade, you "
"cannot open the project with an older version of novelWriter " "cannot open the project with an older version of novelWriter "
"any more, so make sure you have a recent backup." "any more, so make sure you have a recent backup."
)) ))
if msgRes != QMessageBox.Yes: if not msgRes:
self.clearProject() self.clearProject()
return False return False
elif fileVersion != "1.1" and fileVersion != "1.2" and self.mainConf.showGUI: elif fileVersion != "1.1" and fileVersion != "1.2":
self.makeAlert(( self.makeAlert((
"Unknown or unsupported novelWriter project file format. " "Unknown or unsupported novelWriter project file format. "
"The project cannot be opened by this version of novelWriter. " "The project cannot be opened by this version of novelWriter. "
@@ -510,9 +496,8 @@ class NWProject():
# Check novelWriter Version # Check novelWriter Version
# ========================= # =========================
if int(hexVersion, 16) > int(nw.__hexversion__, 16) and self.mainConf.showGUI: if int(hexVersion, 16) > int(nw.__hexversion__, 16):
msgBox = QMessageBox() msgRes = self.theParent.askQuestion("Version Conflict", (
msgRes = msgBox.question(self.theParent, "Version Conflict", (
"This project was saved by a newer version of novelWriter, version %s. " "This project was saved by a newer version of novelWriter, version %s. "
"This is version %s. If you continue to open the project, some attributes " "This is version %s. If you continue to open the project, some attributes "
"and settings may not be preserved, but the overall project should be fine. " "and settings may not be preserved, but the overall project should be fine. "
@@ -520,7 +505,7 @@ class NWProject():
) % ( ) % (
appVersion, nw.__version__ appVersion, nw.__version__
)) ))
if msgRes != QMessageBox.Yes: if not msgRes:
self.clearProject() self.clearProject()
return False return False
@@ -835,15 +820,15 @@ class NWProject():
try: try:
self._clearLockFile() self._clearLockFile()
make_archive(baseName, "zip", self.projPath, ".") shutil.make_archive(baseName, "zip", self.projPath, ".")
self._writeLockFile() self._writeLockFile()
logger.info("Backup written to: %s" % archName)
if doNotify: if doNotify:
self.theParent.makeAlert( self.theParent.makeAlert(
"Backup archive file written to: %s.zip" % os.path.join(cleanName, archName), "Backup archive file written to: %s.zip" % os.path.join(cleanName, archName),
nwAlert.INFO nwAlert.INFO
) )
else:
logger.info("Backup written to: %s" % archName)
except Exception as e: except Exception as e:
self.theParent.makeAlert( self.theParent.makeAlert(
["Could not write backup archive.", str(e)], ["Could not write backup archive.", str(e)],
@@ -874,7 +859,7 @@ class NWProject():
self.setProjectPath(projPath, newProject=True) self.setProjectPath(projPath, newProject=True)
try: try:
unpack_archive(pkgSample, projPath) shutil.unpack_archive(pkgSample, projPath)
isSuccess = True isSuccess = True
except Exception as e: except Exception as e:
self.makeAlert( self.makeAlert(
@@ -887,14 +872,14 @@ class NWProject():
try: try:
srcProj = os.path.join(srcSample, nwFiles.PROJ_FILE) srcProj = os.path.join(srcSample, nwFiles.PROJ_FILE)
dstProj = os.path.join(projPath, nwFiles.PROJ_FILE) dstProj = os.path.join(projPath, nwFiles.PROJ_FILE)
copyfile(srcProj, dstProj) shutil.copyfile(srcProj, dstProj)
srcContent = os.path.join(srcSample, "content") srcContent = os.path.join(srcSample, "content")
dstContent = os.path.join(projPath, "content") dstContent = os.path.join(projPath, "content")
for srcFile in os.listdir(srcContent): for srcFile in os.listdir(srcContent):
srcDoc = os.path.join(srcContent, srcFile) srcDoc = os.path.join(srcContent, srcFile)
dstDoc = os.path.join(dstContent, srcFile) dstDoc = os.path.join(dstContent, srcFile)
copyfile(srcDoc, dstDoc) shutil.copyfile(srcDoc, dstDoc)
isSuccess = True isSuccess = True
@@ -998,11 +983,15 @@ class NWProject():
"You must set a valid backup path in preferences to use " "You must set a valid backup path in preferences to use "
"the automatic project backup feature." "the automatic project backup feature."
), nwAlert.WARN) ), nwAlert.WARN)
return False
if self.projName == "": if self.projName == "":
self.theParent.makeAlert(( self.theParent.makeAlert((
"You must set a valid project name in project settings to " "You must set a valid project name in project settings to "
"use the automatic project backup feature." "use the automatic project backup feature."
), nwAlert.WARN) ), nwAlert.WARN)
return False
return True return True
def setSpellCheck(self, theMode): def setSpellCheck(self, theMode):
@@ -1011,12 +1000,15 @@ class NWProject():
if self.spellCheck != theMode: if self.spellCheck != theMode:
self.spellCheck = theMode self.spellCheck = theMode
self.setProjectChanged(True) self.setProjectChanged(True)
return True return self.spellCheck
def setSpellLang(self, theLang): def setSpellLang(self, theLang):
"""Set the project-specific spell check language. """Set the project-specific spell check language.
""" """
self.projLang = checkString(theLang, None, True) theLang = checkString(theLang, None, True)
if self.projLang != theLang:
self.projLang = theLang
self.setProjectChanged(True)
return True return True
def setAutoOutline(self, theMode): def setAutoOutline(self, theMode):
@@ -1025,7 +1017,7 @@ class NWProject():
if self.autoOutline != theMode: if self.autoOutline != theMode:
self.autoOutline = theMode self.autoOutline = theMode
self.setProjectChanged(True) self.setProjectChanged(True)
return True return self.autoOutline
def setTreeOrder(self, newOrder): def setTreeOrder(self, newOrder):
"""A list representing the linear/flattened order of project """A list representing the linear/flattened order of project
@@ -1072,7 +1064,7 @@ class NWProject():
if nwItem.itemStatus in replaceMap.keys(): if nwItem.itemStatus in replaceMap.keys():
nwItem.setStatus(replaceMap[nwItem.itemStatus]) nwItem.setStatus(replaceMap[nwItem.itemStatus])
self.setProjectChanged(True) self.setProjectChanged(True)
return return True
def setImportColours(self, newCols): def setImportColours(self, newCols):
"""Update the list of note file importance flags. Also iterate """Update the list of note file importance flags. Also iterate
@@ -1084,14 +1076,15 @@ class NWProject():
if nwItem.itemStatus in replaceMap.keys(): if nwItem.itemStatus in replaceMap.keys():
nwItem.setStatus(replaceMap[nwItem.itemStatus]) nwItem.setStatus(replaceMap[nwItem.itemStatus])
self.setProjectChanged(True) self.setProjectChanged(True)
return return True
def setAutoReplace(self, autoReplace): def setAutoReplace(self, autoReplace):
"""Update the auto-replace dictionary. This replaces the entire """Update the auto-replace dictionary. This replaces the entire
dictionary, so alterations have to be made in a copy. dictionary, so alterations have to be made in a copy.
""" """
self.autoReplace = autoReplace self.autoReplace = autoReplace
return self.setProjectChanged(True)
return True
def setTitleFormat(self, titleFormat): def setTitleFormat(self, titleFormat):
"""Set the formatting of titles in the project. """Set the formatting of titles in the project.
@@ -1099,7 +1092,7 @@ class NWProject():
for valKey, valEntry in titleFormat.items(): for valKey, valEntry in titleFormat.items():
if valKey in self.titleFormat: if valKey in self.titleFormat:
self.titleFormat[valKey] = checkString(valEntry, self.titleFormat[valKey], False) self.titleFormat[valKey] = checkString(valEntry, self.titleFormat[valKey], False)
return return True
def setProjectChanged(self, bValue): def setProjectChanged(self, bValue):
"""Toggle the project changed flag, and propagate the """Toggle the project changed flag, and propagate the
@@ -1292,7 +1285,7 @@ class NWProject():
back into the project tree. back into the project tree.
""" """
if self.projPath is None: if self.projPath is None:
return return False
# Then check the files in the data folder # Then check the files in the data folder
logger.debug("Checking files in project content folder") logger.debug("Checking files in project content folder")
@@ -1352,7 +1345,7 @@ class NWProject():
orphItem.setLayout(oLayout) orphItem.setLayout(oLayout)
self.projTree.append(oHandle, None, orphItem) self.projTree.append(oHandle, None, orphItem)
return return True
def _appendSessionStats(self): def _appendSessionStats(self):
"""Append session statistics to the sessions log file. """Append session statistics to the sessions log file.
@@ -1490,7 +1483,8 @@ class NWProject():
os.unlink(rmFile) os.unlink(rmFile)
except Exception as e: except Exception as e:
logger.error(str(e)) logger.error(str(e))
return False
return return True
# END Class NWProject # END Class NWProject
+2 -1
View File
@@ -109,7 +109,8 @@ class NWStatus():
return return
def countEntry(self, theLabel): def countEntry(self, theLabel):
"""Lookup the usage count of a given entry. """Increment the counter for a given label. This should be used
together with resetCounts in a loop over project items.
""" """
theIndex = self.lookupEntry(theLabel) theIndex = self.lookupEntry(theLabel)
if theIndex is not None: if theIndex is not None:
+7
View File
@@ -982,6 +982,13 @@ class GuiMain(QMainWindow):
return return
def askQuestion(self, theTitle, theQuestion):
"""Ask the user a Yes/No question.
"""
msgBox = QMessageBox()
msgRes = msgBox.question(self, theTitle, theQuestion)
return msgRes == QMessageBox.Yes
def reportConfErr(self): def reportConfErr(self):
"""Checks if the Config module has any errors to report, and let """Checks if the Config module has any errors to report, and let
the user know if this is the case. The Config module caches the user know if this is the case. The Config module caches