From 4fcff94b058745b5531c21c40c53853a5f425a9a Mon Sep 17 00:00:00 2001 From: "Veronica K. B. Olsen" <1619840+vkbo@users.noreply.github.com> Date: Mon, 28 Oct 2019 14:12:26 +0100 Subject: [PATCH] Make sure the document isn't overwritten if it exists, but we have an error loading it due to encoding, or otherwise --- nw/gui/doceditor.py | 14 +++++++++++++- nw/gui/winmain.py | 10 ++++++---- nw/project/document.py | 7 ++++++- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/nw/gui/doceditor.py b/nw/gui/doceditor.py index 3ecc9f3c..9c247ae5 100644 --- a/nw/gui/doceditor.py +++ b/nw/gui/doceditor.py @@ -162,9 +162,21 @@ class GuiDocEditor(QTextEdit): return True def loadText(self, tHandle): + """Load text from a document into the editor. If we have an io error, we must handle this + and clear the editor so that we don't risk overwriting the file if it exists. This can for + instance happen of the file contains binary elements or an encoding that novelWriter does + not support. If load is successful, ot the document is new (empty string) we set up the + editor for editing the file. + """ + + theDoc = self.nwDocument.openDocument(tHandle) + if theDoc is None: + # There was an io error + self.clearEditor() + return False self.hLight.setHandle(tHandle) - self.setPlainText(self.nwDocument.openDocument(tHandle)) + self.setPlainText(theDoc) self.setCursorPosition(self.nwDocument.theItem.cursorPos) self.lastEdit = time() self._runCounter() diff --git a/nw/gui/winmain.py b/nw/gui/winmain.py index e4319e16..53a882d9 100644 --- a/nw/gui/winmain.py +++ b/nw/gui/winmain.py @@ -332,10 +332,12 @@ class GuiMain(QMainWindow): def openDocument(self, tHandle): if self.hasProject: self.closeDocument() - self.docEditor.loadText(tHandle) - self.docEditor.setFocus() - self.docEditor.changeWidth() - self.theProject.setLastEdited(tHandle) + if self.docEditor.loadText(tHandle): + self.docEditor.setFocus() + self.docEditor.changeWidth() + self.theProject.setLastEdited(tHandle) + else: + return False return True def saveDocument(self): diff --git a/nw/project/document.py b/nw/project/document.py index 57ce1d44..7f5b550a 100644 --- a/nw/project/document.py +++ b/nw/project/document.py @@ -57,8 +57,13 @@ class NWDoc(): theDoc = inFile.read() except Exception as e: self.makeAlert(["Failed to open document file.",str(e)], nwAlert.ERROR) - return "" + # Note: Document must be cleared in case of an io error, or else the auto-save or + # save will try to overwrite it with an empty file. Return None to alert the caller. + self.clearDocument() + return None else: + # The document file does not exist, so we assume it's a new document and initialise an + # empty text string. logger.debug("The requested document does not exist.") return ""