Update linting for main code

This commit is contained in:
Veronica Berglyd Olsen
2025-08-27 21:00:09 +02:00
parent 84ff1f4640
commit c174f8f931
80 changed files with 461 additions and 1653 deletions
+7 -9
View File
@@ -20,7 +20,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import logging
@@ -45,6 +45,12 @@ logger = logging.getLogger(__name__)
class GuiDictionaries(NNonBlockingDialog):
"""GUI: Spell Check Dictionary Tool.
A helper tool for downloading and extracting dictionaries to a
location where Enchant can find them. This tool is only needed on
Windows.
"""
def __init__(self, parent: QWidget) -> None:
super().__init__(parent=parent)
@@ -123,11 +129,8 @@ class GuiDictionaries(NNonBlockingDialog):
logger.debug("Ready: GuiDictionaries")
return
def __del__(self) -> None: # pragma: no cover
logger.debug("Delete: GuiDictionaries")
return
def initDialog(self) -> bool:
"""Prepare and check that we can proceed."""
@@ -164,7 +167,6 @@ class GuiDictionaries(NNonBlockingDialog):
"""Capture the user closing the window."""
event.accept()
self.softDelete()
return
##
# Private Slots
@@ -182,7 +184,6 @@ class GuiDictionaries(NNonBlockingDialog):
if soxFile:
path = Path(soxFile).absolute()
self.huInput.setText(str(path))
return
@pyqtSlot()
def _doImportHunspell(self) -> None:
@@ -202,14 +203,12 @@ class GuiDictionaries(NNonBlockingDialog):
self._appendLog(formatException(exc), err=True)
else:
self._appendLog(procErr, err=True)
return
@pyqtSlot()
def _doOpenInstallLocation(self) -> None:
"""Open the dictionary folder."""
if not openExternalPath(Path(self.inPath.text())):
SHARED.error("Path not found.")
return
##
# Internal Functions
@@ -247,4 +246,3 @@ class GuiDictionaries(NNonBlockingDialog):
cursor.movePosition(QTextCursor.MoveOperation.End)
cursor.deleteChar()
self.infoBox.setTextCursor(cursor)
return
+2 -5
View File
@@ -20,7 +20,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import logging
@@ -42,6 +42,7 @@ logger = logging.getLogger(__name__)
class GuiLipsum(NDialog):
"""GUI: Lorem Ipsum Text Tool."""
def __init__(self, parent: QWidget) -> None:
super().__init__(parent=parent)
@@ -111,11 +112,8 @@ class GuiLipsum(NDialog):
logger.debug("Ready: GuiLipsum")
return
def __del__(self) -> None: # pragma: no cover
logger.debug("Delete: GuiLipsum")
return
@property
def lipsumText(self) -> str:
@@ -145,4 +143,3 @@ class GuiLipsum(NDialog):
pCount = self.paraCount.value()
self._lipsumText = "\n\n".join(lipsumText[0:pCount]) + "\n\n"
self.close()
return
+2 -14
View File
@@ -20,7 +20,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import logging
@@ -54,7 +54,7 @@ logger = logging.getLogger(__name__)
class GuiManuscriptBuild(NDialog):
"""GUI Tools: Manuscript Build Dialog
"""GUI Tools: Manuscript Build Dialog.
This is the tool for running the build itself. It can be accessed
independently of the Manuscript Build Tool.
@@ -244,11 +244,8 @@ class GuiManuscriptBuild(NDialog):
logger.debug("Ready: GuiManuscriptBuild")
return
def __del__(self) -> None: # pragma: no cover
logger.debug("Delete: GuiManuscriptBuild")
return
##
# Events
@@ -261,7 +258,6 @@ class GuiManuscriptBuild(NDialog):
self._saveSettings()
event.accept()
self.softDelete()
return
##
# Private Slots
@@ -278,7 +274,6 @@ class GuiManuscriptBuild(NDialog):
self._openOutputFolder()
elif role == QtRoleReject:
self.close()
return
@pyqtSlot()
def _doSelectPath(self) -> None:
@@ -290,7 +285,6 @@ class GuiManuscriptBuild(NDialog):
)
if savePath:
self.buildPath.setText(savePath)
return
@pyqtSlot()
def _doResetBuildName(self) -> None:
@@ -298,13 +292,11 @@ class GuiManuscriptBuild(NDialog):
bName = f"{SHARED.project.data.name} - {self._build.name}"
self.buildName.setText(bName)
self._build.setLastBuildName(bName)
return
@pyqtSlot()
def _resetProgress(self) -> None:
"""Set the progress bar back to 0."""
self.buildProgress.setValue(0)
return
##
# Internal Functions
@@ -371,7 +363,6 @@ class GuiManuscriptBuild(NDialog):
pOptions.setValue("GuiManuscriptBuild", "fmtWidth", mainSplit[0])
pOptions.setValue("GuiManuscriptBuild", "sumWidth", mainSplit[1])
pOptions.saveSettings()
return
def _populateContentList(self) -> None:
"""Build the content list."""
@@ -396,9 +387,6 @@ class GuiManuscriptBuild(NDialog):
item.setIcon(nwItem.getMainIcon())
self.listContent.addItem(item)
return
def _openOutputFolder(self) -> None:
"""Open the build folder in the system's file explorer."""
openExternalPath(Path(self.buildPath.text()))
return
+2 -54
View File
@@ -20,7 +20,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import logging
@@ -66,7 +66,7 @@ logger = logging.getLogger(__name__)
class GuiManuscript(NToolDialog):
"""GUI Tools: Manuscript Tool
"""GUI Tools: Manuscript Tool.
The dialog displays all the users build definitions, a preview panel
for the manuscript, and can trigger the actual build dialog to build
@@ -251,11 +251,8 @@ class GuiManuscript(NToolDialog):
logger.debug("Ready: GuiManuscript")
return
def __del__(self) -> None: # pragma: no cover
logger.debug("Delete: GuiManuscript")
return
def loadContent(self) -> None:
"""Load dialog content from project data."""
@@ -272,8 +269,6 @@ class GuiManuscript(NToolDialog):
self.buildList.setCurrentItem(self._buildMap[selected])
QTimer.singleShot(200, self._generatePreview)
return
##
# Events
##
@@ -290,7 +285,6 @@ class GuiManuscript(NToolDialog):
obj.close()
event.accept()
self.softDelete()
return
##
# Private Slots
@@ -302,14 +296,12 @@ class GuiManuscript(NToolDialog):
build = BuildSettings()
build.setName(self.tr("My Manuscript"))
self._openSettingsDialog(build)
return
@pyqtSlot()
def _editSelectedBuild(self) -> None:
"""Edit the currently selected build settings entry."""
if build := self._getSelectedBuild():
self._openSettingsDialog(build)
return
@pyqtSlot()
def _copySelectedBuild(self) -> None:
@@ -320,14 +312,12 @@ class GuiManuscript(NToolDialog):
self._updateBuildsList()
if item := self._buildMap.get(new.buildID):
item.setSelected(True)
return
@pyqtSlot("QListWidgetItem*", "QListWidgetItem*")
def _updateBuildDetails(self, current: QListWidgetItem, previous: QListWidgetItem) -> None:
"""Process change of build selection to update the details."""
if current and (build := self._builds.getBuild(current.data(self.D_KEY))):
self.buildDetails.updateInfo(build)
return
@pyqtSlot()
def _deleteSelectedBuild(self) -> None:
@@ -338,7 +328,6 @@ class GuiManuscript(NToolDialog):
dialog.close()
self._builds.removeBuild(build.buildID)
self._updateBuildsList()
return
@pyqtSlot(BuildSettings)
def _processNewSettings(self, build: BuildSettings) -> None:
@@ -347,7 +336,6 @@ class GuiManuscript(NToolDialog):
self._updateBuildItem(build)
if (current := self.buildList.currentItem()) and current.data(self.D_KEY) == build.buildID:
self._updateBuildDetails(current, current)
return
@pyqtSlot()
def _generatePreview(self) -> None:
@@ -399,15 +387,12 @@ class GuiManuscript(NToolDialog):
if build.changed:
self._builds.setBuild(build)
return
@pyqtSlot()
def _printDocument(self) -> None:
"""Open the print preview dialog."""
preview = QPrintPreviewDialog(self)
preview.paintRequested.connect(self.docPreview.printPreview)
preview.exec()
return
##
# Internal Functions
@@ -456,8 +441,6 @@ class GuiManuscript(NToolDialog):
pOptions.setValue("GuiManuscript", "showNewPage", showNewPage)
pOptions.saveSettings()
return
def _openSettingsDialog(self, build: BuildSettings) -> None:
"""Open the build settings dialog."""
if dialog := self._findSettingsDialog(build.buildID):
@@ -482,7 +465,6 @@ class GuiManuscript(NToolDialog):
bItem.setData(self.D_KEY, key)
self.buildList.addItem(bItem)
self._buildMap[key] = bItem
return
def _updateBuildItem(self, build: BuildSettings) -> None:
"""Update the entry of a specific build item."""
@@ -490,7 +472,6 @@ class GuiManuscript(NToolDialog):
item.setText(build.name)
else: # Probably a new item
self._updateBuildsList()
return
def _findSettingsDialog(self, buildID: str) -> GuiBuildSettings | None:
"""Return an open build settings dialog for a given build, if
@@ -521,8 +502,6 @@ class _DetailsWidget(QWidget):
self.outerBox.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.outerBox)
return
##
# Getters
##
@@ -547,7 +526,6 @@ class _DetailsWidget(QWidget):
def setColumnWidth(self, value: int) -> None:
"""Set the width of the first column."""
self.listView.setColumnWidth(0, value)
return
def setExpandedState(self, state: list[bool]) -> None:
"""Set the expanded state of each top level item."""
@@ -556,7 +534,6 @@ class _DetailsWidget(QWidget):
item = self.listView.topLevelItem(i)
if isinstance(item, QTreeWidgetItem):
item.setExpanded((state[i] if i < count else True) and item.childCount() > 0)
return
##
# Methods
@@ -637,8 +614,6 @@ class _DetailsWidget(QWidget):
# Restore expanded state
self.setExpandedState(expanded)
return
class _OutlineWidget(QWidget):
@@ -663,8 +638,6 @@ class _OutlineWidget(QWidget):
self.outerBox.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.outerBox)
return
def updateOutline(self, data: dict[str, str]) -> None:
"""Update the outline."""
if isinstance(data, dict) and data != self._outline:
@@ -705,8 +678,6 @@ class _OutlineWidget(QWidget):
self.listView.setIndentation(SHARED.theme.baseIconHeight if indent else 4)
self._outline = data
return
##
# Private Slots
##
@@ -714,7 +685,6 @@ class _OutlineWidget(QWidget):
def _onItemClick(self, item: QTreeWidgetItem) -> None:
"""Process tree item click."""
self.outlineEntryClicked.emit(str(item.data(0, self.D_LINE)))
return
class _PreviewWidget(QTextBrowser):
@@ -787,8 +757,6 @@ class _PreviewWidget(QTextBrowser):
self.ageTimer.timeout.connect(self._updateBuildAge)
self.ageTimer.start()
return
##
# Setters
##
@@ -797,7 +765,6 @@ class _PreviewWidget(QTextBrowser):
"""Set the build name for the document label."""
self._buildName = name
self._updateBuildAge()
return
def setTextFont(self, font: QFont) -> None:
"""Set the text font properties and then reset for sub-widgets.
@@ -807,7 +774,6 @@ class _PreviewWidget(QTextBrowser):
self.setFont(font)
self.buildProgress.setFont(SHARED.theme.guiFont)
self.ageLabel.setFont(SHARED.theme.guiFontSmall)
return
##
# Methods
@@ -823,13 +789,11 @@ class _PreviewWidget(QTextBrowser):
self._scrollPos = vBar.value()
self.setPlaceholderText("")
self.clear()
return
def buildStep(self, value: int) -> None:
"""Update the progress bar value."""
self.buildProgress.setValue(value)
QApplication.processEvents()
return
def setContent(self, document: QTextDocument) -> None:
"""Set the content of the preview widget."""
@@ -850,8 +814,6 @@ class _PreviewWidget(QTextBrowser):
QApplication.processEvents()
QTimer.singleShot(300, self._postUpdate)
return
##
# Events
##
@@ -860,7 +822,6 @@ class _PreviewWidget(QTextBrowser):
"""Capture resize and update the document margins."""
super().resizeEvent(event)
self._updateDocMargins()
return
##
# Public Slots
@@ -874,14 +835,12 @@ class _PreviewWidget(QTextBrowser):
printer.setPageOrientation(QPageLayout.Orientation.Portrait)
document.print(printer)
QApplication.restoreOverrideCursor()
return
@pyqtSlot(str)
def navigateTo(self, anchor: str) -> None:
"""Go to a specific #link in the document."""
logger.debug("Moving to anchor '#%s'", anchor)
self.setSource(QUrl(f"#{anchor}"))
return
##
# Private Slots
@@ -896,7 +855,6 @@ class _PreviewWidget(QTextBrowser):
self.navigateTo(link.lstrip("#"))
elif link.startswith("http"):
QDesktopServices.openUrl(QUrl(url))
return
@pyqtSlot()
def _updateBuildAge(self) -> None:
@@ -909,7 +867,6 @@ class _PreviewWidget(QTextBrowser):
))
else:
self.ageLabel.setText("<b>{0}</b>".format(self.tr("No Preview")))
return
@pyqtSlot()
def _postUpdate(self) -> None:
@@ -917,7 +874,6 @@ class _PreviewWidget(QTextBrowser):
self.buildProgress.setVisible(False)
if vBar := self.verticalScrollBar():
vBar.setValue(self._scrollPos)
return
##
# Internal Functions
@@ -936,7 +892,6 @@ class _PreviewWidget(QTextBrowser):
self.ageLabel.setGeometry(tB, tB, vW, tH)
self.setViewportMargins(0, tH, 0, 0)
self.buildProgress.move((vW-pS)//2, (vH-pS)//2)
return
class _StatsWidget(QWidget):
@@ -969,8 +924,6 @@ class _StatsWidget(QWidget):
self._toggleView(False)
return
def updateStats(self, data: dict[str, int]) -> None:
"""Update the stats values from a Tokenizer stats dict."""
# Minimal
@@ -992,8 +945,6 @@ class _StatsWidget(QWidget):
self.maxHeadWordChars.setText(f"{data.get(nwStats.WCHARS_TITLE, 0):n}")
self.maxTextWordChars.setText(f"{data.get(nwStats.WCHARS_TEXT, 0):n}")
return
##
# Private Slots
##
@@ -1013,7 +964,6 @@ class _StatsWidget(QWidget):
self.minWidget.adjustSize()
self.mainStack.adjustSize()
self.adjustSize()
return
##
# Internal Functions
@@ -1105,5 +1055,3 @@ class _StatsWidget(QWidget):
self.minWidget.setLayout(self.minLayout)
self.maxWidget.setLayout(self.maxLayout)
return
+8 -54
View File
@@ -20,7 +20,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import logging
@@ -62,7 +62,7 @@ logger = logging.getLogger(__name__)
class GuiBuildSettings(NToolDialog):
"""GUI Tools: Manuscript Build Settings Dialog
"""GUI Tools: Manuscript Build Settings Dialog.
The main tool for configuring manuscript builds. It's a GUI tool for
editing JSON build definitions, wrapped as a BuildSettings object.
@@ -153,11 +153,8 @@ class GuiBuildSettings(NToolDialog):
logger.debug("Ready: GuiBuildSettings")
return
def __del__(self) -> None: # pragma: no cover
logger.debug("Delete: GuiBuildSettings")
return
def loadContent(self) -> None:
"""Populate the child widgets."""
@@ -165,7 +162,6 @@ class GuiBuildSettings(NToolDialog):
self.optTabSelect.loadContent()
self.optTabHeadings.loadContent()
self.optTabFormatting.loadContent()
return
##
# Properties
@@ -190,7 +186,6 @@ class GuiBuildSettings(NToolDialog):
self._saveSettings()
event.accept()
self.softDelete()
return
##
# Private Slots
@@ -206,7 +201,6 @@ class GuiBuildSettings(NToolDialog):
elif pageId >= self.OPT_FORMATTING:
self.toolStack.setCurrentWidget(self.optTabFormatting)
self.optTabFormatting.scrollToSection(pageId)
return
@pyqtSlot("QAbstractButton*")
def _dialogButtonClicked(self, button: QAbstractButton) -> None:
@@ -222,7 +216,6 @@ class GuiBuildSettings(NToolDialog):
elif role == QtRoleReject:
self._build.resetChangedState()
self.close()
return
##
# Internal Functions
@@ -238,7 +231,6 @@ class GuiBuildSettings(NToolDialog):
).format(self._build.name)):
self._emitBuildData()
self._build.resetChangedState()
return
def _saveSettings(self) -> None:
"""Save the various user settings."""
@@ -250,20 +242,17 @@ class GuiBuildSettings(NToolDialog):
pOptions.setValue("GuiBuildSettings", "treeWidth", treeWidth)
pOptions.setValue("GuiBuildSettings", "filterWidth", filterWidth)
pOptions.saveSettings()
return
def _applyChanges(self) -> None:
"""Apply all settings changes to the build object."""
self._build.setName(self.editBuildName.text())
self.optTabHeadings.saveContent()
self.optTabFormatting.saveContent()
return
def _emitBuildData(self) -> None:
"""Assemble the build data and emit the signal."""
self.newSettingsReady.emit(self._build)
self._build.resetChangedState()
return
class _FilterTab(NFixedPage):
@@ -382,13 +371,10 @@ class _FilterTab(NFixedPage):
self.setCentralWidget(self.mainSplit)
return
def loadContent(self) -> None:
"""Populate the widgets."""
self._populateTree()
self._populateFilters()
return
def mainSplitSizes(self) -> tuple[int, int]:
"""Extract the sizes of the main splitter."""
@@ -409,7 +395,6 @@ class _FilterTab(NFixedPage):
elif key.startswith("root:"):
self._build.setAllowRoot(key[5:], state)
self._populateTree()
return
##
# Internal Functions
@@ -453,8 +438,6 @@ class _FilterTab(NFixedPage):
self._setTreeItemMode()
return
def _populateFilters(self) -> None:
"""Populate the filter options switches."""
self.filterOpt.clear()
@@ -489,8 +472,6 @@ class _FilterTab(NFixedPage):
default=self._build.isRootAllowed(tHandle)
)
return
def _setSelectedMode(self, mode: int) -> None:
"""Set the mode for the selected items."""
items = self.optTree.selectedItems()
@@ -511,8 +492,6 @@ class _FilterTab(NFixedPage):
self._setTreeItemMode()
return
def _setTreeItemMode(self) -> None:
"""Update the filtered mode icon on all items."""
filtered = self._build.buildItemFilter(SHARED.project)
@@ -529,11 +508,10 @@ class _FilterTab(NFixedPage):
item.setToolTip(self.C_STATUS, self._trIncluded)
else:
item.setIcon(self.C_STATUS, self._statusFlags[self.F_NONE])
return
def _scanChildren(self, item: QTreeWidgetItem | None, items: list) -> list[QTreeWidgetItem]:
"""This is a recursive function returning all items in a tree
starting at a given QTreeWidgetItem.
"""Recursively return all items in a tree starting at a given
QTreeWidgetItem.
"""
if isinstance(item, QTreeWidgetItem):
items.append(item)
@@ -791,8 +769,6 @@ class _HeadingsTab(NScrollablePage):
self.setCentralLayout(self.outerBox)
return
def loadContent(self) -> None:
"""Populate the widgets."""
def fmtBreak(text: str) -> str:
@@ -821,7 +797,6 @@ class _HeadingsTab(NScrollablePage):
self.breakPart.setChecked(self._build.getBool("headings.breakPart"))
self.breakChapter.setChecked(self._build.getBool("headings.breakChapter"))
self.breakScene.setChecked(self._build.getBool("headings.breakScene"))
return
def saveContent(self) -> None:
"""Save choices back into build object."""
@@ -841,7 +816,6 @@ class _HeadingsTab(NScrollablePage):
self._build.setValue("headings.breakPart", self.breakPart.isChecked())
self._build.setValue("headings.breakChapter", self.breakChapter.isChecked())
self._build.setValue("headings.breakScene", self.breakScene.isChecked())
return
##
# Internal Functions
@@ -853,7 +827,6 @@ class _HeadingsTab(NScrollablePage):
cursor = self.editTextBox.textCursor()
cursor.insertText(text)
self.editTextBox.setFocus()
return
def _editHeading(self, heading: int) -> None:
"""Populate the form with a specific heading format."""
@@ -886,8 +859,6 @@ class _HeadingsTab(NScrollablePage):
self.editTextBox.setPlainText(text.replace(nwUnicode.U_LBREAK, "\n"))
self.lblEditForm.setText(self.tr("Editing: {0}").format(label))
return
##
# Private Slots
##
@@ -934,7 +905,6 @@ class _HeadingSyntaxHighlighter(QSyntaxHighlighter):
self._fmtSymbol.setForeground(syntax.head)
self._fmtFormat = QTextCharFormat()
self._fmtFormat.setForeground(syntax.emph)
return
def highlightBlock(self, text: str) -> None:
"""Add syntax highlighting to the text block."""
@@ -947,7 +917,6 @@ class _HeadingSyntaxHighlighter(QSyntaxHighlighter):
ddots = heading.find(":")
if ddots > 0:
self.setFormat(pos + ddots, 1, self._fmtSymbol)
return
class _FormattingTab(NScrollableForm):
@@ -961,8 +930,6 @@ class _FormattingTab(NScrollableForm):
self.setHelpTextStyle(SHARED.theme.helpText)
self.buildForm()
return
def buildForm(self) -> None:
"""Build the formatting form."""
section = 10
@@ -1290,8 +1257,6 @@ class _FormattingTab(NScrollableForm):
# Finalise
self.finalise()
return
def loadContent(self) -> None:
"""Populate the widgets."""
# Text Content
@@ -1391,8 +1356,6 @@ class _FormattingTab(NScrollableForm):
self.htmlAddStyles.setChecked(self._build.getBool("html.addStyles"))
self.htmlPreserveTabs.setChecked(self._build.getBool("html.preserveTabs"))
return
def saveContent(self) -> None:
"""Save choices back into build object."""
# Text Content
@@ -1458,8 +1421,6 @@ class _FormattingTab(NScrollableForm):
self._build.setValue("html.addStyles", self.htmlAddStyles.isChecked())
self._build.setValue("html.preserveTabs", self.htmlPreserveTabs.isChecked())
return
##
# Private Slots
##
@@ -1472,11 +1433,10 @@ class _FormattingTab(NScrollableForm):
self._textFont = fontMatcher(font)
self.textFont.setText(describeFont(self._textFont))
self.textFont.setCursorPosition(0)
return
@pyqtSlot(int)
def _changeUnit(self, index: int) -> None:
"""The current unit change, so recalculate sizes."""
"""Process current unit change to recalculate sizes."""
newUnit = self.pageUnit.itemData(index)
newScale = nwLabels.UNIT_SCALE.get(newUnit, 1.0)
reScale = self._unitScale/newScale
@@ -1531,11 +1491,9 @@ class _FormattingTab(NScrollableForm):
self._unitScale = newScale
self._changePageSize(self.pageSize.currentIndex())
return
@pyqtSlot(int)
def _changePageSize(self, index: int) -> None:
"""The page size has changed."""
"""Process page size change."""
w, h = nwLabels.PAPER_SIZE[self.pageSize.itemData(index)] if index >= 0 else (-1.0, -1.0)
if w > 0.0 and h > 0.0:
self.pageWidth.blockSignals(True)
@@ -1544,23 +1502,20 @@ class _FormattingTab(NScrollableForm):
self.pageHeight.blockSignals(True)
self.pageHeight.setValue(h/self._unitScale)
self.pageHeight.blockSignals(False)
return
@pyqtSlot()
def _pageSizeValueChanged(self) -> None:
"""The user has changed the page size spin boxes, so we flip
the page size box to Custom.
"""Process that the user has changed the page size spin boxes,
so we flip the page size box to Custom.
"""
index = self.pageSize.findData("Custom")
if index >= 0:
self.pageSize.setCurrentIndex(index)
return
def _resetPageHeader(self) -> None:
"""Reset the ODT header format to default."""
self.odtPageHeader.setText(nwHeadFmt.DOC_AUTO)
self.odtPageHeader.setCursorPosition(0)
return
##
# Internal Functions
@@ -1573,4 +1528,3 @@ class _FormattingTab(NScrollableForm):
current.append(keyword)
verified = set(x for x in current if x in nwKeyWords.VALID_KEYS)
self.ignoredKeywords.setText(", ".join(verified))
return
+2 -20
View File
@@ -20,7 +20,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import logging
@@ -52,6 +52,7 @@ logger = logging.getLogger(__name__)
class GuiNovelDetails(NNonBlockingDialog):
"""GUI: Novel Details Tool."""
PAGE_OVERVIEW = 1
PAGE_CONTENTS = 2
@@ -130,11 +131,8 @@ class GuiNovelDetails(NNonBlockingDialog):
logger.debug("Ready: GuiNovelDetails")
return
def __del__(self) -> None: # pragma: no cover
logger.debug("Delete: GuiNovelDetails")
return
##
# Methods
@@ -146,7 +144,6 @@ class GuiNovelDetails(NNonBlockingDialog):
self.overviewPage.updateProjectData()
self.overviewPage.novelValueChanged(handle)
self.contentsPage.novelValueChanged(handle)
return
##
# Events
@@ -157,7 +154,6 @@ class GuiNovelDetails(NNonBlockingDialog):
self._saveSettings()
event.accept()
self.softDelete()
return
##
# Private Slots
@@ -170,7 +166,6 @@ class GuiNovelDetails(NNonBlockingDialog):
self.mainStack.setCurrentWidget(self.overviewPage)
elif pageId == self.PAGE_CONTENTS:
self.mainStack.setCurrentWidget(self.contentsPage)
return
##
# Internal Functions
@@ -185,7 +180,6 @@ class GuiNovelDetails(NNonBlockingDialog):
options.setValue("GuiNovelDetails", "winHeight", self.height())
options.setValue("GuiNovelDetails", "novelRoot", novelRoot)
self.contentsPage.saveSettings()
return
class _OverviewPage(NScrollablePage):
@@ -248,8 +242,6 @@ class _OverviewPage(NScrollablePage):
self.setCentralLayout(self.outerBox)
return
##
# Methods
##
@@ -266,7 +258,6 @@ class _OverviewPage(NScrollablePage):
self.projWords.setText(f"{wcNovel + wcNotes:n}")
self.projNovels.setText(f"{wcNovel:n}")
self.projNotes.setText(f"{wcNotes:n}")
return
##
# Public Slots
@@ -286,8 +277,6 @@ class _OverviewPage(NScrollablePage):
self.novelChapters.setText(f"{hCounts[2]:n}")
self.novelScenes.setText(f"{hCounts[3]:n}")
return
class _ContentsPage(NFixedPage):
@@ -400,8 +389,6 @@ class _ContentsPage(NFixedPage):
self.setCentralLayout(self.outerBox)
return
def saveSettings(self) -> None:
"""Save the user GUI settings."""
options = SHARED.project.options
@@ -413,7 +400,6 @@ class _ContentsPage(NFixedPage):
options.setValue("GuiNovelDetails", "wordsPerPage", self.wpValue.value())
options.setValue("GuiNovelDetails", "countFrom", self.poValue.value())
options.setValue("GuiNovelDetails", "clearDouble", self.dblValue.isChecked())
return
##
# Public Slots
@@ -426,7 +412,6 @@ class _ContentsPage(NFixedPage):
self._prepareData(tHandle)
self._populateTree()
self._currentRoot = tHandle
return
##
# Private Slots
@@ -496,8 +481,6 @@ class _ContentsPage(NFixedPage):
self.tocTree.addTopLevelItem(newItem)
return
##
# Internal Functions
##
@@ -507,4 +490,3 @@ class _ContentsPage(NFixedPage):
logger.debug("Populating ToC from handle '%s'", rootHandle)
self._data = SHARED.project.index.getTableOfContents(rootHandle, 2)
self._data.append(("", 0, self.tr("END"), 0))
return
+6 -39
View File
@@ -20,7 +20,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import logging
@@ -56,6 +56,11 @@ PANEL_ALPHA = 178
class GuiWelcome(NDialog):
"""GUI: Welcome Dialog.
This is the main dialog shown when novelWriter launches or when the
user wants to create or open another project.
"""
openProjectRequest = pyqtSignal(Path)
@@ -161,11 +166,8 @@ class GuiWelcome(NDialog):
logger.debug("Ready: GuiWelcome")
return
def __del__(self) -> None: # pragma: no cover
logger.debug("Delete: GuiWelcome")
return
##
# Events
@@ -180,14 +182,12 @@ class GuiWelcome(NDialog):
painter.drawPixmap(0, hWin - hPix, self.bgImage.scaledToHeight(hPix, tMode))
painter.end()
super().paintEvent(event)
return
def closeEvent(self, event: QCloseEvent) -> None:
"""Capture the user closing the window and save settings."""
self._saveSettings()
event.accept()
self.softDelete()
return
##
# Private Slots
@@ -199,28 +199,24 @@ class GuiWelcome(NDialog):
self.mainStack.setCurrentWidget(self.tabNew)
self._setButtonVisibility()
self.tabNew.enterForm()
return
@pyqtSlot()
def _showOpenProjectPage(self) -> None:
"""Show the open exiting project page."""
self.mainStack.setCurrentWidget(self.tabOpen)
self._setButtonVisibility()
return
@pyqtSlot()
def _browseForProject(self) -> None:
"""Browse for a project to open."""
if path := SHARED.getProjectPath(self, path=CONFIG.homePath(), allowZip=False):
self._openProjectPath(path)
return
@pyqtSlot()
def _openSelectedItem(self) -> None:
"""Open the currently selected project item."""
if self.mainStack.currentWidget() == self.tabOpen:
self.tabOpen.openSelectedItem()
return
@pyqtSlot(Path)
def _openProjectPath(self, path: Path) -> None:
@@ -231,7 +227,6 @@ class GuiWelcome(NDialog):
self.hide()
self.openProjectRequest.emit(path)
self.close()
return
##
# Internal Functions
@@ -241,7 +236,6 @@ class GuiWelcome(NDialog):
"""Save the user GUI settings."""
logger.debug("Saving State: GuiWelcome")
CONFIG.setWelcomeWinSize(self.width(), self.height())
return
def _setButtonVisibility(self) -> None:
"""Change the visibility of the dialog buttons."""
@@ -255,7 +249,6 @@ class GuiWelcome(NDialog):
self.btnOpen.setFocus()
else:
self.btnCreate.setFocus()
return
class _OpenProjectPage(QWidget):
@@ -308,8 +301,6 @@ class _OpenProjectPage(QWidget):
f"QLineEdit {{border: none; background: {baseCol}; padding: 4px;}} "
)
return
##
# Public Slots
##
@@ -319,7 +310,6 @@ class _OpenProjectPage(QWidget):
"""Open the currently selected project item."""
if (selection := self.listWidget.selectedIndexes()) and (index := selection[0]).isValid():
self.openProjectRequest.emit(Path(str(index.data()[1])))
return
##
# Private Slots
@@ -335,14 +325,12 @@ class _OpenProjectPage(QWidget):
self.selectedPath.setToolTip(text)
self.selectedPath.setCursorPosition(0)
self.aMissing.setVisible(not (Path(value) / nwFiles.PROJ_FILE).is_file())
return
@pyqtSlot(QModelIndex)
def _projectDoubleClicked(self, index: QModelIndex) -> None:
"""Process double click on project item."""
if index.isValid():
self.openProjectRequest.emit(Path(str(index.data()[1])))
return
@pyqtSlot()
def _deleteSelectedItem(self) -> None:
@@ -355,7 +343,6 @@ class _OpenProjectPage(QWidget):
if SHARED.question(text):
self.listModel.removeEntry(index)
self._selectFirstItem()
return
@pyqtSlot("QPoint")
def _openContextMenu(self, pos: QPoint) -> None:
@@ -368,7 +355,6 @@ class _OpenProjectPage(QWidget):
action.triggered.connect(self._deleteSelectedItem)
ctxMenu.exec(self.mapToGlobal(pos))
ctxMenu.setParent(None)
return
##
# Internal Functions
@@ -379,7 +365,6 @@ class _OpenProjectPage(QWidget):
index = self.listModel.index(0)
self.listWidget.setCurrentIndex(index)
self._projectClicked(index)
return
class _ProjectListItem(QStyledItemDelegate):
@@ -407,8 +392,6 @@ class _ProjectListItem(QStyledItemDelegate):
self._icon = SHARED.theme.getPixmap("proj_nwx", (iPx, iPx))
return
def paint(self, painter: QPainter, opt: QStyleOptionViewItem, index: QModelIndex) -> None:
"""Paint a project entry on the canvas."""
rect = opt.rect
@@ -430,8 +413,6 @@ class _ProjectListItem(QStyledItemDelegate):
painter.drawText(rect.adjusted(x, y, 0, 0), tFlag, details)
painter.restore()
return
def sizeHint(self, opt: QStyleOptionViewItem, index: QModelIndex) -> QSize:
"""Set the size hint to fixed height."""
return QSize(opt.rect.width(), self._hPx)
@@ -449,7 +430,6 @@ class _ProjectListModel(QAbstractListModel):
when = CONFIG.localDate(datetime.fromtimestamp(time))
data.append((title, path, f"{opened}: {when}, {words}: {formatInt(count)}"))
self._data = data
return
def rowCount(self, parent: QModelIndex | None = None) -> int:
"""Return the size of the model."""
@@ -516,8 +496,6 @@ class _NewProjectPage(QWidget):
f"_NewProjectForm {{border: none; background: {baseCol};}} "
)
return
##
# Public Slots
##
@@ -689,13 +667,10 @@ class _NewProjectForm(QWidget):
self._updateProjPath()
self._updateFillInfo()
return
def enterForm(self) -> None:
"""Focus the project name field when entering the form."""
self.projName.setFocus()
self.projName.selectAll()
return
def getProjectData(self) -> dict:
"""Collect form data and return it as a dictionary."""
@@ -733,14 +708,12 @@ class _NewProjectForm(QWidget):
self._basePath = Path(path)
self._updateProjPath()
CONFIG.setLastPath("project", path)
return
@pyqtSlot()
def _updateProjPath(self) -> None:
"""Update the path box to show the full project path."""
projName = makeFileNameSafe(self.projName.text().strip())
self.projPath.setText(str(self._basePath / projName))
return
@pyqtSlot()
def _syncSwitches(self) -> None:
@@ -750,21 +723,18 @@ class _NewProjectForm(QWidget):
addWorld = self.addWorld.isChecked()
if not (addPlot or addChar or addWorld):
self.addNotes.setChecked(False)
return
@pyqtSlot()
def _setFillBlank(self) -> None:
"""Set fill mode to blank project."""
self._fillMode = self.FILL_BLANK
self._updateFillInfo()
return
@pyqtSlot()
def _setFillSample(self) -> None:
"""Set fill mode to sample project."""
self._fillMode = self.FILL_SAMPLE
self._updateFillInfo()
return
@pyqtSlot()
def _setFillCopy(self) -> None:
@@ -773,7 +743,6 @@ class _NewProjectForm(QWidget):
self._fillMode = self.FILL_COPY
self._copyPath = copyPath
self._updateFillInfo()
return
##
# Internal Functions
@@ -793,5 +762,3 @@ class _NewProjectForm(QWidget):
self.projFill.setToolTip(text)
self.projFill.setCursorPosition(0)
self.extraWidget.setVisible(self._fillMode == self.FILL_BLANK)
return
+2 -13
View File
@@ -20,7 +20,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import json
@@ -54,7 +54,7 @@ logger = logging.getLogger(__name__)
class GuiWritingStats(NToolDialog):
"""GUI Tools: Writing Statistics
"""GUI Tools: Writing Statistics.
Displays data from the NWSessionLog object.
"""
@@ -311,11 +311,8 @@ class GuiWritingStats(NToolDialog):
logger.debug("Ready: GuiWritingStats")
return
def __del__(self) -> None: # pragma: no cover
logger.debug("Delete: GuiWritingStats")
return
def populateGUI(self) -> None:
"""Populate list box with data from the log file."""
@@ -323,7 +320,6 @@ class GuiWritingStats(NToolDialog):
self._loadLogFile()
self._updateListBox()
QApplication.restoreOverrideCursor()
return
##
# Events
@@ -333,7 +329,6 @@ class GuiWritingStats(NToolDialog):
"""Capture the user closing the window."""
event.accept()
self.softDelete()
return
##
# Private Slots
@@ -377,8 +372,6 @@ class GuiWritingStats(NToolDialog):
self.close()
return
def _saveData(self, dataFmt: int) -> bool:
"""Save the content of the list box to a file."""
fileExt = ""
@@ -498,8 +491,6 @@ class GuiWritingStats(NToolDialog):
self.notesWords.setText(f"{ttNotes:n}")
self.totalWords.setText(f"{ttWords:n}")
return
##
# Private Slots
##
@@ -622,5 +613,3 @@ class GuiWritingStats(NToolDialog):
self.timeFilter += sDiff
self.labelFilter.setText(formatTime(round(self.timeFilter)))
return