Clean up variables and formatting

This commit is contained in:
Veronica Berglyd Olsen
2024-01-28 00:28:01 +01:00
parent 97b791511f
commit 8e4e6903b1
41 changed files with 1241 additions and 1248 deletions
+16 -16
View File
@@ -213,17 +213,17 @@ def formatInt(value: int) -> str:
if not isinstance(value, int):
return "ERR"
theVal = float(value)
if theVal > 1000.0:
fVal = float(value)
if fVal > 1000.0:
for pF in ["k", "M", "G", "T", "P", "E"]:
theVal /= 1000.0
if theVal < 1000.0:
if theVal < 10.0:
return f"{theVal:4.2f}{nwUnicode.U_THSP}{pF}"
elif theVal < 100.0:
return f"{theVal:4.1f}{nwUnicode.U_THSP}{pF}"
fVal /= 1000.0
if fVal < 1000.0:
if fVal < 10.0:
return f"{fVal:4.2f}{nwUnicode.U_THSP}{pF}"
elif fVal < 100.0:
return f"{fVal:4.1f}{nwUnicode.U_THSP}{pF}"
else:
return f"{theVal:3.0f}{nwUnicode.U_THSP}{pF}"
return f"{fVal:3.0f}{nwUnicode.U_THSP}{pF}"
return str(value)
@@ -275,22 +275,22 @@ def transferCase(source: str, target: str) -> str:
"""Transfers the case of the source word to the target word. This
will consider all upper or lower, and first char capitalisation.
"""
theResult = target
result = target
if not isinstance(source, str) or not isinstance(target, str):
return theResult
return result
if len(target) < 1 or len(source) < 1:
return theResult
return result
if source.istitle():
theResult = target.title()
result = target.title()
if source.isupper():
theResult = target.upper()
result = target.upper()
elif source.islower():
theResult = target.lower()
result = target.lower()
return theResult
return result
def fuzzyTime(seconds: int) -> str:
+2 -6
View File
@@ -235,16 +235,12 @@ class BuildSettings:
def getInt(self, key: str) -> int:
"""Type safe value access for integers."""
value = self._settings.get(key, SETTINGS_TEMPLATE.get(key, (None, None))[1])
if isinstance(value, (int, float)):
return int(value)
return 0
return int(value) if isinstance(value, (int, float)) else 0
def getFloat(self, key: str) -> float:
"""Type safe value access for floats."""
value = self._settings.get(key, SETTINGS_TEMPLATE.get(key, (None, None))[1])
if isinstance(value, (int, float)):
return float(value)
return 0.0
return float(value) if isinstance(value, (int, float)) else 0.0
##
# Setters
+19 -22
View File
@@ -279,28 +279,25 @@ class DocDuplicator:
"""Run through a list of items, duplicate them, and copy the
text content if they are documents.
"""
if not items:
return
nHandle = items[0]
hMap: dict[str, str | None] = {t: None for t in items}
for tHandle in items:
newItem = self._project.tree.duplicate(tHandle)
if newItem is None:
return
hMap[tHandle] = newItem.itemHandle
if newItem.itemParent in hMap:
newItem.setParent(hMap[newItem.itemParent])
self._project.tree.updateItemData(newItem.itemHandle)
if newItem.isFileType():
oldDoc = self._project.storage.getDocument(tHandle)
newDoc = self._project.storage.getDocument(newItem.itemHandle)
if newDoc.fileExists():
if items:
nHandle = items[0]
hMap: dict[str, str | None] = {t: None for t in items}
for tHandle in items:
newItem = self._project.tree.duplicate(tHandle)
if newItem is None:
return
newDoc.writeDocument(oldDoc.readDocument() or "")
yield newItem.itemHandle, nHandle
nHandle = None
hMap[tHandle] = newItem.itemHandle
if newItem.itemParent in hMap:
newItem.setParent(hMap[newItem.itemParent])
self._project.tree.updateItemData(newItem.itemHandle)
if newItem.isFileType():
oldDoc = self._project.storage.getDocument(tHandle)
newDoc = self._project.storage.getDocument(newItem.itemHandle)
if newDoc.fileExists():
return
newDoc.writeDocument(oldDoc.readDocument() or "")
yield newItem.itemHandle, nHandle
nHandle = None
return
# END Class DocDuplicator
@@ -313,7 +310,7 @@ class ProjectBuilder:
def __init__(self) -> None:
self._path = None
self.tr = partial(QCoreApplication.translate, "NWProject")
self.tr = partial(QCoreApplication.translate, "ProjectBuilder")
return
@property
+2 -2
View File
@@ -248,8 +248,8 @@ class NWBuildDocument:
def _setupBuild(self, bldObj: Tokenizer) -> dict:
"""Configure the build object."""
# Get Settings
textFont = self._build.getStr("format.textFont")
textSize = self._build.getInt("format.textSize")
textFont = self._build.getStr("format.textFont")
textSize = self._build.getInt("format.textSize")
fontFamily = textFont or CONFIG.textFont
bldFont = QFont(fontFamily, textSize)
+6 -6
View File
@@ -52,7 +52,7 @@ class NWDocument:
def __init__(self, project: NWProject, tHandle: str | None) -> None:
self._project = project
self._project = project
self._item = None # The currently open item
self._handle = None # The handle of the currently open item
@@ -284,12 +284,12 @@ class NWDocument:
"""Parse the document meta tag and return the name, parent,
class and layout meta values.
"""
theName = self._docMeta.get("name", "")
theParent = self._docMeta.get("parent", None)
theClass = self._docMeta.get("class", None)
theLayout = self._docMeta.get("layout", None)
name = self._docMeta.get("name", "")
parent = self._docMeta.get("parent", None)
itemClass = self._docMeta.get("class", None)
itemLayout = self._docMeta.get("layout", None)
return theName, theParent, theClass, theLayout
return name, parent, itemClass, itemLayout
def getError(self) -> str:
"""Return the last recorded exception."""
+4 -4
View File
@@ -122,8 +122,8 @@ class NWIndex:
for nwItem in self._project.tree:
if nwItem.isFileType():
tHandle = nwItem.itemHandle
theDoc = self._project.storage.getDocument(tHandle)
self.scanText(tHandle, theDoc.readDocument() or "", blockSignal=True)
doc = self._project.storage.getDocument(tHandle)
self.scanText(tHandle, doc.readDocument() or "", blockSignal=True)
self._indexBroken = False
SHARED.indexSignalProxy({"event": "buildIndex"})
return
@@ -148,8 +148,8 @@ class NWIndex:
"""
if tHandle and self._project.tree.checkType(tHandle, nwItemType.FILE):
logger.debug("Re-indexing item '%s'", tHandle)
theDoc = self._project.storage.getDocument(tHandle)
self.scanText(tHandle, theDoc.readDocument() or "")
doc = self._project.storage.getDocument(tHandle)
self.scanText(tHandle, doc.readDocument() or "")
return True
return False
+4 -4
View File
@@ -194,12 +194,12 @@ class Tokenizer(ABC):
##
@property
def theResult(self) -> str:
def result(self) -> str:
"""The result of the build process."""
return self._result
@property
def theMarkdown(self) -> list:
def allMarkdown(self) -> list:
"""The combined novelWriter Markdown text."""
return self._allMarkdown
@@ -358,8 +358,8 @@ class Tokenizer(ABC):
return True
def setText(self, tHandle: str, text: str | None = None) -> bool:
"""Set the text for the tokenizer from a handle. If theText is
not set, load it from the file.
"""Set the text for the tokenizer from a handle. If text is not
set, load it from the file.
"""
self._nwItem = self._project.tree[tHandle]
if self._nwItem is None:
+4 -4
View File
@@ -682,12 +682,12 @@ class ToOdt(Tokenizer):
return parName
oStyle.setParentStyleName(parName)
theID = oStyle.getID()
if theID in self._autoPara:
return self._autoPara[theID][0]
pID = oStyle.getID()
if pID in self._autoPara:
return self._autoPara[pID][0]
newName = "P%d" % (len(self._autoPara) + 1)
self._autoPara[theID] = (newName, oStyle)
self._autoPara[pID] = (newName, oStyle)
return newName
+1 -1
View File
@@ -500,7 +500,7 @@ class NWTree:
##
def _setTreeChanged(self, state: bool) -> None:
"""Set the changed flag to theState, and if being set to True,
"""Set the changed flag to state, and if being set to True,
propagate that state change to the parent NWProject class.
"""
self._changed = state
+3 -3
View File
@@ -77,9 +77,9 @@ class GuiQuoteSelect(QDialog):
minSize = 100
for sKey, sLabel in nwQuotes.SYMBOLS.items():
theText = "[ %s ] %s" % (sKey, trConst(sLabel))
minSize = max(minSize, qMetrics.boundingRect(theText).width())
qtItem = QListWidgetItem(theText)
text = "[ %s ] %s" % (sKey, trConst(sLabel))
minSize = max(minSize, qMetrics.boundingRect(text).width())
qtItem = QListWidgetItem(text)
qtItem.setData(self.D_KEY, sKey)
self.listBox.addItem(qtItem)
if sKey == current:
+3 -3
View File
@@ -256,9 +256,9 @@ class GuiDocHighlighter(QSyntaxHighlighter):
nBlocks = qDoc.blockCount()
tStart = time()
for i in range(nBlocks):
theBlock = qDoc.findBlockByNumber(i)
if theBlock.userState() & cType > 0:
self.rehighlightBlock(theBlock)
block = qDoc.findBlockByNumber(i)
if block.userState() & cType > 0:
self.rehighlightBlock(block)
logger.debug("Document highlighted in %.3f ms" % (1000*(time() - tStart)))
return
+4 -4
View File
@@ -229,7 +229,7 @@ class GuiDocViewer(QTextBrowser):
self.setDocumentTitle(tHandle)
# Replace tabs before setting the HTML, and then put them back in
self.setHtml(aDoc.theResult.replace("\t", "!!tab!!"))
self.setHtml(aDoc.result.replace("\t", "!!tab!!"))
while self.find("!!tab!!"):
self.textCursor().insertText("\t")
@@ -367,9 +367,9 @@ class GuiDocViewer(QTextBrowser):
link = url.url()
logger.debug("Clicked link: '%s'", link)
if len(link) > 0:
theBits = link.split("=")
if len(theBits) == 2:
self.loadDocumentTagRequest.emit(theBits[1], nwDocMode.VIEW)
bits = link.split("=")
if len(bits) == 2:
self.loadDocumentTagRequest.emit(bits[1], nwDocMode.VIEW)
return
@pyqtSlot("QPoint")
+7 -7
View File
@@ -239,9 +239,9 @@ class GuiItemDetails(QWidget):
# Label
# =====
theLabel = nwItem.itemName
if len(theLabel) > 100:
theLabel = theLabel[:96].rstrip()+" ..."
label = nwItem.itemName
if len(label) > 100:
label = label[:96].rstrip()+" ..."
if nwItem.isFileType():
if nwItem.isActive:
@@ -251,14 +251,14 @@ class GuiItemDetails(QWidget):
else:
self.labelIcon.setPixmap(SHARED.theme.getPixmap("noncheckable", (iPx, iPx)))
self.labelData.setText(theLabel)
self.labelData.setText(label)
# Status
# ======
theStatus, theIcon = nwItem.getImportStatus(incIcon=True)
self.statusIcon.setPixmap(theIcon.pixmap(iPx, iPx))
self.statusData.setText(theStatus)
status, icon = nwItem.getImportStatus(incIcon=True)
self.statusIcon.setPixmap(icon.pixmap(iPx, iPx))
self.statusData.setText(status)
# Class
# =====
+4 -4
View File
@@ -726,17 +726,17 @@ class GuiNovelTree(QTreeWidget):
refData = []
refName = ""
theRefs = SHARED.project.index.getReferences(tHandle, sTitle)
refs = SHARED.project.index.getReferences(tHandle, sTitle)
if self._lastCol == NovelTreeColumn.POV:
refData = theRefs[nwKeyWords.POV_KEY]
refData = refs[nwKeyWords.POV_KEY]
refName = self._povLabel
elif self._lastCol == NovelTreeColumn.FOCUS:
refData = theRefs[nwKeyWords.FOCUS_KEY]
refData = refs[nwKeyWords.FOCUS_KEY]
refName = self._focLabel
elif self._lastCol == NovelTreeColumn.PLOT:
refData = theRefs[nwKeyWords.PLOT_KEY]
refData = refs[nwKeyWords.PLOT_KEY]
refName = self._pltLabel
if refData:
+13 -13
View File
@@ -625,12 +625,12 @@ class GuiOutlineTree(QTreeWidget):
self.clear()
if self._firstView:
theLabels = []
labels = []
for i, hItem in enumerate(self._treeOrder):
theLabels.append(trConst(nwLabels.OUTLINE_COLS[hItem]))
labels.append(trConst(nwLabels.OUTLINE_COLS[hItem]))
self._colIdx[hItem] = i
self.setHeaderLabels(theLabels)
self.setHeaderLabels(labels)
for hItem in self._treeOrder:
self.setColumnWidth(self._colIdx[hItem], self._colWidth[hItem])
self.setColumnHidden(self._colIdx[hItem], self._colHidden[hItem])
@@ -990,7 +990,7 @@ class GuiOutlineDetails(QScrollArea):
pIndex = SHARED.project.index
nwItem = SHARED.project.tree[tHandle]
novIdx = pIndex.getItemHeader(tHandle, sTitle)
theRefs = pIndex.getReferences(tHandle, sTitle)
novRefs = pIndex.getReferences(tHandle, sTitle)
if nwItem is None or novIdx is None:
return False
@@ -1015,15 +1015,15 @@ class GuiOutlineDetails(QScrollArea):
self.synopValue.setText(novIdx.synopsis)
self.povKeyValue.setText(self._formatTags(theRefs, nwKeyWords.POV_KEY))
self.focKeyValue.setText(self._formatTags(theRefs, nwKeyWords.FOCUS_KEY))
self.chrKeyValue.setText(self._formatTags(theRefs, nwKeyWords.CHAR_KEY))
self.pltKeyValue.setText(self._formatTags(theRefs, nwKeyWords.PLOT_KEY))
self.timKeyValue.setText(self._formatTags(theRefs, nwKeyWords.TIME_KEY))
self.wldKeyValue.setText(self._formatTags(theRefs, nwKeyWords.WORLD_KEY))
self.objKeyValue.setText(self._formatTags(theRefs, nwKeyWords.OBJECT_KEY))
self.entKeyValue.setText(self._formatTags(theRefs, nwKeyWords.ENTITY_KEY))
self.cstKeyValue.setText(self._formatTags(theRefs, nwKeyWords.CUSTOM_KEY))
self.povKeyValue.setText(self._formatTags(novRefs, nwKeyWords.POV_KEY))
self.focKeyValue.setText(self._formatTags(novRefs, nwKeyWords.FOCUS_KEY))
self.chrKeyValue.setText(self._formatTags(novRefs, nwKeyWords.CHAR_KEY))
self.pltKeyValue.setText(self._formatTags(novRefs, nwKeyWords.PLOT_KEY))
self.timKeyValue.setText(self._formatTags(novRefs, nwKeyWords.TIME_KEY))
self.wldKeyValue.setText(self._formatTags(novRefs, nwKeyWords.WORLD_KEY))
self.objKeyValue.setText(self._formatTags(novRefs, nwKeyWords.OBJECT_KEY))
self.entKeyValue.setText(self._formatTags(novRefs, nwKeyWords.ENTITY_KEY))
self.cstKeyValue.setText(self._formatTags(novRefs, nwKeyWords.CUSTOM_KEY))
return True
+12 -12
View File
@@ -785,24 +785,24 @@ class GuiProjectTree(QTreeWidget):
project structure, and must be called before any code that
depends on this order to be up to date.
"""
theList = []
items = []
for i in range(self.topLevelItemCount()):
item = self.topLevelItem(i)
if isinstance(item, QTreeWidgetItem):
theList = self._scanChildren(theList, item, i)
items = self._scanChildren(items, item, i)
logger.debug("Saving project tree item order")
SHARED.project.setTreeOrder(theList)
SHARED.project.setTreeOrder(items)
return
def getTreeFromHandle(self, tHandle: str) -> list[str]:
"""Recursively return all the child items starting from a given
item handle.
"""
theList = []
theItem = self._getTreeItem(tHandle)
if theItem is not None:
theList = self._scanChildren(theList, theItem, 0)
return theList
result = []
tIten = self._getTreeItem(tHandle)
if tIten is not None:
result = self._scanChildren(result, tIten, 0)
return result
def requestDeleteItem(self, tHandle: str | None = None) -> bool:
"""Request an item deleted from the project tree. This function
@@ -857,11 +857,11 @@ class GuiProjectTree(QTreeWidget):
SHARED.info(self.tr("There is currently no Trash folder in this project."))
return False
theTrash = self.getTreeFromHandle(trashHandle)
if trashHandle in theTrash:
theTrash.remove(trashHandle)
trashItems = self.getTreeFromHandle(trashHandle)
if trashHandle in trashItems:
trashItems.remove(trashHandle)
nTrash = len(theTrash)
nTrash = len(trashItems)
if nTrash == 0:
SHARED.info(self.tr("The Trash folder is already empty."))
return False
+9 -9
View File
@@ -368,22 +368,22 @@ class GuiTheme:
def _setGuiFont(self) -> None:
"""Update the GUI's font style from settings."""
theFont = QFont()
font = QFont()
fontDB = QFontDatabase()
if CONFIG.guiFont not in fontDB.families():
if CONFIG.osWindows and "Arial" in fontDB.families():
# On Windows we default to Arial if possible
theFont.setFamily("Arial")
theFont.setPointSize(10)
font.setFamily("Arial")
font.setPointSize(10)
else:
theFont = fontDB.systemFont(QFontDatabase.GeneralFont)
CONFIG.guiFont = theFont.family()
CONFIG.guiFontSize = theFont.pointSize()
font = fontDB.systemFont(QFontDatabase.GeneralFont)
CONFIG.guiFont = font.family()
CONFIG.guiFontSize = font.pointSize()
else:
theFont.setFamily(CONFIG.guiFont)
theFont.setPointSize(CONFIG.guiFontSize)
font.setFamily(CONFIG.guiFont)
font.setPointSize(CONFIG.guiFontSize)
qApp.setFont(theFont)
qApp.setFont(font)
return
+3 -3
View File
@@ -679,10 +679,10 @@ class GuiMain(QMainWindow):
if loadFile.strip() == "":
return False
theText = None
text = None
try:
with open(loadFile, mode="rt", encoding="utf-8") as inFile:
theText = inFile.read()
text = inFile.read()
CONFIG.setLastPath(loadFile)
except Exception as exc:
SHARED.error(self.tr(
@@ -704,7 +704,7 @@ class GuiMain(QMainWindow):
if not msgYes:
return False
self.docEditor.replaceText(theText)
self.docEditor.replaceText(text)
return True
+5 -5
View File
@@ -375,9 +375,9 @@ class GuiManuscript(QDialog):
@pyqtSlot()
def _printDocument(self) -> None:
"""Open the print preview dialog."""
thePreview = QPrintPreviewDialog(self)
thePreview.paintRequested.connect(self.docPreview.printPreview)
thePreview.exec_()
preview = QPrintPreviewDialog(self)
preview.paintRequested.connect(self.docPreview.printPreview)
preview.exec_()
return
##
@@ -771,8 +771,8 @@ class _PreviewWidget(QTextBrowser):
self.setHtml(html)
qApp.processEvents()
while self.find("!!tab!!"):
theCursor = self.textCursor()
theCursor.insertText("\t")
cursor = self.textCursor()
cursor.insertText("\t")
self.verticalScrollBar().setValue(sPos)
self._docTime = checkInt(data.get("time"), 0)
+4 -4
View File
@@ -1112,10 +1112,10 @@ class _FormatTab(NScrollableForm):
currFont = QFont()
currFont.setFamily(self.textFont.text())
currFont.setPointSize(self.textSize.value())
theFont, theStatus = QFontDialog.getFont(currFont, self)
if theStatus:
self.textFont.setText(theFont.family())
self.textSize.setValue(theFont.pointSize())
newFont, status = QFontDialog.getFont(currFont, self)
if status:
self.textFont.setText(newFont.family())
self.textSize.setValue(newFont.pointSize())
return
@pyqtSlot(int)
+3 -3
View File
@@ -455,19 +455,19 @@ class _ContentsPage(NFixedPage):
pTotal = 0
tPages = 1
theList = []
entries = []
for _, tLevel, tTitle, wCount in self._data:
pCount = math.ceil(wCount/wpPage)
if dblPages:
pCount += pCount%2
pTotal += pCount
theList.append((tLevel, tTitle, wCount, pCount))
entries.append((tLevel, tTitle, wCount, pCount))
pMax = pTotal - fstPage
self.tocTree.clear()
for tLevel, tTitle, wCount, pCount in theList:
for tLevel, tTitle, wCount, pCount in entries:
newItem = QTreeWidgetItem()
if tPages <= fstPage:
+2 -2
View File
@@ -585,13 +585,13 @@ class GuiWritingStats(QDialog):
newItem.setText(self.C_COUNT, f"{nWords:n}")
if nWords > 0 and listMax > 0:
theBar = self.barImage.scaled(
wBar = self.barImage.scaled(
int(200*min(nWords, histMax)/listMax),
self.barHeight,
Qt.IgnoreAspectRatio,
Qt.FastTransformation
)
newItem.setData(self.C_BAR, Qt.DecorationRole, theBar)
newItem.setData(self.C_BAR, Qt.DecorationRole, wBar)
newItem.setTextAlignment(self.C_LENGTH, Qt.AlignRight)
newItem.setTextAlignment(self.C_IDLE, Qt.AlignRight)