Further PEP8 compliance changes

This commit is contained in:
Veronica K. B. Olsen
2019-11-03 18:02:47 +01:00
parent 7c95af951a
commit b303eb6539
37 changed files with 408 additions and 380 deletions
+14 -8
View File
@@ -17,16 +17,20 @@ logger = logging.getLogger(__name__)
def checkString(checkValue, defaultValue, allowNone=False): def checkString(checkValue, defaultValue, allowNone=False):
if allowNone: if allowNone:
if checkValue == None: return None if checkValue == None:
if checkValue == "None": return None return None
if checkValue == "None":
return None
if isinstance(checkValue,str): if isinstance(checkValue,str):
return str(checkValue) return str(checkValue)
return defaultValue return defaultValue
def checkInt(checkValue, defaultValue, allowNone=False): def checkInt(checkValue, defaultValue, allowNone=False):
if allowNone: if allowNone:
if checkValue == None: return None if checkValue == None:
if checkValue == "None": return None return None
if checkValue == "None":
return None
try: try:
return int(checkValue) return int(checkValue)
except: except:
@@ -34,8 +38,10 @@ def checkInt(checkValue, defaultValue, allowNone=False):
def checkBool(checkValue, defaultValue, allowNone=False): def checkBool(checkValue, defaultValue, allowNone=False):
if allowNone: if allowNone:
if checkValue == None: return None if checkValue == None:
if checkValue == "None": return None return None
if checkValue == "None":
return None
if isinstance(checkValue, str): if isinstance(checkValue, str):
if checkValue == "True": if checkValue == "True":
return True return True
@@ -92,8 +98,8 @@ def splitVersionNumber(vString):
vPatch = 0 vPatch = 0
vInt = 0 vInt = 0
vBits = vString.split(".") vBits = vString.split(".")
nBits = len(vBits) nBits = len(vBits)
if nBits > 0: if nBits > 0:
vMajor = checkInt(vBits[0],0) vMajor = checkInt(vBits[0],0)
+9 -9
View File
@@ -15,15 +15,15 @@ import configparser
import sys import sys
import nw import nw
from os import path, mkdir, makedirs, getcwd from os import path, mkdir, makedirs, getcwd
from appdirs import user_config_dir from appdirs import user_config_dir
from datetime import datetime from datetime import datetime
from PyQt5.Qt import PYQT_VERSION_STR
from PyQt5.QtCore import QT_VERSION_STR
from nw.constants import nwFiles, nwUnicode from nw.constants import nwFiles, nwUnicode
from nw.common import splitVersionNumber from nw.common import splitVersionNumber
from PyQt5.Qt import PYQT_VERSION_STR
from PyQt5.QtCore import QT_VERSION_STR
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -59,8 +59,8 @@ class Config:
self.confChanged = False self.confChanged = False
## General ## General
self.guiTheme = "default" self.guiTheme = "default"
self.guiSyntax = "default_light" self.guiSyntax = "default_light"
## Sizes ## Sizes
self.winGeometry = [1100, 650] self.winGeometry = [1100, 650]
+3 -4
View File
@@ -13,12 +13,13 @@
import logging import logging
import nw import nw
from os import path from os import path
from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QMessageBox
from nw.convert.file.text import TextFile from nw.convert.file.text import TextFile
from nw.convert.tokenizer import Tokenizer from nw.convert.tokenizer import Tokenizer
from nw.enum import nwAlert, nwItemLayout from nw.enum import nwAlert, nwItemLayout
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -26,9 +27,7 @@ class ConcatFile(TextFile):
def __init__(self, theProject, theParent): def __init__(self, theProject, theParent):
TextFile.__init__(self, theProject, theParent) TextFile.__init__(self, theProject, theParent)
self.theConv = Tokenizer(self.theProject, self.theParent) self.theConv = Tokenizer(self.theProject, self.theParent)
return return
def addText(self, tHandle): def addText(self, tHandle):
+2 -4
View File
@@ -13,9 +13,9 @@
import logging import logging
import nw import nw
from nw.convert.file.text import TextFile from nw.convert.file.text import TextFile
from nw.convert.text.tohtml import ToHtml from nw.convert.text.tohtml import ToHtml
from nw.enum import nwAlert from nw.enum import nwAlert
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -23,9 +23,7 @@ class HtmlFile(TextFile):
def __init__(self, theProject, theParent): def __init__(self, theProject, theParent):
TextFile.__init__(self, theProject, theParent) TextFile.__init__(self, theProject, theParent)
self.theConv = ToHtml(self.theProject, self.theParent) self.theConv = ToHtml(self.theProject, self.theParent)
return return
## ##
+2 -7
View File
@@ -13,9 +13,9 @@
import logging import logging
import nw import nw
from nw.convert.file.text import TextFile from nw.convert.file.text import TextFile
from nw.convert.text.tolatex import ToLaTeX from nw.convert.text.tolatex import ToLaTeX
from nw.enum import nwAlert from nw.enum import nwAlert
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -32,7 +32,6 @@ class LaTeXFile(TextFile):
## ##
def _doOpenFile(self, filePath): def _doOpenFile(self, filePath):
try: try:
self.outFile = open(filePath,mode="wt+",encoding="utf8") self.outFile = open(filePath,mode="wt+",encoding="utf8")
self.outFile.write("\\documentclass[12pt]{report}\n") self.outFile.write("\\documentclass[12pt]{report}\n")
@@ -43,17 +42,13 @@ class LaTeXFile(TextFile):
except Exception as e: except Exception as e:
self.makeAlert(["Failed to open file.",str(e)], nwAlert.ERROR) self.makeAlert(["Failed to open file.",str(e)], nwAlert.ERROR)
return False return False
return True return True
def _doCloseFile(self): def _doCloseFile(self):
if self.outFile is not None: if self.outFile is not None:
self.outFile.write("\\end{document}\n") self.outFile.write("\\end{document}\n")
self.outFile.close() self.outFile.close()
self.texCodecFail = self.theConv.texCodecFail self.texCodecFail = self.theConv.texCodecFail
return True return True
# END Class LaTeXFile # END Class LaTeXFile
+2 -4
View File
@@ -13,9 +13,9 @@
import logging import logging
import nw import nw
from nw.convert.file.text import TextFile from nw.convert.file.text import TextFile
from nw.convert.text.tomarkdown import ToMarkdown from nw.convert.text.tomarkdown import ToMarkdown
from nw.enum import nwAlert from nw.enum import nwAlert
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -23,9 +23,7 @@ class MarkdownFile(TextFile):
def __init__(self, theProject, theParent): def __init__(self, theProject, theParent):
TextFile.__init__(self, theProject, theParent) TextFile.__init__(self, theProject, theParent)
self.theConv = ToMarkdown(self.theProject, self.theParent) self.theConv = ToMarkdown(self.theProject, self.theParent)
return return
## ##
+10 -9
View File
@@ -13,11 +13,12 @@
import logging import logging
import nw import nw
from os import path from os import path
from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QMessageBox
from nw.convert.text.totext import ToText from nw.convert.text.totext import ToText
from nw.enum import nwAlert, nwItemType, nwItemLayout, nwItemClass from nw.enum import nwAlert, nwItemType, nwItemLayout, nwItemClass
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -29,14 +30,14 @@ class TextFile():
self.theProject = theProject self.theProject = theProject
self.theParent = theParent self.theParent = theParent
self.outFile = None self.outFile = None
self.fileName = "" self.fileName = ""
self.theText = "" self.theText = ""
self.expNovel = True self.expNovel = True
self.expNotes = False self.expNotes = False
self.theConv = ToText(self.theProject, self.theParent) self.theConv = ToText(self.theProject, self.theParent)
self.makeAlert = self.theParent.makeAlert self.makeAlert = self.theParent.makeAlert
self.setComments(False) self.setComments(False)
self.setKeywords(False) self.setKeywords(False)
+1 -3
View File
@@ -15,7 +15,7 @@ import re
import nw import nw
from nw.convert.tokenizer import Tokenizer from nw.convert.tokenizer import Tokenizer
from nw.constants import nwUnicode, nwLabels from nw.constants import nwUnicode, nwLabels
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -31,12 +31,10 @@ class ToHtml(Tokenizer):
need to make a few changes to formatting, which is selected by need to make a few changes to formatting, which is selected by
this flag. this flag.
""" """
self.forPreview = forPreview self.forPreview = forPreview
if forPreview: if forPreview:
self.doKeywords = True self.doKeywords = True
self.doComments = doComments self.doComments = doComments
return return
def doAutoReplace(self): def doAutoReplace(self):
+1 -1
View File
@@ -16,7 +16,7 @@ import re
import nw import nw
from nw.convert.tokenizer import Tokenizer from nw.convert.tokenizer import Tokenizer
from nw.constants import nwUnicode from nw.constants import nwUnicode
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+1 -1
View File
@@ -16,7 +16,7 @@ import re
import nw import nw
from nw.convert.tokenizer import Tokenizer from nw.convert.tokenizer import Tokenizer
from nw.constants import nwUnicode from nw.constants import nwUnicode
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+6 -5
View File
@@ -15,12 +15,12 @@ import logging
import re import re
import nw import nw
from operator import itemgetter from operator import itemgetter
from PyQt5.QtCore import QRegularExpression from PyQt5.QtCore import QRegularExpression
from nw.project.document import NWDoc from nw.project.document import NWDoc
from nw.tools.translate import numberToWord from nw.tools.translate import numberToWord
from nw.enum import nwItemLayout from nw.enum import nwItemLayout
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -230,7 +230,8 @@ class Tokenizer():
if isNone: return if isNone: return
if isNote: return if isNote: return
# For novel files, we need to handle chapter numbering and scene breaks # For novel files, we need to handle chapter numbering and scene
# breaks
if isBook or isUnNum or isChap or isScene: if isBook or isUnNum or isChap or isScene:
for n in range(len(self.theTokens)): for n in range(len(self.theTokens)):
+18 -10
View File
@@ -15,15 +15,15 @@ import nw
from os import path from os import path
from PyQt5.QtCore import Qt, QSize from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QIcon, QPixmap, QColor, QBrush, QStandardItemModel, QFont from PyQt5.QtGui import QIcon, QPixmap, QColor, QBrush, QStandardItemModel, QFont
from PyQt5.QtSvg import QSvgWidget from PyQt5.QtSvg import QSvgWidget
from PyQt5.QtWidgets import ( from PyQt5.QtWidgets import (
QDialog, QHBoxLayout, QVBoxLayout, QFormLayout, QLineEdit, QPlainTextEdit, QLabel, QDialog, QHBoxLayout, QVBoxLayout, QFormLayout, QLineEdit, QPlainTextEdit, QLabel,
QWidget, QTabWidget, QDialogButtonBox, QSpinBox, QGroupBox, QComboBox, QMessageBox, QWidget, QTabWidget, QDialogButtonBox, QSpinBox, QGroupBox, QComboBox, QMessageBox,
QCheckBox, QGridLayout, QFontComboBox, QPushButton, QFileDialog QCheckBox, QGridLayout, QFontComboBox, QPushButton, QFileDialog
) )
from nw.enum import nwAlert from nw.enum import nwAlert
from nw.constants import nwQuotes from nw.constants import nwQuotes
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -80,8 +80,8 @@ class GuiConfigEditor(QDialog):
logger.verbose("ConfigEditor save button clicked") logger.verbose("ConfigEditor save button clicked")
validEntries = True validEntries = True
needsRestart = False needsRestart = False
retA, retB = self.tabMain.saveValues() retA, retB = self.tabMain.saveValues()
validEntries &= retA validEntries &= retA
@@ -557,25 +557,33 @@ class GuiConfigEditEditor(QWidget):
if self._checkQuoteSymbol(fmtSingleQuotesO): if self._checkQuoteSymbol(fmtSingleQuotesO):
self.mainConf.fmtSingleQuotes[0] = fmtSingleQuotesO self.mainConf.fmtSingleQuotes[0] = fmtSingleQuotesO
else: else:
self.theParent.makeAlert("Invalid quote symbol: %s" % fmtSingleQuotesO, nwAlert.ERROR) self.theParent.makeAlert(
"Invalid quote symbol: %s" % fmtSingleQuotesO, nwAlert.ERROR
)
validEntries = False validEntries = False
if self._checkQuoteSymbol(fmtSingleQuotesC): if self._checkQuoteSymbol(fmtSingleQuotesC):
self.mainConf.fmtSingleQuotes[1] = fmtSingleQuotesC self.mainConf.fmtSingleQuotes[1] = fmtSingleQuotesC
else: else:
self.theParent.makeAlert("Invalid quote symbol: %s" % fmtSingleQuotesC, nwAlert.ERROR) self.theParent.makeAlert(
"Invalid quote symbol: %s" % fmtSingleQuotesC, nwAlert.ERROR
)
validEntries = False validEntries = False
if self._checkQuoteSymbol(fmtDoubleQuotesO): if self._checkQuoteSymbol(fmtDoubleQuotesO):
self.mainConf.fmtDoubleQuotes[0] = fmtDoubleQuotesO self.mainConf.fmtDoubleQuotes[0] = fmtDoubleQuotesO
else: else:
self.theParent.makeAlert("Invalid quote symbol: %s" % fmtDoubleQuotesO, nwAlert.ERROR) self.theParent.makeAlert(
"Invalid quote symbol: %s" % fmtDoubleQuotesO, nwAlert.ERROR
)
validEntries = False validEntries = False
if self._checkQuoteSymbol(fmtDoubleQuotesC): if self._checkQuoteSymbol(fmtDoubleQuotesC):
self.mainConf.fmtDoubleQuotes[1] = fmtDoubleQuotesC self.mainConf.fmtDoubleQuotes[1] = fmtDoubleQuotesC
else: else:
self.theParent.makeAlert("Invalid quote symbol: %s" % fmtDoubleQuotesC, nwAlert.ERROR) self.theParent.makeAlert(
"Invalid quote symbol: %s" % fmtDoubleQuotesC, nwAlert.ERROR
)
validEntries = False validEntries = False
showTabsNSpaces = self.showTabsNSpaces.isChecked() showTabsNSpaces = self.showTabsNSpaces.isChecked()
+36 -33
View File
@@ -16,24 +16,25 @@ import nw
from os import path from os import path
from PyQt5.QtCore import Qt, QSize from PyQt5.QtCore import Qt, QSize
from PyQt5.QtSvg import QSvgWidget from PyQt5.QtSvg import QSvgWidget
from PyQt5.QtWidgets import ( from PyQt5.QtWidgets import (
QDialog, QHBoxLayout, QVBoxLayout, QWidget, QTabWidget, QGridLayout, QGroupBox, QCheckBox, QDialog, QHBoxLayout, QVBoxLayout, QWidget, QTabWidget, QGridLayout,
QLabel, QComboBox, QLineEdit, QPushButton, QFileDialog, QProgressBar, QSpinBox, QMessageBox QGroupBox, QCheckBox, QLabel, QComboBox, QLineEdit, QPushButton,
QFileDialog, QProgressBar, QSpinBox, QMessageBox
) )
from nw.project.document import NWDoc from nw.project.document import NWDoc
from nw.tools.translate import numberToWord from nw.tools.translate import numberToWord
from nw.tools.optlaststate import OptLastState from nw.tools.optlaststate import OptLastState
from nw.convert.file.text import TextFile from nw.convert.file.text import TextFile
from nw.convert.file.html import HtmlFile from nw.convert.file.html import HtmlFile
from nw.convert.file.markdown import MarkdownFile from nw.convert.file.markdown import MarkdownFile
from nw.convert.file.latex import LaTeXFile from nw.convert.file.latex import LaTeXFile
from nw.convert.file.concat import ConcatFile from nw.convert.file.concat import ConcatFile
from nw.common import packageRefURL from nw.common import packageRefURL
from nw.constants import nwFiles from nw.constants import nwFiles
from nw.enum import nwItemType, nwAlert from nw.enum import nwItemType, nwAlert
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -201,9 +202,10 @@ class GuiExport(QDialog):
# Check that encoding was successful # Check that encoding was successful
if outFile.texCodecFail: if outFile.texCodecFail:
self.theParent.makeAlert(( self.theParent.makeAlert((
"Failed to escape unicode characters while writing LaTeX file. The generated " "Failed to escape unicode characters while writing LaTeX "
".tex file may not build properly. Make sure the python package '{package:s}' " "file. The generated .tex file may not build properly. "
"is installed and working." "Make sure the python package '{package:s}' is installed "
"and working."
).format( ).format(
package = packageRefURL("latexcodec") package = packageRefURL("latexcodec")
), nwAlert.WARN) ), nwAlert.WARN)
@@ -343,27 +345,31 @@ class GuiExportMain(QWidget):
} }
FMT_HELP = { FMT_HELP = {
FMT_NWD : ( FMT_NWD : (
"Exports a document using the novelWriter markdown format. The files selected by the " "Exports a document using the novelWriter markdown format. "
"filters are appended as-is, including comments and other settings." "The files selected by the filters are appended as-is, "
"including comments and other settings."
), ),
FMT_TXT : ( FMT_TXT : (
"Exports a plain text file. All formatting is stripped and comments are in square " "Exports a plain text file. All formatting is stripped and "
"brackets." "comments are in square brackets."
), ),
FMT_MD : ( FMT_MD : (
"Exports a standard markdown file. Comments are converted to preformatted text blocks." "Exports a standard markdown file. Comments are converted "
"to preformatted text blocks."
), ),
FMT_HTML : ( FMT_HTML : (
"Exports a plain html5 file. Comments are wrapped in blocks with a yellow background " "Exports a plain html5 file. Comments are wrapped in "
"colour." "blocks with a yellow background colour."
), ),
FMT_TEX : ( FMT_TEX : (
"Exports a LaTeX file that can be compiled to PDF using for instance PDFLaTeX. " "Exports a LaTeX file that can be compiled to PDF using "
"Comments are exported as LaTeX comments." "for instance PDFLaTeX. Comments are exported as LaTeX "
"comments."
), ),
FMT_PDOC : ( FMT_PDOC : (
"Exports first to markdown or html5. The file is then passed on to Pandoc for a " "Exports first to markdown or html5. The file is then "
"second stage. Use the Pandoc tab for settings up the conversion." "passed on to Pandoc for a second stage. Use the Pandoc "
"tab for settings up the conversion."
), ),
} }
@@ -566,7 +572,8 @@ class GuiExportMain(QWidget):
dlgOpt = QFileDialog.Options() dlgOpt = QFileDialog.Options()
dlgOpt |= QFileDialog.DontUseNativeDialog dlgOpt |= QFileDialog.DontUseNativeDialog
saveTo = QFileDialog.getSaveFileName( saveTo = QFileDialog.getSaveFileName(
self,"Export File",self.exportPath.text(),options=dlgOpt,filter=";;".join(extFilter) self, "Export File", self.exportPath.text(),
options=dlgOpt, filter=";;".join(extFilter)
) )
if saveTo: if saveTo:
self.exportPath.setText(saveTo[0]) self.exportPath.setText(saveTo[0])
@@ -658,7 +665,6 @@ class GuiExportPandoc(QWidget):
self.outputFormat.addItem("ePUB eBook v2 (.epub2)", self.FMT_EPUB2) self.outputFormat.addItem("ePUB eBook v2 (.epub2)", self.FMT_EPUB2)
self.outputFormat.addItem("ePUB eBook v3 (.epub3)", self.FMT_EPUB3) self.outputFormat.addItem("ePUB eBook v3 (.epub3)", self.FMT_EPUB3)
self.outputFormat.addItem("Zim Wiki (.txt)", self.FMT_ZIM) self.outputFormat.addItem("Zim Wiki (.txt)", self.FMT_ZIM)
# self.outputFormat.currentIndexChanged.connect(self._updateFormat)
optIdx = self.outputFormat.findData(self.optState.getSetting("pFormat")) optIdx = self.outputFormat.findData(self.optState.getSetting("pFormat"))
if optIdx == -1: if optIdx == -1:
@@ -674,9 +680,6 @@ class GuiExportPandoc(QWidget):
self.outerBox.addWidget(self.guiInfo, 0, 0) self.outerBox.addWidget(self.guiInfo, 0, 0)
self.outerBox.addWidget(self.guiOutput, 1, 0) self.outerBox.addWidget(self.guiOutput, 1, 0)
self.outerBox.setRowStretch(2, 1) self.outerBox.setRowStretch(2, 1)
# self.outerBox.setColumnStretch(0, 1)
# self.outerBox.setColumnStretch(1, 1)
# self.outerBox.setColumnStretch(2, 1)
self.setLayout(self.outerBox) self.setLayout(self.outerBox)
return return
+5 -4
View File
@@ -15,13 +15,14 @@ import nw
from os import path from os import path
from PyQt5.QtCore import Qt, QSize from PyQt5.QtCore import Qt, QSize
from PyQt5.QtSvg import QSvgWidget from PyQt5.QtSvg import QSvgWidget
from PyQt5.QtWidgets import ( from PyQt5.QtWidgets import (
QDialog, QHBoxLayout, QVBoxLayout, QGroupBox, QFormLayout, QLineEdit, QPushButton, QComboBox QDialog, QHBoxLayout, QVBoxLayout, QGroupBox, QFormLayout,
QLineEdit, QPushButton, QComboBox
) )
from nw.enum import nwItemLayout, nwItemClass, nwItemType from nw.enum import nwItemLayout, nwItemClass, nwItemType
from nw.constants import nwLabels from nw.constants import nwLabels
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+8 -7
View File
@@ -15,13 +15,14 @@ import nw
from os import path from os import path
from PyQt5.QtCore import Qt, QSize from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QIcon, QPixmap, QColor, QBrush, QStandardItemModel from PyQt5.QtGui import QIcon, QPixmap, QColor, QBrush, QStandardItemModel
from PyQt5.QtSvg import QSvgWidget from PyQt5.QtSvg import QSvgWidget
from PyQt5.QtWidgets import ( from PyQt5.QtWidgets import (
QDialog, QHBoxLayout, QVBoxLayout, QFormLayout, QLineEdit, QPlainTextEdit, QLabel, QDialog, QHBoxLayout, QVBoxLayout, QFormLayout, QLineEdit, QPlainTextEdit,
QWidget, QTabWidget, QDialogButtonBox, QListWidget, QListWidgetItem, QPushButton, QLabel, QWidget, QTabWidget, QDialogButtonBox, QListWidget,
QColorDialog, QAbstractItemView, QTreeWidget, QTreeWidgetItem, QCheckBox QListWidgetItem, QPushButton, QColorDialog, QAbstractItemView, QTreeWidget,
QTreeWidgetItem, QCheckBox
) )
from nw.enum import nwAlert from nw.enum import nwAlert
@@ -173,7 +174,7 @@ class GuiProjectEditStatus(QWidget):
for iName, iCol, nUse in self.theStatus: for iName, iCol, nUse in self.theStatus:
self._addItem(iName, iCol, iName, nUse) self._addItem(iName, iCol, iName, nUse)
self.editName = QLineEdit() self.editName = QLineEdit()
self.editName.setEnabled(False) self.editName.setEnabled(False)
self.newButton = QPushButton("New") self.newButton = QPushButton("New")
self.delButton = QPushButton("Delete") self.delButton = QPushButton("Delete")
+19 -17
View File
@@ -13,18 +13,20 @@
import logging import logging
import nw import nw
from os import path from os import path
from datetime import datetime from datetime import datetime
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon, QColor, QPixmap, QFont from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon, QColor, QPixmap, QFont
from PyQt5.QtWidgets import ( from PyQt5.QtWidgets import (
QDialog, QVBoxLayout, QHBoxLayout, QTreeWidget, QTreeWidgetItem, QDialogButtonBox, QHeaderView, QDialog, QVBoxLayout, QHBoxLayout, QTreeWidget, QTreeWidgetItem,
QGridLayout, QLabel, QGroupBox, QCheckBox QDialogButtonBox, QHeaderView, QGridLayout, QLabel, QGroupBox,
QCheckBox
) )
from nw.tools.optlaststate import OptLastState from nw.tools.optlaststate import OptLastState
from nw.constants import nwConst, nwFiles from nw.constants import nwConst, nwFiles
from nw.enum import nwAlert from nw.enum import nwAlert
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -44,8 +46,8 @@ class GuiSessionLogView(QDialog):
self.timeFilter = 0.0 self.timeFilter = 0.0
self.timeTotal = 0.0 self.timeTotal = 0.0
self.outerBox = QGridLayout() self.outerBox = QGridLayout()
self.bottomBox = QHBoxLayout() self.bottomBox = QHBoxLayout()
self.setWindowTitle("Session Log") self.setWindowTitle("Session Log")
self.setMinimumWidth(420) self.setMinimumWidth(420)
@@ -76,7 +78,7 @@ class GuiSessionLogView(QDialog):
self.monoFont = QFont("Monospace",10) self.monoFont = QFont("Monospace",10)
sortValid = (Qt.AscendingOrder, Qt.DescendingOrder) sortValid = (Qt.AscendingOrder, Qt.DescendingOrder)
sortCol = self.optState.validIntRange( sortCol = self.optState.validIntRange(
self.optState.getSetting("sortCol"), 0, 2, 0 self.optState.getSetting("sortCol"), 0, 2, 0
) )
sortOrder = self.optState.validIntTuple( sortOrder = self.optState.validIntTuple(
@@ -91,7 +93,7 @@ class GuiSessionLogView(QDialog):
self.infoBoxForm = QGridLayout(self) self.infoBoxForm = QGridLayout(self)
self.infoBox.setLayout(self.infoBoxForm) self.infoBox.setLayout(self.infoBoxForm)
self.labelTotal = QLabel(self._formatTime(0)) self.labelTotal = QLabel(self._formatTime(0))
self.labelTotal.setFont(self.monoFont) self.labelTotal.setFont(self.monoFont)
self.labelTotal.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.labelTotal.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
@@ -162,11 +164,11 @@ class GuiSessionLogView(QDialog):
inData = inLine.split() inData = inLine.split()
if len(inData) != 8: if len(inData) != 8:
continue continue
dStart = datetime.strptime("%s %s" % (inData[1],inData[2]),nwConst.tStampFmt) dStart = datetime.strptime("%s %s" % (inData[1],inData[2]),nwConst.tStampFmt)
dEnd = datetime.strptime("%s %s" % (inData[4],inData[5]),nwConst.tStampFmt) dEnd = datetime.strptime("%s %s" % (inData[4],inData[5]),nwConst.tStampFmt)
nWords = int(inData[7]) nWords = int(inData[7])
tDiff = dEnd - dStart tDiff = dEnd - dStart
sDiff = tDiff.total_seconds() sDiff = tDiff.total_seconds()
self.timeTotal += sDiff self.timeTotal += sDiff
if abs(nWords) > 0: if abs(nWords) > 0:
+7 -6
View File
@@ -15,16 +15,17 @@ import nw
from os import path from os import path
from PyQt5.QtCore import Qt from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon, QColor, QPixmap from PyQt5.QtGui import QIcon, QColor, QPixmap
from PyQt5.QtWidgets import ( from PyQt5.QtWidgets import (
QDialog, QVBoxLayout, QHBoxLayout, QTableWidget, QTableWidgetItem, QDialogButtonBox, QLabel, QDialog, QVBoxLayout, QHBoxLayout, QTableWidget, QTableWidgetItem,
QPushButton, QHeaderView, QGridLayout, QGroupBox, QCheckBox QDialogButtonBox, QLabel, QPushButton, QHeaderView, QGridLayout,
QGroupBox, QCheckBox
) )
from nw.tools.optlaststate import OptLastState from nw.tools.optlaststate import OptLastState
from nw.constants import nwFiles from nw.constants import nwFiles
from nw.enum import nwItemClass from nw.enum import nwItemClass
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+2 -2
View File
@@ -13,10 +13,10 @@
import logging import logging
import nw import nw
from PyQt5.QtGui import QFont from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QFrame, QGridLayout, QLabel from PyQt5.QtWidgets import QFrame, QGridLayout, QLabel
from nw.constants import nwLabels from nw.constants import nwLabels
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+19 -16
View File
@@ -15,18 +15,21 @@ import nw
from time import time from time import time
from PyQt5.QtCore import Qt, QTimer, QSizeF from PyQt5.QtCore import Qt, QTimer, QSizeF
from PyQt5.QtWidgets import qApp, QTextEdit, QAction, QMenu, QShortcut, QMessageBox from PyQt5.QtWidgets import (
from PyQt5.QtGui import ( qApp, QTextEdit, QAction, QMenu, QShortcut, QMessageBox
QTextCursor, QTextOption, QIcon, QKeySequence, QFont, QColor, QPalette, QTextDocument, )
from PyQt5.QtGui import (
QTextCursor, QTextOption, QIcon, QKeySequence, QFont, QColor,
QPalette, QTextDocument,
) )
from nw.project.document import NWDoc from nw.project.document import NWDoc
from nw.gui.tools.dochighlight import GuiDocHighlighter from nw.gui.tools.dochighlight import GuiDocHighlighter
from nw.gui.tools.wordcounter import WordCounter from nw.gui.tools.wordcounter import WordCounter
from nw.tools.spellcheck import NWSpellCheck from nw.tools.spellcheck import NWSpellCheck
from nw.constants import nwFiles, nwUnicode from nw.constants import nwFiles, nwUnicode
from nw.enum import nwDocAction, nwAlert from nw.enum import nwDocAction, nwAlert
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -85,20 +88,20 @@ class GuiDocEditor(QTextEdit):
QShortcut( QShortcut(
QKeySequence("Ctrl+."), QKeySequence("Ctrl+."),
self, self,
context = Qt.WidgetShortcut, context=Qt.WidgetShortcut,
activated = self._openSpellContext activated=self._openSpellContext
) )
QShortcut( QShortcut(
Qt.Key_Return | Qt.ControlModifier, Qt.Key_Return | Qt.ControlModifier,
self, self,
context = Qt.WidgetShortcut, context=Qt.WidgetShortcut,
activated = self._followTag activated=self._followTag
) )
QShortcut( QShortcut(
Qt.Key_Enter | Qt.ControlModifier, Qt.Key_Enter | Qt.ControlModifier,
self, self,
context = Qt.WidgetShortcut, context=Qt.WidgetShortcut,
activated = self._followTag activated=self._followTag
) )
# Set Up Word Count Thread and Timer # Set Up Word Count Thread and Timer
@@ -684,7 +687,7 @@ class GuiDocEditor(QTextEdit):
the document. Wraps back to the top if not found. the document. Wraps back to the top if not found.
""" """
searchFor = self.theParent.searchBar.getSearchText() searchFor = self.theParent.searchBar.getSearchText()
wasFound = self.find(searchFor) wasFound = self.find(searchFor)
if not wasFound: if not wasFound:
theCursor = self.textCursor() theCursor = self.textCursor()
theCursor.movePosition(QTextCursor.Start) theCursor.movePosition(QTextCursor.Start)
+7 -5
View File
@@ -13,13 +13,15 @@
import logging import logging
import nw import nw
from PyQt5.QtCore import Qt, QSize from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QIcon, QFont, QColor from PyQt5.QtGui import QIcon, QFont, QColor
from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QAbstractItemView, QApplication from PyQt5.QtWidgets import (
QTreeWidget, QTreeWidgetItem, QAbstractItemView, QApplication
)
from nw.project.item import NWItem from nw.project.item import NWItem
from nw.constants import nwLabels from nw.constants import nwLabels
from nw.enum import nwItemType, nwItemClass, nwItemLayout, nwAlert from nw.enum import nwItemType, nwItemClass, nwItemLayout, nwAlert
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+4 -4
View File
@@ -13,13 +13,13 @@
import logging import logging
import nw import nw
from PyQt5.QtCore import Qt from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QTextBrowser from PyQt5.QtWidgets import QTextBrowser
from PyQt5.QtGui import QTextOption, QFont, QPalette, QColor from PyQt5.QtGui import QTextOption, QFont, QPalette, QColor
from nw.convert.tokenizer import Tokenizer from nw.convert.tokenizer import Tokenizer
from nw.convert.text.tohtml import ToHtml from nw.convert.text.tohtml import ToHtml
from nw.enum import nwAlert, nwItemType from nw.enum import nwAlert, nwItemType
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+4 -3
View File
@@ -13,8 +13,8 @@
import logging import logging
import nw import nw
from PyQt5.QtCore import Qt from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPalette, QColor from PyQt5.QtGui import QPalette, QColor
from PyQt5.QtWidgets import QFrame, QHBoxLayout, QLabel, QPushButton from PyQt5.QtWidgets import QFrame, QHBoxLayout, QLabel, QPushButton
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -36,7 +36,8 @@ class GuiNoticeBar(QFrame):
self.mainBox = QHBoxLayout(self) self.mainBox = QHBoxLayout(self)
self.mainBox.setContentsMargins(8,2,2,2) self.mainBox.setContentsMargins(8,2,2,2)
self.noteLabel = QLabel("Hi there!") self.noteLabel = QLabel("Hi there!")
self.closeButton = QPushButton(self.theTheme.getIcon("close"),"") self.closeButton = QPushButton(self.theTheme.getIcon("close"),"")
self.closeButton.clicked.connect(self.hideNote) self.closeButton.clicked.connect(self.hideNote)
+5 -3
View File
@@ -13,9 +13,11 @@
import logging import logging
import nw import nw
from PyQt5.QtCore import Qt from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QFrame, QGridLayout, QLabel, QLineEdit, QPushButton, QApplication from PyQt5.QtWidgets import (
QFrame, QGridLayout, QLabel, QLineEdit, QPushButton, QApplication
)
from nw.enum import nwDocAction from nw.enum import nwDocAction
+4 -4
View File
@@ -13,11 +13,11 @@
import logging import logging
import nw import nw
from PyQt5.QtCore import Qt, QSize from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QFont from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import ( from PyQt5.QtWidgets import (
QWidget, QHBoxLayout, QVBoxLayout, QLabel, QGroupBox, QScrollArea, QFrame, QToolButton, QWidget, QHBoxLayout, QVBoxLayout, QLabel, QGroupBox, QScrollArea, QFrame,
QSizePolicy, QCheckBox, QGridLayout QToolButton, QSizePolicy, QCheckBox, QGridLayout
) )
from nw.constants import nwLabels from nw.constants import nwLabels
+5 -3
View File
@@ -13,8 +13,8 @@
import logging import logging
import nw import nw
from PyQt5.QtCore import QUrl from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QIcon, QDesktopServices from PyQt5.QtGui import QIcon, QDesktopServices
from PyQt5.QtWidgets import QMenuBar, QAction, QMessageBox from PyQt5.QtWidgets import QMenuBar, QAction, QMessageBox
from nw.enum import nwItemType, nwItemClass, nwDocAction from nw.enum import nwItemType, nwItemClass, nwDocAction
@@ -78,7 +78,9 @@ class GuiMainMenu(QMenuBar):
recentProject = self.mainConf.recentList[n] recentProject = self.mainConf.recentList[n]
if recentProject == "": continue if recentProject == "": continue
menuItem = QAction("%s" % recentProject, self.projMenu) menuItem = QAction("%s" % recentProject, self.projMenu)
menuItem.triggered.connect(lambda menuItem, n=n : self.openRecentProject(menuItem, n)) menuItem.triggered.connect(
lambda menuItem, n=n : self.openRecentProject(menuItem, n)
)
self.recentMenu.addAction(menuItem) self.recentMenu.addAction(menuItem)
self.recentMenu.addSeparator() self.recentMenu.addSeparator()
+4 -3
View File
@@ -13,9 +13,10 @@
import logging import logging
import nw import nw
from time import time from time import time
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QIcon, QColor, QPixmap from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QIcon, QColor, QPixmap
from PyQt5.QtWidgets import QStatusBar, QLabel, QFrame from PyQt5.QtWidgets import QStatusBar, QLabel, QFrame
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+16 -14
View File
@@ -14,7 +14,9 @@ import logging
import nw import nw
from PyQt5.QtCore import Qt, QRegularExpression from PyQt5.QtCore import Qt, QRegularExpression
from PyQt5.QtGui import QColor, QTextCharFormat, QFont, QSyntaxHighlighter, QBrush from PyQt5.QtGui import (
QColor, QTextCharFormat, QFont, QSyntaxHighlighter, QBrush
)
from nw.constants import nwUnicode from nw.constants import nwUnicode
@@ -38,18 +40,18 @@ class GuiDocHighlighter(QSyntaxHighlighter):
self.hRules = [] self.hRules = []
self.hStyles = {} self.hStyles = {}
self.colHead = QColor(0,0,0) self.colHead = QColor(0,0,0)
self.colHeadH = QColor(0,0,0) self.colHeadH = QColor(0,0,0)
self.colEmph = QColor(0,0,0) self.colEmph = QColor(0,0,0)
self.colDialN = QColor(0,0,0) self.colDialN = QColor(0,0,0)
self.colDialD = QColor(0,0,0) self.colDialD = QColor(0,0,0)
self.colDialS = QColor(0,0,0) self.colDialS = QColor(0,0,0)
self.colComm = QColor(0,0,0) self.colComm = QColor(0,0,0)
self.colKey = QColor(0,0,0) self.colKey = QColor(0,0,0)
self.colVal = QColor(0,0,0) self.colVal = QColor(0,0,0)
self.colSpell = QColor(0,0,0) self.colSpell = QColor(0,0,0)
self.colTagErr = QColor(0,0,0) self.colTagErr = QColor(0,0,0)
self.colRepTag = QColor(0,0,0) self.colRepTag = QColor(0,0,0)
self.initHighlighter() self.initHighlighter()
@@ -196,7 +198,7 @@ class GuiDocHighlighter(QSyntaxHighlighter):
)) ))
self.hRules.append(( self.hRules.append((
"<(\S+?)>", { r"<(\S+?)>", {
0 : self.hStyles["replace"], 0 : self.hStyles["replace"],
} }
)) ))
+31 -31
View File
@@ -16,37 +16,37 @@ import nw
from os import path from os import path
from PyQt5.QtCore import Qt, QTimer from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QIcon, QPixmap, QColor from PyQt5.QtGui import QIcon, QPixmap, QColor
from PyQt5.QtWidgets import ( from PyQt5.QtWidgets import (
qApp, QWidget, QMainWindow, QVBoxLayout, QFrame, QSplitter, QFileDialog, qApp, QWidget, QMainWindow, QVBoxLayout, QFrame, QSplitter, QFileDialog,
QShortcut, QMessageBox, QProgressDialog, QDialog QShortcut, QMessageBox, QProgressDialog, QDialog
) )
from nw.gui.mainmenu import GuiMainMenu from nw.gui.mainmenu import GuiMainMenu
from nw.gui.statusbar import GuiMainStatus from nw.gui.statusbar import GuiMainStatus
from nw.gui.elements.doctree import GuiDocTree from nw.gui.elements.doctree import GuiDocTree
from nw.gui.elements.doceditor import GuiDocEditor from nw.gui.elements.doceditor import GuiDocEditor
from nw.gui.elements.docviewer import GuiDocViewer from nw.gui.elements.docviewer import GuiDocViewer
from nw.gui.elements.docdetails import GuiDocDetails from nw.gui.elements.docdetails import GuiDocDetails
from nw.gui.elements.searchbar import GuiSearchBar from nw.gui.elements.searchbar import GuiSearchBar
from nw.gui.elements.noticebar import GuiNoticeBar from nw.gui.elements.noticebar import GuiNoticeBar
from nw.gui.elements.viewdetails import GuiDocViewDetails from nw.gui.elements.viewdetails import GuiDocViewDetails
from nw.gui.dialogs.configeditor import GuiConfigEditor from nw.gui.dialogs.configeditor import GuiConfigEditor
from nw.gui.dialogs.projecteditor import GuiProjectEditor from nw.gui.dialogs.projecteditor import GuiProjectEditor
from nw.gui.dialogs.export import GuiExport from nw.gui.dialogs.export import GuiExport
from nw.gui.dialogs.itemeditor import GuiItemEditor from nw.gui.dialogs.itemeditor import GuiItemEditor
from nw.gui.dialogs.timelineview import GuiTimeLineView from nw.gui.dialogs.timelineview import GuiTimeLineView
from nw.gui.dialogs.sessionlog import GuiSessionLogView from nw.gui.dialogs.sessionlog import GuiSessionLogView
from nw.project.project import NWProject from nw.project.project import NWProject
from nw.project.document import NWDoc from nw.project.document import NWDoc
from nw.project.item import NWItem from nw.project.item import NWItem
from nw.project.index import NWIndex from nw.project.index import NWIndex
from nw.project.backup import NWBackup from nw.project.backup import NWBackup
from nw.tools.wordcount import countWords from nw.tools.wordcount import countWords
from nw.theme import Theme from nw.theme import Theme
from nw.enum import nwItemType, nwAlert from nw.enum import nwItemType, nwAlert
from nw.constants import nwFiles from nw.constants import nwFiles
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -168,17 +168,17 @@ class GuiMain(QMainWindow):
QShortcut( QShortcut(
Qt.Key_Return, Qt.Key_Return,
self.treeView, self.treeView,
context = Qt.WidgetShortcut, context=Qt.WidgetShortcut,
activated = self._treeKeyPressReturn activated=self._treeKeyPressReturn
) )
QShortcut( QShortcut(
Qt.Key_Escape, Qt.Key_Escape,
self, self,
activated = self._keyPressEscape activated=self._keyPressEscape
) )
# Forward Functions # Forward Functions
self.setStatus = self.statusBar.setStatus self.setStatus = self.statusBar.setStatus
self.setProjectStatus = self.statusBar.setProjectStatus self.setProjectStatus = self.statusBar.setProjectStatus
if self.mainConf.showGUI: if self.mainConf.showGUI:
@@ -578,7 +578,7 @@ class GuiMain(QMainWindow):
dlgOpt |= QFileDialog.ShowDirsOnly dlgOpt |= QFileDialog.ShowDirsOnly
dlgOpt |= QFileDialog.DontUseNativeDialog dlgOpt |= QFileDialog.DontUseNativeDialog
projPath = QFileDialog.getExistingDirectory( projPath = QFileDialog.getExistingDirectory(
self,"Save novelWriter Project","",options=dlgOpt self, "Save novelWriter Project", "", options=dlgOpt
) )
if projPath: if projPath:
return projPath return projPath
@@ -589,7 +589,7 @@ class GuiMain(QMainWindow):
dlgOpt |= QFileDialog.ShowDirsOnly dlgOpt |= QFileDialog.ShowDirsOnly
dlgOpt |= QFileDialog.DontUseNativeDialog dlgOpt |= QFileDialog.DontUseNativeDialog
projPath = QFileDialog.getExistingDirectory( projPath = QFileDialog.getExistingDirectory(
self,"Select Location for New novelWriter Project","",options=dlgOpt self, "Select Location for New novelWriter Project", "", options=dlgOpt
) )
if projPath: if projPath:
return projPath return projPath
+2 -2
View File
@@ -13,8 +13,8 @@
import logging import logging
import nw import nw
from os import path, mkdir, listdir from os import path, mkdir, listdir
from shutil import make_archive from shutil import make_archive
from datetime import datetime from datetime import datetime
from nw.enum import nwAlert from nw.enum import nwAlert
+6 -3
View File
@@ -103,9 +103,12 @@ class NWDoc():
docTemp = path.join(dataPath,docFile[:-3]+"tmp") docTemp = path.join(dataPath,docFile[:-3]+"tmp")
docBack = path.join(dataPath,docFile[:-3]+"bak") docBack = path.join(dataPath,docFile[:-3]+"bak")
if path.isfile(docTemp): unlink(docTemp) if path.isfile(docTemp):
if path.isfile(docBack): rename(docBack,docTemp) unlink(docTemp)
if path.isfile(docPath): rename(docPath,docBack) if path.isfile(docBack):
rename(docBack,docTemp)
if path.isfile(docPath):
rename(docPath,docBack)
try: try:
with open(docPath,mode="w",encoding="utf8") as outFile: with open(docPath,mode="w",encoding="utf8") as outFile:
+7 -9
View File
@@ -17,9 +17,9 @@ import nw
from os import path from os import path
from nw.project.document import NWDoc from nw.project.document import NWDoc
from nw.enum import nwItemType, nwItemClass, nwItemLayout from nw.enum import nwItemType, nwItemClass, nwItemLayout
from nw.constants import nwFiles, nwKeyWords from nw.constants import nwFiles, nwKeyWords
from nw.enum import nwAlert from nw.enum import nwAlert
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -62,7 +62,7 @@ class NWIndex():
self.noteIndex = {} self.noteIndex = {}
# Lists # Lists
self.novelList = [] self.novelList = []
return return
@@ -101,7 +101,7 @@ class NWIndex():
"""Load index from last session from the project meta folder. """Load index from last session from the project meta folder.
""" """
theData = {} theData = {}
indexFile = path.join(self.theProject.projMeta, nwFiles.INDEX_FILE) indexFile = path.join(self.theProject.projMeta, nwFiles.INDEX_FILE)
if path.isfile(indexFile): if path.isfile(indexFile):
logger.debug("Loading index file") logger.debug("Loading index file")
@@ -213,11 +213,11 @@ class NWIndex():
# Check file type, and reset its old index # Check file type, and reset its old index
if itemClass == nwItemClass.NOVEL: if itemClass == nwItemClass.NOVEL:
self.novelIndex[tHandle] = [] self.novelIndex[tHandle] = []
self.refIndex[tHandle] = [] self.refIndex[tHandle] = []
isNovel = True isNovel = True
else: else:
self.noteIndex[tHandle] = [] self.noteIndex[tHandle] = []
self.refIndex[tHandle] = [] self.refIndex[tHandle] = []
isNovel = False isNovel = False
# Also clear references to file in tag index # Also clear references to file in tag index
@@ -390,7 +390,6 @@ class NWIndex():
def buildNovelList(self): def buildNovelList(self):
"""Build a list of the content of the novel. """Build a list of the content of the novel.
""" """
self.novelList = [] self.novelList = []
self.novelOrder = [] self.novelOrder = []
for tHandle in self.theProject.treeOrder: for tHandle in self.theProject.treeOrder:
@@ -399,7 +398,6 @@ class NWIndex():
for tEntry in self.novelIndex[tHandle]: for tEntry in self.novelIndex[tHandle]:
self.novelList.append(tEntry) self.novelList.append(tEntry)
self.novelOrder.append("%s:%d" % (tHandle,tEntry[0])) self.novelOrder.append("%s:%d" % (tHandle,tEntry[0]))
return True return True
def buildReferenceList(self, tHandle): def buildReferenceList(self, tHandle):
+18 -18
View File
@@ -13,11 +13,11 @@
import logging import logging
import nw import nw
from os import path, mkdir from os import path, mkdir
from lxml import etree from lxml import etree
from datetime import datetime from datetime import datetime
from nw.enum import nwItemType, nwItemClass, nwItemLayout from nw.enum import nwItemType, nwItemClass, nwItemLayout
from nw.common import checkInt from nw.common import checkInt
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -28,23 +28,23 @@ class NWItem():
def __init__(self, theProject): def __init__(self, theProject):
self.theProject = theProject self.theProject = theProject
self.itemName = "" self.itemName = ""
self.itemHandle = None self.itemHandle = None
self.parHandle = None self.parHandle = None
self.itemOrder = None self.itemOrder = None
self.itemType = nwItemType.NO_TYPE self.itemType = nwItemType.NO_TYPE
self.itemClass = nwItemClass.NO_CLASS self.itemClass = nwItemClass.NO_CLASS
self.itemLayout = nwItemLayout.NO_LAYOUT self.itemLayout = nwItemLayout.NO_LAYOUT
self.itemStatus = None self.itemStatus = None
self.isExpanded = False self.isExpanded = False
# Document Meta Data # Document Meta Data
self.charCount = 0 self.charCount = 0
self.wordCount = 0 self.wordCount = 0
self.paraCount = 0 self.paraCount = 0
self.cursorPos = 0 self.cursorPos = 0
return return
+40 -38
View File
@@ -13,18 +13,18 @@
import logging import logging
import nw import nw
from os import path, mkdir, listdir from os import path, mkdir, listdir
from shutil import copyfile from shutil import copyfile
from lxml import etree from lxml import etree
from hashlib import sha256 from hashlib import sha256
from datetime import datetime from datetime import datetime
from time import time from time import time
from nw.project.item import NWItem from nw.project.item import NWItem
from nw.project.status import NWStatus from nw.project.status import NWStatus
from nw.enum import nwItemType, nwItemClass, nwItemLayout, nwAlert from nw.enum import nwItemType, nwItemClass, nwItemLayout, nwAlert
from nw.common import checkString, checkBool, checkInt from nw.common import checkString, checkBool, checkInt
from nw.constants import nwFiles, nwConst from nw.constants import nwFiles, nwConst
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -40,18 +40,18 @@ class NWProject():
self.projAltered = None # The project has been altered this session self.projAltered = None # The project has been altered this session
# Debug # Debug
self.handleSeed = None self.handleSeed = None
# Class Settings # Class Settings
self.projTree = None # Holds all the items of the project self.projTree = None # Holds all the items of the project
self.treeOrder = None # The order of the tree items on the tree view self.treeOrder = None # The order of the tree items on the tree view
self.treeRoots = None # The root items of the tree self.treeRoots = None # The root items of the tree
self.trashRoot = None # The handle of the trash root folder self.trashRoot = None # The handle of the trash root folder
self.projPath = None # The full path to where the currently open project is saved self.projPath = None # The full path to where the currently open project is saved
self.projMeta = None # The full path to the project's meta data folder self.projMeta = None # The full path to the project's meta data folder
self.projCache = None # The full path to the project's cache folder self.projCache = None # The full path to the project's cache folder
self.projDict = None # The spell check dictionary self.projDict = None # The spell check dictionary
self.projFile = None # The file name of the project main xml file self.projFile = None # The file name of the project main xml file
# Project Meta # Project Meta
self.projName = None self.projName = None
@@ -194,8 +194,10 @@ class NWProject():
self.projCache = path.join(self.projPath,"cache") self.projCache = path.join(self.projPath,"cache")
self.projDict = path.join(self.projMeta, nwFiles.PROJ_DICT) self.projDict = path.join(self.projMeta, nwFiles.PROJ_DICT)
if not self._checkFolder(self.projMeta): return if not self._checkFolder(self.projMeta):
if not self._checkFolder(self.projCache): return return
if not self._checkFolder(self.projCache):
return
try: try:
nwXML = etree.parse(fileName) nwXML = etree.parse(fileName)
@@ -313,19 +315,19 @@ class NWProject():
}) })
# Save Project Meta # Save Project Meta
xProject = etree.SubElement(nwXML,"project") xProject = etree.SubElement(nwXML, "project")
self._saveProjectValue(xProject,"name", self.projName, True) self._saveProjectValue(xProject, "name", self.projName, True)
self._saveProjectValue(xProject,"title", self.bookTitle, True) self._saveProjectValue(xProject, "title", self.bookTitle, True)
self._saveProjectValue(xProject,"author",self.bookAuthors) self._saveProjectValue(xProject, "author", self.bookAuthors)
self._saveProjectValue(xProject,"backup",self.doBackup) self._saveProjectValue(xProject, "backup", self.doBackup)
# Save Project Settings # Save Project Settings
xSettings = etree.SubElement(nwXML,"settings") xSettings = etree.SubElement(nwXML, "settings")
self._saveProjectValue(xSettings,"spellCheck", self.spellCheck) self._saveProjectValue(xSettings, "spellCheck", self.spellCheck)
self._saveProjectValue(xSettings,"lastEdited", self.lastEdited) self._saveProjectValue(xSettings, "lastEdited", self.lastEdited)
self._saveProjectValue(xSettings,"lastViewed", self.lastViewed) self._saveProjectValue(xSettings, "lastViewed", self.lastViewed)
self._saveProjectValue(xSettings,"lastWordCount",self.currWCount) self._saveProjectValue(xSettings, "lastWordCount", self.currWCount)
xAutoRep = etree.SubElement(xSettings,"autoReplace") xAutoRep = etree.SubElement(xSettings, "autoReplace")
for aKey, aValue in self.autoReplace.items(): for aKey, aValue in self.autoReplace.items():
if len(aKey) > 0: if len(aKey) > 0:
self._saveProjectValue(xAutoRep,aKey,aValue) self._saveProjectValue(xAutoRep,aKey,aValue)
@@ -337,7 +339,7 @@ class NWProject():
# Save Tree Content # Save Tree Content
logger.debug("Writing project content") logger.debug("Writing project content")
xContent = etree.SubElement(nwXML,"content",attrib={"count":str(len(self.treeOrder))}) xContent = etree.SubElement(nwXML, "content", attrib={"count":str(len(self.treeOrder))})
for tHandle in self.treeOrder: for tHandle in self.treeOrder:
self.projTree[tHandle].packXML(xContent) self.projTree[tHandle].packXML(xContent)
@@ -411,8 +413,8 @@ class NWProject():
return False return False
if self.projName == "": if self.projName == "":
self.theParent.makeAlert(( self.theParent.makeAlert((
"You must set a valid project name in project settings to use " "You must set a valid project name in project settings to "
"the automatic project backup feature." "use the automatic project backup feature."
), nwAlert.ERROR) ), nwAlert.ERROR)
return False return False
self.doBackup = True self.doBackup = True
@@ -699,7 +701,7 @@ class NWProject():
sessionFile = path.join(self.projMeta, nwFiles.SESS_INFO) sessionFile = path.join(self.projMeta, nwFiles.SESS_INFO)
with open(sessionFile,mode="a+",encoding="utf8") as outFile: with open(sessionFile, mode="a+", encoding="utf8") as outFile:
print(( print((
"Start: {opened:s} " "Start: {opened:s} "
"End: {closed:s} " "End: {closed:s} "
@@ -750,8 +752,8 @@ class NWProject():
try: try:
copyfile( copyfile(
path.join(self.projPath,self.projFile), path.join(self.projPath, self.projFile),
path.join(self.projCache,projBackup) path.join(self.projCache, projBackup)
) )
except: except:
logger.error("Failed to write to file %s" % projBackup) logger.error("Failed to write to file %s" % projBackup)
+1 -1
View File
@@ -15,7 +15,7 @@ import nw
from lxml import etree from lxml import etree
from nw.enum import nwItemClass from nw.enum import nwItemClass
from nw.common import checkInt from nw.common import checkInt
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+86 -86
View File
@@ -17,7 +17,7 @@ import nw
from os import path, listdir from os import path, listdir
from PyQt5.QtWidgets import qApp from PyQt5.QtWidgets import qApp
from PyQt5.QtGui import QPalette, QColor, QIcon from PyQt5.QtGui import QPalette, QColor, QIcon
from nw.enum import nwAlert from nw.enum import nwAlert
@@ -41,30 +41,30 @@ class Theme:
def __init__(self, theParent): def __init__(self, theParent):
self.mainConf = nw.CONFIG self.mainConf = nw.CONFIG
self.theParent = theParent self.theParent = theParent
self.guiPalette = QPalette() self.guiPalette = QPalette()
self.guiPath = "gui" self.guiPath = "gui"
self.iconPath = "icons" self.iconPath = "icons"
self.syntaxPath = "syntax" self.syntaxPath = "syntax"
self.cssName = "style.qss" self.cssName = "style.qss"
self.confName = "theme.conf" self.confName = "theme.conf"
self.themeList = [] self.themeList = []
self.syntaxList = [] self.syntaxList = []
# Loaded Theme Settings # Loaded Theme Settings
## Theme ## Theme
self.themeName = "" self.themeName = ""
self.themeAuthor = "" self.themeAuthor = ""
self.themeCredit = "" self.themeCredit = ""
self.themeUrl = "" self.themeUrl = ""
## GUI ## GUI
self.treeWCount = [ 0, 0, 0] self.treeWCount = [ 0, 0, 0]
self.statNone = [120,120,120] self.statNone = [120,120,120]
self.statUnsaved = [120,120, 40] self.statUnsaved = [120,120, 40]
self.statSaved = [ 40,120, 0] self.statSaved = [ 40,120, 0]
# Loaded Syntax Settings # Loaded Syntax Settings
@@ -75,33 +75,33 @@ class Theme:
self.syntaxUrl = "" self.syntaxUrl = ""
## Colours ## Colours
self.colBack = [255,255,255] self.colBack = [255,255,255]
self.colText = [ 0, 0, 0] self.colText = [ 0, 0, 0]
self.colLink = [ 0, 0, 0] self.colLink = [ 0, 0, 0]
self.colHead = [ 0, 0, 0] self.colHead = [ 0, 0, 0]
self.colHeadH = [ 0, 0, 0] self.colHeadH = [ 0, 0, 0]
self.colEmph = [ 0, 0, 0] self.colEmph = [ 0, 0, 0]
self.colDialN = [ 0, 0, 0] self.colDialN = [ 0, 0, 0]
self.colDialD = [ 0, 0, 0] self.colDialD = [ 0, 0, 0]
self.colDialS = [ 0, 0, 0] self.colDialS = [ 0, 0, 0]
self.colComm = [ 0, 0, 0] self.colComm = [ 0, 0, 0]
self.colKey = [ 0, 0, 0] self.colKey = [ 0, 0, 0]
self.colVal = [ 0, 0, 0] self.colVal = [ 0, 0, 0]
self.colSpell = [ 0, 0, 0] self.colSpell = [ 0, 0, 0]
self.colTagErr = [ 0, 0, 0] self.colTagErr = [ 0, 0, 0]
self.colRepTag = [ 0, 0, 0] self.colRepTag = [ 0, 0, 0]
## Icons ## Icons
self.themeIcons = {} self.themeIcons = {}
# Changeable Settings # Changeable Settings
self.guiTheme = None self.guiTheme = None
self.guiSyntax = None self.guiSyntax = None
self.themeRoot = None self.themeRoot = None
self.themePath = None self.themePath = None
self.syntaxFile = None self.syntaxFile = None
self.confFile = None self.confFile = None
self.cssFile = None self.cssFile = None
self.updateTheme() self.updateTheme()
@@ -162,36 +162,36 @@ class Theme:
## Main ## Main
cnfSec = "Main" cnfSec = "Main"
if confParser.has_section(cnfSec): if confParser.has_section(cnfSec):
self.themeName = self._parseLine(confParser,cnfSec,"name", "") self.themeName = self._parseLine( confParser, cnfSec, "name", "")
self.themeAuthor = self._parseLine(confParser,cnfSec,"author","") self.themeAuthor = self._parseLine( confParser, cnfSec, "author", "")
self.themeCredit = self._parseLine(confParser,cnfSec,"credit","") self.themeCredit = self._parseLine( confParser, cnfSec, "credit", "")
self.themeUrl = self._parseLine(confParser,cnfSec,"url", "") self.themeUrl = self._parseLine( confParser, cnfSec, "url", "")
## Palette ## Palette
cnfSec = "Palette" cnfSec = "Palette"
if confParser.has_section(cnfSec): if confParser.has_section(cnfSec):
self._setPalette(confParser,cnfSec,"window", QPalette.Window) self._setPalette(confParser, cnfSec, "window", QPalette.Window)
self._setPalette(confParser,cnfSec,"windowtext", QPalette.WindowText) self._setPalette(confParser, cnfSec, "windowtext", QPalette.WindowText)
self._setPalette(confParser,cnfSec,"base", QPalette.Base) self._setPalette(confParser, cnfSec, "base", QPalette.Base)
self._setPalette(confParser,cnfSec,"alternatebase", QPalette.AlternateBase) self._setPalette(confParser, cnfSec, "alternatebase", QPalette.AlternateBase)
self._setPalette(confParser,cnfSec,"text", QPalette.Text) self._setPalette(confParser, cnfSec, "text", QPalette.Text)
self._setPalette(confParser,cnfSec,"tooltipbase", QPalette.ToolTipBase) self._setPalette(confParser, cnfSec, "tooltipbase", QPalette.ToolTipBase)
self._setPalette(confParser,cnfSec,"tooltiptext", QPalette.ToolTipText) self._setPalette(confParser, cnfSec, "tooltiptext", QPalette.ToolTipText)
self._setPalette(confParser,cnfSec,"button", QPalette.Button) self._setPalette(confParser, cnfSec, "button", QPalette.Button)
self._setPalette(confParser,cnfSec,"buttontext", QPalette.ButtonText) self._setPalette(confParser, cnfSec, "buttontext", QPalette.ButtonText)
self._setPalette(confParser,cnfSec,"brighttext", QPalette.BrightText) self._setPalette(confParser, cnfSec, "brighttext", QPalette.BrightText)
self._setPalette(confParser,cnfSec,"highlight", QPalette.Highlight) self._setPalette(confParser, cnfSec, "highlight", QPalette.Highlight)
self._setPalette(confParser,cnfSec,"highlightedtext",QPalette.HighlightedText) self._setPalette(confParser, cnfSec, "highlightedtext", QPalette.HighlightedText)
self._setPalette(confParser,cnfSec,"link", QPalette.Link) self._setPalette(confParser, cnfSec, "link", QPalette.Link)
self._setPalette(confParser,cnfSec,"linkvisited", QPalette.LinkVisited) self._setPalette(confParser, cnfSec, "linkvisited", QPalette.LinkVisited)
## GUI ## GUI
cnfSec = "GUI" cnfSec = "GUI"
if confParser.has_section(cnfSec): if confParser.has_section(cnfSec):
self.treeWCount = self._loadColour(confParser,cnfSec,"treewordcount") self.treeWCount = self._loadColour(confParser, cnfSec, "treewordcount")
self.statNone = self._loadColour(confParser,cnfSec,"statusnone") self.statNone = self._loadColour(confParser, cnfSec, "statusnone")
self.statUnsaved = self._loadColour(confParser,cnfSec,"statusunsaved") self.statUnsaved = self._loadColour(confParser, cnfSec, "statusunsaved")
self.statSaved = self._loadColour(confParser,cnfSec,"statussaved") self.statSaved = self._loadColour(confParser, cnfSec, "statussaved")
# Apply Styles # Apply Styles
qApp.setStyleSheet(cssData) qApp.setStyleSheet(cssData)
@@ -205,7 +205,7 @@ class Theme:
confParser = configparser.ConfigParser() confParser = configparser.ConfigParser()
try: try:
confParser.read_file(open(self.syntaxFile,mode="r",encoding="utf8")) confParser.read_file(open(self.syntaxFile, mode="r", encoding="utf8"))
except Exception as e: except Exception as e:
logger.error("Could not load syntax colours from: %s" % self.syntaxFile) logger.error("Could not load syntax colours from: %s" % self.syntaxFile)
return False return False
@@ -213,29 +213,29 @@ class Theme:
## Main ## Main
cnfSec = "Main" cnfSec = "Main"
if confParser.has_section(cnfSec): if confParser.has_section(cnfSec):
self.syntaxName = self._parseLine(confParser,cnfSec,"name","") self.syntaxName = self._parseLine(confParser, cnfSec, "name", "")
self.syntaxAuthor = self._parseLine(confParser,cnfSec,"author","") self.syntaxAuthor = self._parseLine(confParser, cnfSec, "author", "")
self.syntaxCredit = self._parseLine(confParser,cnfSec,"credit","") self.syntaxCredit = self._parseLine(confParser, cnfSec, "credit", "")
self.syntaxUrl = self._parseLine(confParser,cnfSec,"url", "") self.syntaxUrl = self._parseLine(confParser, cnfSec, "url", "")
## Syntax ## Syntax
cnfSec = "Syntax" cnfSec = "Syntax"
if confParser.has_section(cnfSec): if confParser.has_section(cnfSec):
self.colBack = self._loadColour(confParser,cnfSec,"background") self.colBack = self._loadColour(confParser, cnfSec, "background")
self.colText = self._loadColour(confParser,cnfSec,"text") self.colText = self._loadColour(confParser, cnfSec, "text")
self.colLink = self._loadColour(confParser,cnfSec,"link") self.colLink = self._loadColour(confParser, cnfSec, "link")
self.colHead = self._loadColour(confParser,cnfSec,"headertext") self.colHead = self._loadColour(confParser, cnfSec, "headertext")
self.colHeadH = self._loadColour(confParser,cnfSec,"headertag") self.colHeadH = self._loadColour(confParser, cnfSec, "headertag")
self.colEmph = self._loadColour(confParser,cnfSec,"emphasis") self.colEmph = self._loadColour(confParser, cnfSec, "emphasis")
self.colDialN = self._loadColour(confParser,cnfSec,"straightquotes") self.colDialN = self._loadColour(confParser, cnfSec, "straightquotes")
self.colDialD = self._loadColour(confParser,cnfSec,"doublequotes") self.colDialD = self._loadColour(confParser, cnfSec, "doublequotes")
self.colDialS = self._loadColour(confParser,cnfSec,"singlequotes") self.colDialS = self._loadColour(confParser, cnfSec, "singlequotes")
self.colComm = self._loadColour(confParser,cnfSec,"hidden") self.colComm = self._loadColour(confParser, cnfSec, "hidden")
self.colKey = self._loadColour(confParser,cnfSec,"keyword") self.colKey = self._loadColour(confParser, cnfSec, "keyword")
self.colVal = self._loadColour(confParser,cnfSec,"value") self.colVal = self._loadColour(confParser, cnfSec, "value")
self.colSpell = self._loadColour(confParser,cnfSec,"spellcheckline") self.colSpell = self._loadColour(confParser, cnfSec, "spellcheckline")
self.colTagErr = self._loadColour(confParser,cnfSec,"tagerror") self.colTagErr = self._loadColour(confParser, cnfSec, "tagerror")
self.colRepTag = self._loadColour(confParser,cnfSec,"replacetag") self.colRepTag = self._loadColour(confParser, cnfSec, "replacetag")
logger.info("Loaded syntax theme '%s'" % self.guiSyntax) logger.info("Loaded syntax theme '%s'" % self.guiSyntax)
@@ -251,7 +251,7 @@ class Theme:
themeConf = path.join(self.mainConf.themeRoot, self.guiPath, themeDir, self.confName) themeConf = path.join(self.mainConf.themeRoot, self.guiPath, themeDir, self.confName)
logger.verbose("Checking theme config for '%s'" % themeDir) logger.verbose("Checking theme config for '%s'" % themeDir)
try: try:
confParser.read_file(open(themeConf,mode="r",encoding="utf8")) confParser.read_file(open(themeConf, mode="r", encoding="utf8"))
except Exception as e: except Exception as e:
self.theParent.makeAlert(["Could not load theme config file",str(e)],nwAlert.ERROR) self.theParent.makeAlert(["Could not load theme config file",str(e)],nwAlert.ERROR)
continue continue
@@ -279,7 +279,7 @@ class Theme:
continue continue
logger.verbose("Checking theme syntax for '%s'" % syntaxFile) logger.verbose("Checking theme syntax for '%s'" % syntaxFile)
try: try:
confParser.read_file(open(syntaxPath,mode="r",encoding="utf8")) confParser.read_file(open(syntaxPath, mode="r", encoding="utf8"))
except Exception as e: except Exception as e:
self.theParent.makeAlert(["Could not load syntax file",str(e)],nwAlert.ERROR) self.theParent.makeAlert(["Could not load syntax file",str(e)],nwAlert.ERROR)
return [] return []
+2 -2
View File
@@ -130,8 +130,8 @@ class TextAnalysis():
else: else:
cleanText += " " cleanText += " "
asVow = "aeiouy'" asVow = "aeiouy'"
dExept = ("ei","ie","ua","ia","eo") dExept = ("ei","ie","ua","ia","eo")
theWords = cleanText.lower().split() theWords = cleanText.lower().split()
allSylls = 0 allSylls = 0
for inWord in theWords: for inWord in theWords:
+1 -1
View File
@@ -34,7 +34,7 @@ def countWords(theText):
if aLine[0] == "@" or aLine[0] == "%": if aLine[0] == "@" or aLine[0] == "%":
continue continue
if aLine[0:5] == "#### ": if aLine[0:5] == "#### ":
wordCount -= 1 wordCount -= 1
charCount -= 5 charCount -= 5
countPara = False countPara = False