Make GuiDocEditor variables private

This commit is contained in:
Veronica K. B. Olsen
2021-05-15 23:57:31 +02:00
parent 6ef8611a0a
commit ba5e5f4bb5
6 changed files with 254 additions and 230 deletions
+239 -215
View File
@@ -76,39 +76,39 @@ class GuiDocEditor(QTextEdit):
self.theIndex = theParent.theIndex self.theIndex = theParent.theIndex
self.theProject = theParent.theProject self.theProject = theParent.theProject
self.nwDocument = None self._nwDocument = None
self.nwItem = None self._nwItem = None
self.docChanged = False # Flag for changed status of document self._docChanged = False # Flag for changed status of document
self.spellCheck = False # Flag for spell checking enabled self._docHandle = None # The handle of the open file
self.theHandle = None # The handle of the open file self._docHeaders = [] # Record of headers in the file
self.theHeaders = [] # Record of headers in the file
self.theDict = None # The current spell check dictionary self._spellCheck = False # Flag for spell checking enabled
self.nonWord = "\"'" # Characters to not include in spell checking self.theDict = None # The current spell check dictionary
self._nonWord = "\"'" # Characters to not include in spell checking
# Document Variables # Document Variables
self.charCount = 0 # Character count self._charCount = 0 # Character count
self.wordCount = 0 # Word count self._wordCount = 0 # Word count
self.paraCount = 0 # Paragraph count self._paraCount = 0 # Paragraph count
self.lastEdit = 0 # Time stamp of last edit self._lastEdit = 0 # Time stamp of last edit
self.lastActive = 0 # Time stamp of last activity self._lastActive = 0 # Time stamp of last activity
self.lastFind = None # Position of the last found search word self._lastFind = None # Position of the last found search word
self.bigDoc = False # Flag for very large document size self._bigDoc = False # Flag for very large document size
self.doReplace = False # Switch to temporarily disable auto-replace self._doReplace = False # Switch to temporarily disable auto-replace
self.queuePos = None # Used for delayed change of cursor position self._queuePos = None # Used for delayed change of cursor position
# Typography # Typography
self.typDQOpen = '"' self._typDQOpen = '"'
self.typDQClose = '"' self._typDQClose = '"'
self.typSQOpen = "'" self._typSQOpen = "'"
self.typSQClose = "'" self._typSQClose = "'"
self.typPadChar = " " self._typPadChar = " "
self.addPadding = False
# Core Elements and Signals # Core Elements and Signals
self.qDocument = self.document() self._qDocument = self.document()
self.qDocument.contentsChange.connect(self._docChange) self._qDocument.contentsChange.connect(self._docChange)
self.qDocument.documentLayout().documentSizeChanged.connect(self._docSizeChanged) self._qDocument.documentLayout().documentSizeChanged.connect(self._docSizeChanged)
# Document Title # Document Title
self.docHeader = GuiDocEditHeader(self) self.docHeader = GuiDocEditHeader(self)
@@ -116,7 +116,7 @@ class GuiDocEditor(QTextEdit):
self.docSearch = GuiDocEditSearch(self) self.docSearch = GuiDocEditSearch(self)
# Syntax # Syntax
self.hLight = GuiDocHighlighter(self.qDocument, self.theParent) self.hLight = GuiDocHighlighter(self._qDocument, self.theParent)
# Context Menu # Context Menu
self.setContextMenuPolicy(Qt.CustomContextMenu) self.setContextMenuPolicy(Qt.CustomContextMenu)
@@ -167,25 +167,25 @@ class GuiDocEditor(QTextEdit):
"""Clear the current document and reset all document related """Clear the current document and reset all document related
flags and counters. flags and counters.
""" """
self.nwDocument = None self._nwDocument = None
self.setReadOnly(True) self.setReadOnly(True)
self.clear() self.clear()
self.wcTimer.stop() self.wcTimer.stop()
self.theHandle = None self._docHandle = None
self.charCount = 0 self._charCount = 0
self.wordCount = 0 self._wordCount = 0
self.paraCount = 0 self._paraCount = 0
self.lastEdit = 0 self._lastEdit = 0
self.lastActive = 0 self._lastActive = 0
self.lastFind = None self._lastFind = None
self.bigDoc = False self._bigDoc = False
self.doReplace = False self._doReplace = False
self.queuePos = None self._queuePos = None
self.setDocumentChanged(False) self.setDocumentChanged(False)
self.docHeader.setTitleFromHandle(self.theHandle) self.docHeader.setTitleFromHandle(self._docHandle)
self.docFooter.setHandle(self.theHandle) self.docFooter.setHandle(self._docHandle)
return True return True
@@ -195,20 +195,20 @@ class GuiDocEditor(QTextEdit):
created, and when the user changes the main editor preferences. created, and when the user changes the main editor preferences.
""" """
# Some Constants # Some Constants
self.nonWord = "\"'" self._nonWord = "\"'"
self.nonWord += "".join(self.mainConf.fmtDoubleQuotes) self._nonWord += "".join(self.mainConf.fmtDoubleQuotes)
self.nonWord += "".join(self.mainConf.fmtSingleQuotes) self._nonWord += "".join(self.mainConf.fmtSingleQuotes)
# Typography # Typography
if self.mainConf.fmtPadThin: if self.mainConf.fmtPadThin:
self.typPadChar = nwUnicode.U_THNBSP self._typPadChar = nwUnicode.U_THNBSP
else: else:
self.typPadChar = nwUnicode.U_NBSP self._typPadChar = nwUnicode.U_NBSP
self.typSQOpen = self.mainConf.fmtSingleQuotes[0] self._typDQOpen = self.mainConf.fmtDoubleQuotes[0]
self.typSQClose = self.mainConf.fmtSingleQuotes[1] self._typDQClose = self.mainConf.fmtDoubleQuotes[1]
self.typDQOpen = self.mainConf.fmtDoubleQuotes[0] self._typSQOpen = self.mainConf.fmtSingleQuotes[0]
self.typDQClose = self.mainConf.fmtDoubleQuotes[1] self._typSQClose = self.mainConf.fmtSingleQuotes[1]
# Reload spell check and dictionaries # Reload spell check and dictionaries
self._setupSpellChecking() self._setupSpellChecking()
@@ -218,7 +218,7 @@ class GuiDocEditor(QTextEdit):
theFont = QFont() theFont = QFont()
if self.mainConf.textFont is None: if self.mainConf.textFont is None:
# If none is defined, set the default back to config # If none is defined, set the default back to config
self.mainConf.textFont = self.qDocument.defaultFont().family() self.mainConf.textFont = self._qDocument.defaultFont().family()
theFont.setFamily(self.mainConf.textFont) theFont.setFamily(self.mainConf.textFont)
theFont.setPointSize(self.mainConf.textSize) theFont.setPointSize(self.mainConf.textSize)
@@ -241,7 +241,7 @@ class GuiDocEditor(QTextEdit):
# Set default text margins # Set default text margins
cM = self.mainConf.getTextMargin() cM = self.mainConf.getTextMargin()
self.qDocument.setDocumentMargin(0) self._qDocument.setDocumentMargin(0)
self.setViewportMargins(cM, cM, cM, cM) self.setViewportMargins(cM, cM, cM, cM)
# Also set the document text options for the document text flow # Also set the document text options for the document text flow
@@ -254,7 +254,7 @@ class GuiDocEditor(QTextEdit):
if self.mainConf.showLineEndings: if self.mainConf.showLineEndings:
theOpt.setFlags(theOpt.flags() | QTextOption.ShowLineAndParagraphSeparators) theOpt.setFlags(theOpt.flags() | QTextOption.ShowLineAndParagraphSeparators)
self.qDocument.setDefaultTextOption(theOpt) self._qDocument.setDefaultTextOption(theOpt)
# Scroll bars # Scroll bars
if self.mainConf.hideVScroll: if self.mainConf.hideVScroll:
@@ -283,7 +283,7 @@ class GuiDocEditor(QTextEdit):
# If we have a document open, we should reload it in case the # If we have a document open, we should reload it in case the
# font changed, otherwise we just clear the editor entirely, # font changed, otherwise we just clear the editor entirely,
# which makes it read only. # which makes it read only.
if self.theHandle is None: if self._docHandle is None:
self.clearEditor() self.clearEditor()
else: else:
self.redrawText() self.redrawText()
@@ -299,10 +299,10 @@ 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 = NWDoc(self.theProject, tHandle) self._nwDocument = NWDoc(self.theProject, tHandle)
self.nwItem = self.nwDocument.getCurrentItem() self._nwItem = self._nwDocument.getCurrentItem()
theDoc = self.nwDocument.readDocument() theDoc = self._nwDocument.readDocument()
if theDoc is None: if theDoc is None:
# There was an io error # There was an io error
self.clearEditor() self.clearEditor()
@@ -331,7 +331,7 @@ class GuiDocEditor(QTextEdit):
# checking. If it is too big, we switch to only check as we type # checking. If it is too big, we switch to only check as we type
self._checkDocSize(docSize) self._checkDocSize(docSize)
spTemp = self.hLight.spellCheck spTemp = self.hLight.spellCheck
if self.bigDoc: if self._bigDoc:
self.hLight.spellCheck = False self.hLight.spellCheck = False
bfTime = time() bfTime = time()
@@ -343,48 +343,48 @@ class GuiDocEditor(QTextEdit):
afTime = time() afTime = time()
logger.debug("Document highlighted in %.3f ms" % (1000*(afTime-bfTime))) logger.debug("Document highlighted in %.3f ms" % (1000*(afTime-bfTime)))
self.lastEdit = time() self._lastEdit = time()
self.lastActive = time() self._lastActive = time()
self._runCounter() self._runCounter()
self.wcTimer.start() self.wcTimer.start()
self.theHandle = tHandle self._docHandle = tHandle
self.setReadOnly(False) self.setReadOnly(False)
self.docHeader.setTitleFromHandle(self.theHandle) self.docHeader.setTitleFromHandle(self._docHandle)
self.docFooter.setHandle(self.theHandle) self.docFooter.setHandle(self._docHandle)
self.updateDocMargins() self.updateDocMargins()
self.hLight.spellCheck = spTemp self.hLight.spellCheck = spTemp
if tLine is None and self.nwItem is not None: if tLine is None and self._nwItem is not None:
# For large documents we queue the repositioning until the # For large documents we queue the repositioning until the
# document layout has grown past the point we want to move # document layout has grown past the point we want to move
# the cursor to. This makes the loading significantly # the cursor to. This makes the loading significantly
# faster. # faster.
if docSize > 50000: if docSize > 50000:
self.queuePos = self.nwItem.cursorPos self._queuePos = self._nwItem.cursorPos
else: else:
self.setCursorPosition(self.nwItem.cursorPos) self.setCursorPosition(self._nwItem.cursorPos)
else: else:
self.setCursorLine(tLine) self.setCursorLine(tLine)
self.docFooter.updateLineCount() self.docFooter.updateLineCount()
self.lengthLast = self.qDocument.characterCount() self.lengthLast = self._qDocument.characterCount()
self.theHeaders = self.theIndex.getHandleHeaders(self.theHandle) self._docHeaders = self.theIndex.getHandleHeaders(self._docHandle)
qApp.processEvents() qApp.processEvents()
self.setDocumentChanged(False) self.setDocumentChanged(False)
qApp.restoreOverrideCursor() qApp.restoreOverrideCursor()
# This is a hack to fix invisble cursor on an empty document # This is a hack to fix invisble cursor on an empty document
if self.qDocument.characterCount() <= 1: if self._qDocument.characterCount() <= 1:
self.setPlainText("\n") self.setPlainText("\n")
self.setPlainText("") self.setPlainText("")
self.setCursorPosition(0) self.setCursorPosition(0)
# Update the status bar # Update the status bar
if self.nwItem is not None: if self._nwItem is not None:
self.theParent.setStatus( self.theParent.setStatus(
self.tr("Opened Document: {0}").format(self.nwItem.itemName) self.tr("Opened Document: {0}").format(self._nwItem.itemName)
) )
return True return True
@@ -398,7 +398,7 @@ class GuiDocEditor(QTextEdit):
def redrawText(self): def redrawText(self):
"""Redraw the text by marking the document content as "dirty". """Redraw the text by marking the document content as "dirty".
""" """
self.qDocument.markContentsDirty(0, self.qDocument.characterCount()) self._qDocument.markContentsDirty(0, self._qDocument.characterCount())
self.updateDocMargins() self.updateDocMargins()
return return
@@ -433,14 +433,14 @@ class GuiDocEditor(QTextEdit):
"""Save the text currently in the editor to the NWDoc object, """Save the text currently in the editor to the NWDoc object,
and update the NWItem meta data. and update the NWItem meta data.
""" """
if self.nwItem is None or self.nwDocument is None: if self._nwItem is None or self._nwDocument is None:
logger.error("Cannot save text as no document is open") logger.error("Cannot save text as no document is open")
return False return False
tHandle = self.nwItem.itemHandle tHandle = self._nwItem.itemHandle
if self.theHandle != tHandle: if self._docHandle != tHandle:
logger.error("Editor handle %s and item handle %s do not match" % ( logger.error("Editor handle %s and item handle %s do not match" % (
self.theHandle, tHandle self._docHandle, tHandle
)) ))
return False return False
@@ -449,14 +449,14 @@ class GuiDocEditor(QTextEdit):
cC, wC, pC = countWords(docText) cC, wC, pC = countWords(docText)
self._updateCounts(cC, wC, pC) self._updateCounts(cC, wC, pC)
self.nwItem.setCharCount(self.charCount) self._nwItem.setCharCount(self._charCount)
self.nwItem.setWordCount(self.wordCount) self._nwItem.setWordCount(self._wordCount)
self.nwItem.setParaCount(self.paraCount) self._nwItem.setParaCount(self._paraCount)
self.saveCursorPosition() self.saveCursorPosition()
if not self.nwDocument.writeDocument(docText): if not self._nwDocument.writeDocument(docText):
self.theParent.makeAlert([ self.theParent.makeAlert([
self.tr("Could not save document."), self.nwDocument.getError() self.tr("Could not save document."), self._nwDocument.getError()
], nwAlert.ERROR) ], nwAlert.ERROR)
return False return False
@@ -470,17 +470,17 @@ class GuiDocEditor(QTextEdit):
self.theParent.novelView.updateWordCounts(tHandle) self.theParent.novelView.updateWordCounts(tHandle)
hLevel = "H0" hLevel = "H0"
if self.theHeaders: if self._docHeaders:
hLevel = self.theHeaders[0][1] hLevel = self._docHeaders[0][1]
if self.theProject.projTree.updateItemLayout(tHandle, hLevel): if self.theProject.projTree.updateItemLayout(tHandle, hLevel):
self.theParent.treeView.setTreeItemValues(tHandle) self.theParent.treeView.setTreeItemValues(tHandle)
self.nwDocument.writeDocument(docText) self._nwDocument.writeDocument(docText)
self.docFooter.updateInfo() self.docFooter.updateInfo()
# Update the status bar # Update the status bar
self.theParent.setStatus( self.theParent.setStatus(
self.tr("Saved Document: {0}").format(self.nwItem.itemName) self.tr("Saved Document: {0}").format(self._nwItem.itemName)
) )
return True return True
@@ -531,16 +531,16 @@ class GuiDocEditor(QTextEdit):
lM = max(cM, fH) lM = max(cM, fH)
self.setViewportMargins(tM, uM, tM, lM) self.setViewportMargins(tM, uM, tM, lM)
docChanged = self.docChanged tmpDocChanged = self._docChanged
if self.mainConf.scrollPastEnd: if self.mainConf.scrollPastEnd:
docFrame = self.qDocument.rootFrame().frameFormat() docFrame = self._qDocument.rootFrame().frameFormat()
docFrame.setBottomMargin(max(0, 0.9*(wH - uM - lM - 4*tB))) docFrame.setBottomMargin(max(0, 0.9*(wH - uM - lM - 4*tB)))
self.qDocument.rootFrame().setFrameFormat(docFrame) self._qDocument.rootFrame().setFrameFormat(docFrame)
# This is needed as the setFrameFormat function itself will # This is needed as the setFrameFormat function itself will
# trigger the contetsChanged signal which sets docChanged, so we # trigger the contetsChanged signal which sets _docChanged, so we
# set it back to whatever it was before. # set it back to whatever it was before.
self.setDocumentChanged(docChanged) self.setDocumentChanged(tmpDocChanged)
return return
@@ -548,14 +548,65 @@ class GuiDocEditor(QTextEdit):
"""Called when an item label is changed to check if the document """Called when an item label is changed to check if the document
title bar needs updating, title bar needs updating,
""" """
if tHandle == self.theHandle: if tHandle == self._docHandle:
self.docHeader.setTitleFromHandle(self.theHandle) self.docHeader.setTitleFromHandle(self._docHandle)
self.docFooter.updateInfo() self.docFooter.updateInfo()
self.updateDocMargins() self.updateDocMargins()
return return
## ##
# Setters and Getters # Properties
##
def docChanged(self):
"""Return the changed status of the document in the editor.
"""
return self._docChanged
def docHandle(self):
"""Return the handle of the currently open document. Returns
None if no document is open.
"""
return self._docHandle
def lastActive(self):
"""Eeturn the last active timestamp for the user.
"""
return self._lastActive
def isEmpty(self):
"""Wrapper function to check if the current document is empty.
"""
return self._qDocument.isEmpty()
##
# Getters
##
def getText(self):
"""Get the text content of the current document. This method
uses QTextEdit->toPlainText for Qt versions lower than 5.9, and
the QTextDocument->toRawText for higher version. The latter
preserves non-breaking spaces, which the former does not.
We still want to get rid of page and line separators though.
See: https://doc.qt.io/qt-5/qtextdocument.html#toPlainText
"""
if self.mainConf.verQtValue >= 50900:
theText = self._qDocument.toRawText()
theText = theText.replace(nwUnicode.U_LSEP, "\n") # Line separators
theText = theText.replace(nwUnicode.U_PSEP, "\n") # Paragraph separators
else:
theText = self.toPlainText()
return theText
def getCursorPosition(self):
"""Find the cursor position in the document. If the editor has a
selection, return the position of the end of the selection.
"""
return self.textCursor().selectionEnd()
##
# Setters
## ##
def setDocumentChanged(self, bValue): def setDocumentChanged(self, bValue):
@@ -563,25 +614,9 @@ class GuiDocEditor(QTextEdit):
that the corresponding icon on the status bar shows the same that the corresponding icon on the status bar shows the same
status. status.
""" """
self.docChanged = bValue self._docChanged = bValue
self.theParent.statusBar.setDocumentStatus(self.docChanged) self.theParent.statusBar.setDocumentStatus(self._docChanged)
return self.docChanged return self._docChanged
def getText(self):
"""Get the text content of the current document. This method
uses QTextEdit->toPlainText for Qt versions lower than 5.9, and
the QDocument->toRawText for higher version. The latter
preserves non-breaking spaces, which the former does not.
We still want to get rid of page and line separators though.
See: https://doc.qt.io/qt-5/qtextdocument.html#toPlainText
"""
if self.mainConf.verQtValue >= 50900:
theText = self.qDocument.toRawText()
theText = theText.replace(nwUnicode.U_LSEP, "\n") # Line separators
theText = theText.replace(nwUnicode.U_PSEP, "\n") # Paragraph separators
else:
theText = self.toPlainText()
return theText
def setCursorPosition(self, thePosition): def setCursorPosition(self, thePosition):
"""Move the cursor to a given position in the document. """Move the cursor to a given position in the document.
@@ -589,7 +624,7 @@ class GuiDocEditor(QTextEdit):
if not isinstance(thePosition, int): if not isinstance(thePosition, int):
return False return False
nChars = self.qDocument.characterCount() nChars = self._qDocument.characterCount()
if nChars > 1: if nChars > 1:
theCursor = self.textCursor() theCursor = self.textCursor()
theCursor.setPosition(min(max(thePosition, 0), nChars-1)) theCursor.setPosition(min(max(thePosition, 0), nChars-1))
@@ -598,18 +633,12 @@ class GuiDocEditor(QTextEdit):
return True return True
def getCursorPosition(self):
"""Find the cursor position in the document. If the editor has a
selection, return the position of the end of the selection.
"""
return self.textCursor().selectionEnd()
def saveCursorPosition(self): def saveCursorPosition(self):
"""Save the cursor position to the current project item object. """Save the cursor position to the current project item object.
""" """
if self.nwItem is not None: if self._nwItem is not None:
cursPos = self.getCursorPosition() cursPos = self.getCursorPosition()
self.nwItem.setCursorPos(cursPos) self._nwItem.setCursorPos(cursPos)
return return
def setCursorLine(self, theLine): def setCursorLine(self, theLine):
@@ -619,7 +648,7 @@ class GuiDocEditor(QTextEdit):
return False return False
if theLine >= 0: if theLine >= 0:
theBlock = self.qDocument.findBlockByLineNumber(theLine) theBlock = self._qDocument.findBlockByLineNumber(theLine)
if theBlock: if theBlock:
self.setCursorPosition(theBlock.position()) self.setCursorPosition(theBlock.position())
self.docFooter.updateLineCount() self.docFooter.updateLineCount()
@@ -646,7 +675,7 @@ class GuiDocEditor(QTextEdit):
self.theParent.statusBar.setLanguage(theLang, theProvider) self.theParent.statusBar.setLanguage(theLang, theProvider)
if not self.bigDoc: if not self._bigDoc:
self.spellCheckDocument() self.spellCheckDocument()
return True return True
@@ -658,16 +687,16 @@ class GuiDocEditor(QTextEdit):
toggle the current status saved in this class. toggle the current status saved in this class.
""" """
if theMode is None: if theMode is None:
theMode = not self.spellCheck theMode = not self._spellCheck
if self.theDict.spellLanguage is None: if self.theDict.spellLanguage is None:
theMode = False theMode = False
self.spellCheck = theMode self._spellCheck = theMode
self.theParent.mainMenu.setSpellCheck(theMode) self.theParent.mainMenu.setSpellCheck(theMode)
self.theProject.setSpellCheck(theMode) self.theProject.setSpellCheck(theMode)
self.hLight.setSpellCheck(theMode) self.hLight.setSpellCheck(theMode)
if not self.bigDoc: if not self._bigDoc:
self.spellCheckDocument() self.spellCheckDocument()
logger.verbose("Spell check is set to %s" % str(theMode)) logger.verbose("Spell check is set to %s" % str(theMode))
@@ -680,10 +709,10 @@ class GuiDocEditor(QTextEdit):
of Qt 5.13, is to clear the text and put it back. of Qt 5.13, is to clear the text and put it back.
""" """
logger.verbose("Running spell checker") logger.verbose("Running spell checker")
if self.spellCheck: if self._spellCheck:
bfTime = time() bfTime = time()
qApp.setOverrideCursor(QCursor(Qt.WaitCursor)) qApp.setOverrideCursor(QCursor(Qt.WaitCursor))
if self.bigDoc: if self._bigDoc:
theText = self.getText() theText = self.getText()
self.setPlainText(theText) self.setPlainText(theText)
else: else:
@@ -707,7 +736,7 @@ class GuiDocEditor(QTextEdit):
this class when calling these actions from other classes. this class when calling these actions from other classes.
""" """
logger.verbose("Requesting action: %s" % theAction.name) logger.verbose("Requesting action: %s" % theAction.name)
if self.theHandle is None: if self._docHandle is None:
logger.error("No document open") logger.error("No document open")
return False return False
@@ -729,9 +758,9 @@ class GuiDocEditor(QTextEdit):
elif theAction == nwDocAction.STRIKE: elif theAction == nwDocAction.STRIKE:
self._toggleFormat(2, "~") self._toggleFormat(2, "~")
elif theAction == nwDocAction.S_QUOTE: elif theAction == nwDocAction.S_QUOTE:
self._wrapSelection(self.typSQOpen, self.typSQClose) self._wrapSelection(self._typSQOpen, self._typSQClose)
elif theAction == nwDocAction.D_QUOTE: elif theAction == nwDocAction.D_QUOTE:
self._wrapSelection(self.typDQOpen, self.typDQClose) self._wrapSelection(self._typDQOpen, self._typDQClose)
elif theAction == nwDocAction.SEL_ALL: elif theAction == nwDocAction.SEL_ALL:
self._makeSelection(QTextCursor.Document) self._makeSelection(QTextCursor.Document)
elif theAction == nwDocAction.SEL_PARA: elif theAction == nwDocAction.SEL_PARA:
@@ -749,24 +778,19 @@ class GuiDocEditor(QTextEdit):
elif theAction == nwDocAction.BLOCK_TXT: elif theAction == nwDocAction.BLOCK_TXT:
self._formatBlock(nwDocAction.BLOCK_TXT) self._formatBlock(nwDocAction.BLOCK_TXT)
elif theAction == nwDocAction.REPL_SNG: elif theAction == nwDocAction.REPL_SNG:
self._replaceQuotes("'", self.typSQOpen, self.typSQClose) self._replaceQuotes("'", self._typSQOpen, self._typSQClose)
elif theAction == nwDocAction.REPL_DBL: elif theAction == nwDocAction.REPL_DBL:
self._replaceQuotes("\"", self.typDQOpen, self.typDQClose) self._replaceQuotes("\"", self._typDQOpen, self._typDQClose)
else: else:
logger.debug("Unknown or unsupported document action %s" % str(theAction)) logger.debug("Unknown or unsupported document action %s" % str(theAction))
self._allowAutoReplace(True) self._allowAutoReplace(True)
return False return False
self._allowAutoReplace(True) self._allowAutoReplace(True)
self.lastActive = time() self._lastActive = time()
return True return True
def isEmpty(self):
"""Wrapper function to check if the current document is empty.
"""
return self.qDocument.isEmpty()
def anyFocus(self): def anyFocus(self):
"""Check if any widget or child widget has focus. """Check if any widget or child widget has focus.
""" """
@@ -780,7 +804,7 @@ class GuiDocEditor(QTextEdit):
"""Tell the user where on the file system the file in the editor """Tell the user where on the file system the file in the editor
is saved. is saved.
""" """
if self.nwDocument is None: if self._nwDocument is None:
logger.error("No document open") logger.error("No document open")
return False return False
@@ -790,7 +814,7 @@ class GuiDocEditor(QTextEdit):
self.tr("File Location"), self.tr("File Location"),
"%s<br>%s" % ( "%s<br>%s" % (
self.tr("The currently open file is saved in:"), self.tr("The currently open file is saved in:"),
self.nwDocument.getFileLocation() self._nwDocument.getFileLocation()
), ),
) )
@@ -799,7 +823,7 @@ class GuiDocEditor(QTextEdit):
def insertText(self, theInsert): def insertText(self, theInsert):
"""Insert a specific type of text at the cursor position. """Insert a specific type of text at the cursor position.
""" """
if self.theHandle is None: if self._docHandle is None:
logger.error("No document open") logger.error("No document open")
return False return False
@@ -809,13 +833,13 @@ class GuiDocEditor(QTextEdit):
if theInsert == nwDocInsert.HARD_BREAK: if theInsert == nwDocInsert.HARD_BREAK:
theText = " \n" theText = " \n"
elif theInsert == nwDocInsert.QUOTE_LS: elif theInsert == nwDocInsert.QUOTE_LS:
theText = self.typSQOpen theText = self._typSQOpen
elif theInsert == nwDocInsert.QUOTE_RS: elif theInsert == nwDocInsert.QUOTE_RS:
theText = self.typSQClose theText = self._typSQClose
elif theInsert == nwDocInsert.QUOTE_LD: elif theInsert == nwDocInsert.QUOTE_LD:
theText = self.typDQOpen theText = self._typDQOpen
elif theInsert == nwDocInsert.QUOTE_RD: elif theInsert == nwDocInsert.QUOTE_RD:
theText = self.typDQClose theText = self._typDQClose
else: else:
return False return False
else: else:
@@ -885,7 +909,7 @@ class GuiDocEditor(QTextEdit):
* The undo/redo/select all sequences bypasses the docAction * The undo/redo/select all sequences bypasses the docAction
pathway from the menu, so we redirect them back from here. pathway from the menu, so we redirect them back from here.
""" """
self.lastActive = time() self._lastActive = time()
isReturn = keyEvent.key() == Qt.Key_Return isReturn = keyEvent.key() == Qt.Key_Return
isReturn |= keyEvent.key() == Qt.Key_Enter isReturn |= keyEvent.key() == Qt.Key_Enter
if isReturn and self.docSearch.anyFocus(): if isReturn and self.docSearch.anyFocus():
@@ -971,10 +995,10 @@ class GuiDocEditor(QTextEdit):
"""Triggered by QTextDocument->contentsChanged. This also """Triggered by QTextDocument->contentsChanged. This also
triggers the syntax highlighter. triggers the syntax highlighter.
""" """
self.lastEdit = time() self._lastEdit = time()
self.lastFind = None self._lastFind = None
if self.qDocument.characterCount() > nwConst.MAX_DOCSIZE: if self._qDocument.characterCount() > nwConst.MAX_DOCSIZE:
self.theParent.makeAlert( self.theParent.makeAlert(
self.tr( self.tr(
"The document has grown too big and you cannot add more text to it. " "The document has grown too big and you cannot add more text to it. "
@@ -987,14 +1011,14 @@ class GuiDocEditor(QTextEdit):
self.undo() self.undo()
return return
if not self.docChanged: if not self._docChanged:
self.setDocumentChanged(chrRem != 0 or chrAdd != 0) self.setDocumentChanged(chrRem != 0 or chrAdd != 0)
if not self.wcTimer.isActive(): if not self.wcTimer.isActive():
self.wcTimer.start() self.wcTimer.start()
if self.doReplace and chrAdd == 1: if self._doReplace and chrAdd == 1:
self._docAutoReplace(self.qDocument.findBlock(thePos)) self._docAutoReplace(self._qDocument.findBlock(thePos))
return return
@@ -1056,14 +1080,14 @@ class GuiDocEditor(QTextEdit):
# ============== # ==============
posCursor = self.cursorForPosition(thePos) posCursor = self.cursorForPosition(thePos)
spellCheck = self.spellCheck spellCheck = self._spellCheck
if posCursor.block().text().startswith("@"): if posCursor.block().text().startswith("@"):
spellCheck = False spellCheck = False
if spellCheck: if spellCheck:
posCursor.select(QTextCursor.WordUnderCursor) posCursor.select(QTextCursor.WordUnderCursor)
theWord = posCursor.selectedText().strip().strip(self.nonWord) theWord = posCursor.selectedText().strip().strip(self._nonWord)
spellCheck &= theWord != "" spellCheck &= theWord != ""
if spellCheck: if spellCheck:
@@ -1118,7 +1142,7 @@ class GuiDocEditor(QTextEdit):
"""Slot for the spell check context menu triggered when the user """Slot for the spell check context menu triggered when the user
wants to add a word to the project dictionary. wants to add a word to the project dictionary.
""" """
theWord = theCursor.selectedText().strip().strip(self.nonWord) theWord = theCursor.selectedText().strip().strip(self._nonWord)
logger.debug("Added '%s' to project dictionary" % theWord) logger.debug("Added '%s' to project dictionary" % theWord)
self.theDict.addWord(theWord) self.theDict.addWord(theWord)
self.hLight.setDict(self.theDict) self.hLight.setDict(self.theDict)
@@ -1130,14 +1154,14 @@ class GuiDocEditor(QTextEdit):
"""Decide whether to run the word counter, or not due to """Decide whether to run the word counter, or not due to
inactivity. inactivity.
""" """
if self.theHandle is None: if self._docHandle is None:
return return
if self.wCounter.isRunning(): if self.wCounter.isRunning():
logger.verbose("Word counter is busy") logger.verbose("Word counter is busy")
return return
if time() - self.lastEdit < 5 * self.wcInterval: if time() - self._lastEdit < 5 * self.wcInterval:
logger.verbose("Running word counter") logger.verbose("Running word counter")
self.theParent.threadPool.start(self.wCounter) self.theParent.threadPool.start(self.wCounter)
@@ -1147,23 +1171,23 @@ class GuiDocEditor(QTextEdit):
def _updateCounts(self, cCount, wCount, pCount): def _updateCounts(self, cCount, wCount, pCount):
"""Slot for the word counter's finished signal """Slot for the word counter's finished signal
""" """
if self.theHandle is None or self.nwItem is None: if self._docHandle is None or self._nwItem is None:
return return
logger.verbose("Updating word count") logger.verbose("Updating word count")
self.charCount = cCount self._charCount = cCount
self.wordCount = wCount self._wordCount = wCount
self.paraCount = pCount self._paraCount = pCount
self.nwItem.setCharCount(cCount) self._nwItem.setCharCount(cCount)
self.nwItem.setWordCount(wCount) self._nwItem.setWordCount(wCount)
self.nwItem.setParaCount(pCount) self._nwItem.setParaCount(pCount)
self.theParent.treeView.propagateCount(self.theHandle, wCount) self.theParent.treeView.propagateCount(self._docHandle, wCount)
self.theParent.treeView.projectWordCount() self.theParent.treeView.projectWordCount()
self.theParent.treeMeta.updateCounts(self.theHandle, cCount, wCount, pCount) self.theParent.treeMeta.updateCounts(self._docHandle, cCount, wCount, pCount)
self._checkDocSize(self.qDocument.characterCount()) self._checkDocSize(self._qDocument.characterCount())
self.docFooter.updateCounts() self.docFooter.updateCounts()
return return
@@ -1175,16 +1199,16 @@ class GuiDocEditor(QTextEdit):
large documents to ensure the region where the cursor is being large documents to ensure the region where the cursor is being
moved to has been drawn before the move is made. moved to has been drawn before the move is made.
""" """
if self.queuePos is not None: if self._queuePos is not None:
thePos = self.qDocument.documentLayout().hitTest( thePos = self._qDocument.documentLayout().hitTest(
QPointF(theSize.width(), theSize.height()), Qt.FuzzyHit QPointF(theSize.width(), theSize.height()), Qt.FuzzyHit
) )
if self.queuePos <= thePos: if self._queuePos <= thePos:
logger.verbose("Allowed cursor move to %d <= %d" % (self.queuePos, thePos)) logger.verbose("Allowed cursor move to %d <= %d" % (self._queuePos, thePos))
self.setCursorPosition(self.queuePos) self.setCursorPosition(self._queuePos)
self.queuePos = None self._queuePos = None
else: else:
logger.verbose("Denied cursor move to %d > %d" % (self.queuePos, thePos)) logger.verbose("Denied cursor move to %d > %d" % (self._queuePos, thePos))
return return
## ##
@@ -1241,7 +1265,7 @@ class GuiDocEditor(QTextEdit):
if not wasFound: if not wasFound:
if self.docSearch.doNextFile and not goBack: if self.docSearch.doNextFile and not goBack:
self.theParent.openNextDocument( self.theParent.openNextDocument(
self.theHandle, wrapAround=self.docSearch.doLoop self._docHandle, wrapAround=self.docSearch.doLoop
) )
elif self.docSearch.doLoop: elif self.docSearch.doLoop:
theCursor = self.textCursor() theCursor = self.textCursor()
@@ -1253,7 +1277,7 @@ class GuiDocEditor(QTextEdit):
if wasFound: if wasFound:
theCursor = self.textCursor() theCursor = self.textCursor()
self.lastFind = (theCursor.selectionStart(), theCursor.selectionEnd()) self._lastFind = (theCursor.selectionStart(), theCursor.selectionEnd())
return return
@@ -1278,7 +1302,7 @@ class GuiDocEditor(QTextEdit):
self.findNext() self.findNext()
return return
if self.lastFind is None and theCursor.hasSelection(): if self._lastFind is None and theCursor.hasSelection():
# If we have a selection but no search, it may have been the # If we have a selection but no search, it may have been the
# text we triggered the search with, in which case we search # text we triggered the search with, in which case we search
# again from the beginning of that selection to make sure we # again from the beginning of that selection to make sure we
@@ -1290,7 +1314,7 @@ class GuiDocEditor(QTextEdit):
self.findNext() self.findNext()
theCursor = self.textCursor() theCursor = self.textCursor()
if self.lastFind is None: if self._lastFind is None:
# In case the above didn't find a result, we give up here. # In case the above didn't find a result, we give up here.
return return
@@ -1303,8 +1327,8 @@ class GuiDocEditor(QTextEdit):
# Make sure the selected text was selected by an actual find # Make sure the selected text was selected by an actual find
# call, and not the user. # call, and not the user.
try: try:
isFind = self.lastFind[0] == theCursor.selectionStart() isFind = self._lastFind[0] == theCursor.selectionStart()
isFind &= self.lastFind[1] == theCursor.selectionEnd() isFind &= self._lastFind[1] == theCursor.selectionEnd()
except Exception: except Exception:
isFind = False isFind = False
@@ -1397,25 +1421,25 @@ class GuiDocEditor(QTextEdit):
if self.mainConf.doReplaceDQuote and theTwo == ' "': if self.mainConf.doReplaceDQuote and theTwo == ' "':
nDelete = 1 nDelete = 1
tInsert = self.typDQOpen tInsert = self._typDQOpen
elif self.mainConf.doReplaceDQuote and theOne == '"': elif self.mainConf.doReplaceDQuote and theOne == '"':
nDelete = 1 nDelete = 1
if thePos == 1: if thePos == 1:
tInsert = self.typDQOpen tInsert = self._typDQOpen
else: else:
tInsert = self.typDQClose tInsert = self._typDQClose
elif self.mainConf.doReplaceSQuote and theTwo == " '": elif self.mainConf.doReplaceSQuote and theTwo == " '":
nDelete = 1 nDelete = 1
tInsert = self.typSQOpen tInsert = self._typSQOpen
elif self.mainConf.doReplaceSQuote and theOne == "'": elif self.mainConf.doReplaceSQuote and theOne == "'":
nDelete = 1 nDelete = 1
if thePos == 1: if thePos == 1:
tInsert = self.typSQOpen tInsert = self._typSQOpen
else: else:
tInsert = self.typSQClose tInsert = self._typSQClose
elif self.mainConf.doReplaceDash and theThree == "---": elif self.mainConf.doReplaceDash and theThree == "---":
nDelete = 3 nDelete = 3
@@ -1436,11 +1460,11 @@ class GuiDocEditor(QTextEdit):
tCheck = tInsert tCheck = tInsert
if tCheck in self.mainConf.fmtPadBefore: if tCheck in self.mainConf.fmtPadBefore:
nDelete = max(nDelete, 1) nDelete = max(nDelete, 1)
tInsert = self.typPadChar + tInsert tInsert = self._typPadChar + tInsert
if tCheck in self.mainConf.fmtPadAfter: if tCheck in self.mainConf.fmtPadAfter:
nDelete = max(nDelete, 1) nDelete = max(nDelete, 1)
tInsert = tInsert + self.typPadChar tInsert = tInsert + self._typPadChar
if nDelete > 0: if nDelete > 0:
theCursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, nDelete) theCursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, nDelete)
@@ -1452,18 +1476,18 @@ class GuiDocEditor(QTextEdit):
"""Update the headers record and return True if anything """Update the headers record and return True if anything
changed, if a check flag was provided. changed, if a check flag was provided.
""" """
if self.theHandle is None: if self._docHandle is None:
return False return False
newHeaders = self.theIndex.getHandleHeaders(self.theHandle) newHeaders = self.theIndex.getHandleHeaders(self._docHandle)
if checkPos: if checkPos:
newPos = [x[0] for x in newHeaders] newPos = [x[0] for x in newHeaders]
oldPos = [x[0] for x in self.theHeaders] oldPos = [x[0] for x in self._docHeaders]
if checkLevel: if checkLevel:
newLev = [x[1] for x in newHeaders] newLev = [x[1] for x in newHeaders]
oldLev = [x[1] for x in self.theHeaders] oldLev = [x[1] for x in self._docHeaders]
self.theHeaders = newHeaders self._docHeaders = newHeaders
if checkPos: if checkPos:
return newPos != oldPos return newPos != oldPos
@@ -1532,7 +1556,7 @@ class GuiDocEditor(QTextEdit):
bigLim = self.mainConf.bigDocLimit*1000 bigLim = self.mainConf.bigDocLimit*1000
newState = theSize > bigLim newState = theSize > bigLim
if newState != self.bigDoc: if newState != self._bigDoc:
if newState: if newState:
logger.info( logger.info(
f"The document size is {theSize:n} > {bigLim:n}, " f"The document size is {theSize:n} > {bigLim:n}, "
@@ -1544,7 +1568,7 @@ class GuiDocEditor(QTextEdit):
f"big doc mode has been disabled" f"big doc mode has been disabled"
) )
self.bigDoc = newState self._bigDoc = newState
return return
@@ -1562,8 +1586,8 @@ class GuiDocEditor(QTextEdit):
posS = theCursor.selectionStart() posS = theCursor.selectionStart()
posE = theCursor.selectionEnd() posE = theCursor.selectionEnd()
blockS = self.qDocument.findBlock(posS) blockS = self._qDocument.findBlock(posS)
blockE = self.qDocument.findBlock(posE) blockE = self._qDocument.findBlock(posE)
if blockS != blockE: if blockS != blockE:
posE = blockS.position() + blockS.length() - 1 posE = blockS.position() + blockS.length() - 1
@@ -1616,10 +1640,10 @@ class GuiDocEditor(QTextEdit):
# Underscore counts as a part of the word, so check that the # Underscore counts as a part of the word, so check that the
# selection isn't wrapped in italics markers. # selection isn't wrapped in italics markers.
reSelect = False reSelect = False
if self.qDocument.characterAt(posS) == "_": if self._qDocument.characterAt(posS) == "_":
posS += 1 posS += 1
reSelect = True reSelect = True
if self.qDocument.characterAt(posE) == "_": if self._qDocument.characterAt(posE) == "_":
posE -= 1 posE -= 1
reSelect = True reSelect = True
if reSelect: if reSelect:
@@ -1641,8 +1665,8 @@ class GuiDocEditor(QTextEdit):
posS = theCursor.selectionStart() posS = theCursor.selectionStart()
posE = theCursor.selectionEnd() posE = theCursor.selectionEnd()
blockS = self.qDocument.findBlock(posS) blockS = self._qDocument.findBlock(posS)
blockE = self.qDocument.findBlock(posE) blockE = self._qDocument.findBlock(posE)
if blockS != blockE: if blockS != blockE:
posE = blockS.position() + blockS.length() - 1 posE = blockS.position() + blockS.length() - 1
@@ -1653,14 +1677,14 @@ class GuiDocEditor(QTextEdit):
numB = 0 numB = 0
for n in range(fLen): for n in range(fLen):
if self.qDocument.characterAt(posS-n-1) == fChar: if self._qDocument.characterAt(posS-n-1) == fChar:
numB += 1 numB += 1
else: else:
break break
numA = 0 numA = 0
for n in range(fLen): for n in range(fLen):
if self.qDocument.characterAt(posE+n) == fChar: if self._qDocument.characterAt(posE+n) == fChar:
numA += 1 numA += 1
else: else:
break break
@@ -1804,9 +1828,9 @@ class GuiDocEditor(QTextEdit):
"""used to enable/disable the auto-replace feature temporarily. """used to enable/disable the auto-replace feature temporarily.
""" """
if theState: if theState:
self.doReplace = self.mainConf.doReplace self._doReplace = self.mainConf.doReplace
else: else:
self.doReplace = False self._doReplace = False
return return
# END Class GuiDocEditor # END Class GuiDocEditor
@@ -2242,7 +2266,7 @@ class GuiDocEditHeader(QWidget):
self.theParent = docEditor.theParent self.theParent = docEditor.theParent
self.theProject = docEditor.theProject self.theProject = docEditor.theProject
self.theTheme = docEditor.theTheme self.theTheme = docEditor.theTheme
self.theHandle = None self._docHandle = None
fPx = int(0.9*self.theTheme.fontPixelSize) fPx = int(0.9*self.theTheme.fontPixelSize)
hSp = self.mainConf.pxInt(6) hSp = self.mainConf.pxInt(6)
@@ -2360,7 +2384,7 @@ class GuiDocEditHeader(QWidget):
"""Sets the document title from the handle, or alternatively, """Sets the document title from the handle, or alternatively,
set the whole document path. set the whole document path.
""" """
self.theHandle = tHandle self._docHandle = tHandle
if tHandle is None: if tHandle is None:
self.theTitle.setText("") self.theTitle.setText("")
self.editButton.setVisible(False) self.editButton.setVisible(False)
@@ -2409,7 +2433,7 @@ class GuiDocEditHeader(QWidget):
def _editDocument(self): def _editDocument(self):
"""Open the edit item dialog from the main GUI. """Open the edit item dialog from the main GUI.
""" """
self.theParent.editItem(self.theHandle) self.theParent.editItem(self._docHandle)
return return
def _searchDocument(self): def _searchDocument(self):
@@ -2442,7 +2466,7 @@ class GuiDocEditHeader(QWidget):
"""Capture a click on the title and ensure that the item is """Capture a click on the title and ensure that the item is
selected in the project tree. selected in the project tree.
""" """
self.theParent.treeView.setSelectedHandle(self.theHandle, doScroll=True) self.theParent.treeView.setSelectedHandle(self._docHandle, doScroll=True)
return return
# END Class GuiDocEditHeader # END Class GuiDocEditHeader
@@ -2465,7 +2489,7 @@ class GuiDocEditFooter(QWidget):
self.theProject = docEditor.theProject self.theProject = docEditor.theProject
self.theTheme = docEditor.theTheme self.theTheme = docEditor.theTheme
self.optState = docEditor.theProject.optState self.optState = docEditor.theProject.optState
self.theHandle = None self._docHandle = None
self.theItem = None self.theItem = None
self.sPx = int(round(0.9*self.theTheme.baseIconSize)) self.sPx = int(round(0.9*self.theTheme.baseIconSize))
@@ -2579,12 +2603,12 @@ class GuiDocEditFooter(QWidget):
def setHandle(self, tHandle): def setHandle(self, tHandle):
"""Set the handle that will populate the footer's data. """Set the handle that will populate the footer's data.
""" """
self.theHandle = tHandle self._docHandle = tHandle
if self.theHandle is None: if self._docHandle is None:
logger.verbose("No handle set, so clearing the editor footer") logger.verbose("No handle set, so clearing the editor footer")
self.theItem = None self.theItem = None
else: else:
self.theItem = self.theProject.projTree[self.theHandle] self.theItem = self.theProject.projTree[self._docHandle]
self.updateInfo() self.updateInfo()
self.updateCounts() self.updateCounts()
@@ -2625,7 +2649,7 @@ class GuiDocEditFooter(QWidget):
else: else:
theCursor = self.docEditor.textCursor() theCursor = self.docEditor.textCursor()
iLine = theCursor.blockNumber() + 1 iLine = theCursor.blockNumber() + 1
iDist = 100*iLine/self.docEditor.qDocument.blockCount() iDist = 100*iLine/self.docEditor._qDocument.blockCount()
self.linesText.setText( self.linesText.setText(
self.tr("Line: {0} ({1})").format(f"{iLine:n}", f"{iDist:.0f} %") self.tr("Line: {0} ({1})").format(f"{iLine:n}", f"{iDist:.0f} %")
@@ -2647,7 +2671,7 @@ class GuiDocEditFooter(QWidget):
self.tr("Words: {0} ({1})").format(f"{wCount:n}", f"{wDiff:+n}") self.tr("Words: {0} ({1})").format(f"{wCount:n}", f"{wDiff:+n}")
) )
byteSize = self.docEditor.qDocument.characterCount() byteSize = self.docEditor._qDocument.characterCount()
self.wordsText.setToolTip( self.wordsText.setToolTip(
self.tr("Document size is {0} bytes").format(f"{byteSize:n}") self.tr("Document size is {0} bytes").format(f"{byteSize:n}")
) )
+1 -1
View File
@@ -876,7 +876,7 @@ class GuiDocViewHeader(QWidget):
def _refreshDocument(self): def _refreshDocument(self):
"""Reload the content of the document. """Reload the content of the document.
""" """
if self.docViewer.theHandle == self.theParent.docEditor.theHandle: if self.docViewer.theHandle == self.theParent.docEditor.docHandle():
self.theParent.saveDocument() self.theParent.saveDocument()
self.docViewer.reloadText() self.docViewer.reloadText()
return return
+1 -1
View File
@@ -524,7 +524,7 @@ class GuiProjectTree(QTreeWidget):
tIndex = trItemP.indexOfChild(trItemS) tIndex = trItemP.indexOfChild(trItemS)
trItemC = trItemP.takeChild(tIndex) trItemC = trItemP.takeChild(tIndex)
if self.theParent.docEditor.theHandle == tHandle: if self.theParent.docEditor.docHandle() == tHandle:
self.theParent.closeDocument() self.theParent.closeDocument()
delDoc = NWDoc(self.theProject, tHandle) delDoc = NWDoc(self.theProject, tHandle)
+8 -8
View File
@@ -407,7 +407,7 @@ class GuiMain(QMainWindow):
if not msgYes: if not msgYes:
return False return False
if self.docEditor.docChanged: if self.docEditor.docChanged():
self.saveDocument() self.saveDocument()
if self.theProject.projAltered: if self.theProject.projAltered:
@@ -576,7 +576,7 @@ class GuiMain(QMainWindow):
self.toggleFocusMode() self.toggleFocusMode()
self.docEditor.saveCursorPosition() self.docEditor.saveCursorPosition()
if self.docEditor.docChanged: if self.docEditor.docChanged():
self.saveDocument() self.saveDocument()
self.docEditor.clearEditor() self.docEditor.clearEditor()
@@ -658,7 +658,7 @@ class GuiMain(QMainWindow):
if self.docEditor.hasFocus(): if self.docEditor.hasFocus():
logger.verbose("Trying editor document") logger.verbose("Trying editor document")
tHandle = self.docEditor.theHandle tHandle = self.docEditor.docHandle()
if tHandle is not None: if tHandle is not None:
self.saveDocument() self.saveDocument()
@@ -727,7 +727,7 @@ class GuiMain(QMainWindow):
], nwAlert.ERROR) ], nwAlert.ERROR)
return False return False
if self.docEditor.theHandle is None: if self.docEditor.docHandle() is None:
self.makeAlert( self.makeAlert(
self.tr("Please open a document to import the text file into."), self.tr("Please open a document to import the text file into."),
nwAlert.ERROR nwAlert.ERROR
@@ -822,7 +822,7 @@ class GuiMain(QMainWindow):
if tHandle is None: if tHandle is None:
if self.docEditor.anyFocus() or self.isFocusMode: if self.docEditor.anyFocus() or self.isFocusMode:
tHandle = self.docEditor.theHandle tHandle = self.docEditor.docHandle()
else: else:
tHandle = self.treeView.getSelectedHandle() tHandle = self.treeView.getSelectedHandle()
@@ -1218,7 +1218,7 @@ class GuiMain(QMainWindow):
"""Main GUI Focus Mode hides tree, view pane and optionally also """Main GUI Focus Mode hides tree, view pane and optionally also
statusbar and menu. statusbar and menu.
""" """
if self.docEditor.theHandle is None: if self.docEditor.docHandle() is None:
logger.error("No document open, so not activating Focus Mode") logger.error("No document open, so not activating Focus Mode")
self.mainMenu.setFocusMode(self.isFocusMode) self.mainMenu.setFocusMode(self.isFocusMode)
return False return False
@@ -1385,7 +1385,7 @@ class GuiMain(QMainWindow):
"""Triggered by the auto-save document timer to save the """Triggered by the auto-save document timer to save the
document. document.
""" """
if self.hasProject and self.docEditor.docChanged: if self.hasProject and self.docEditor.docChanged():
logger.debug("Autosaving document") logger.debug("Autosaving document")
self.saveDocument() self.saveDocument()
return return
@@ -1477,7 +1477,7 @@ class GuiMain(QMainWindow):
return return
currTime = time() currTime = time()
editIdle = currTime - self.docEditor.lastActive > self.mainConf.userIdleTime editIdle = currTime - self.docEditor.lastActive() > self.mainConf.userIdleTime
userIdle = qApp.applicationState() != Qt.ApplicationActive userIdle = qApp.applicationState() != Qt.ApplicationActive
if editIdle or userIdle: if editIdle or userIdle:
+3 -3
View File
@@ -292,9 +292,9 @@ def testGuiEditor_Main(qtbot, monkeypatch, nwGUI, fncDir, fncProj, refDir, outDi
qtbot.wait(stepDelay) qtbot.wait(stepDelay)
# Save the document # Save the document
assert nwGUI.docEditor.docChanged assert nwGUI.docEditor.docChanged()
assert nwGUI.saveDocument() assert nwGUI.saveDocument()
assert not nwGUI.docEditor.docChanged assert not nwGUI.docEditor.docChanged()
qtbot.wait(stepDelay) qtbot.wait(stepDelay)
nwGUI.rebuildIndex() nwGUI.rebuildIndex()
qtbot.wait(stepDelay) qtbot.wait(stepDelay)
@@ -503,7 +503,7 @@ def testGuiEditor_Search(qtbot, monkeypatch, nwGUI, nwLipsum):
# Next Match # Next Match
nwGUI.mainMenu.aFindNext.activate(QAction.Trigger) nwGUI.mainMenu.aFindNext.activate(QAction.Trigger)
assert nwGUI.docEditor.theHandle == "2426c6f0ca922" # Next document assert nwGUI.docEditor.docHandle() == "2426c6f0ca922" # Next document
nwGUI.mainMenu.aFindNext.activate(QAction.Trigger) nwGUI.mainMenu.aFindNext.activate(QAction.Trigger)
assert abs(nwGUI.docEditor.getCursorPosition() - 620) < 3 assert abs(nwGUI.docEditor.getCursorPosition() - 620) < 3
nwGUI.mainMenu.aFindNext.activate(QAction.Trigger) nwGUI.mainMenu.aFindNext.activate(QAction.Trigger)
+2 -2
View File
@@ -97,9 +97,9 @@ def testGuiNovelTree_TreeItems(qtbot, caplog, monkeypatch, nwGUI, nwMinimal):
# Double-click item # Double-click item
scItem.setSelected(True) scItem.setSelected(True)
assert scItem.isSelected() assert scItem.isSelected()
assert nwGUI.docEditor.theHandle is None assert nwGUI.docEditor.docHandle() is None
nwTree._treeDoubleClick(scItem, 0) nwTree._treeDoubleClick(scItem, 0)
assert nwGUI.docEditor.theHandle == "8c659a11cd429" assert nwGUI.docEditor.docHandle() == "8c659a11cd429"
# Open item with middle mouse button # Open item with middle mouse button
scItem.setSelected(True) scItem.setSelected(True)