Move all code to set default text font into the Config class

This commit is contained in:
Veronica Berglyd Olsen
2023-05-31 17:49:31 +02:00
parent 74f46f4633
commit 704fffada3
13 changed files with 62 additions and 63 deletions
+4 -1
View File
@@ -241,8 +241,11 @@ def main(sysArgs=None):
# Connect the exception handler before making the main GUI # Connect the exception handler before making the main GUI
sys.excepthook = exceptionHandler sys.excepthook = exceptionHandler
# Launch main GUI # Run Config steps that require the QApplication
CONFIG.initLocalisation(nwApp) CONFIG.initLocalisation(nwApp)
CONFIG.setTextFont(CONFIG.textFont, CONFIG.textSize) # Makes sure these are valid
# Launch main GUI
nwGUI = GuiMain() nwGUI = GuiMain()
nwGUI.postLaunchTasks(cmdOpen) nwGUI.postLaunchTasks(cmdOpen)
+37 -14
View File
@@ -23,6 +23,8 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. along with this program. If not, see <https://www.gnu.org/licenses/>.
""" """
from __future__ import annotations
import sys import sys
import json import json
import logging import logging
@@ -30,6 +32,7 @@ import logging
from time import time from time import time
from pathlib import Path from pathlib import Path
from PyQt5.QtGui import QFontDatabase
from PyQt5.QtCore import ( from PyQt5.QtCore import (
QT_VERSION, QT_VERSION_STR, PYQT_VERSION, PYQT_VERSION_STR, QStandardPaths, QT_VERSION, QT_VERSION_STR, PYQT_VERSION, PYQT_VERSION_STR, QStandardPaths,
QSysInfo, QLocale, QLibraryInfo, QTranslator QSysInfo, QLocale, QLibraryInfo, QTranslator
@@ -120,7 +123,7 @@ class Config:
self.askBeforeBackup = True # Flag for asking before running automatic backup self.askBeforeBackup = True # Flag for asking before running automatic backup
# Text Editor Settings # Text Editor Settings
self.textFont = None # Editor font self.textFont = "" # Editor font
self.textSize = 12 # Editor font size self.textSize = 12 # Editor font size
self.textWidth = 700 # Editor text width self.textWidth = 700 # Editor text width
self.textMargin = 40 # Editor/viewer text margin self.textMargin = 40 # Editor/viewer text margin
@@ -335,40 +338,59 @@ class Config:
logger.debug("Last path updated: %s" % self._lastPath) logger.debug("Last path updated: %s" % self._lastPath)
return return
def setBackupPath(self, backupPath): def setBackupPath(self, backupPath: Path | None):
"""Set the current backup path.""" """Set the current backup path."""
self._backupPath = checkPath(backupPath, None) self._backupPath = checkPath(backupPath, None)
return return
def setTextFont(self, family: str | None, pointSize: int = 12):
"""Set the text font if it exists. If it doesn't, or is None,
set to default font.
"""
fontDB = QFontDatabase()
fontFam = fontDB.families()
self.textSize = pointSize
if family is None or family not in fontFam:
logger.warning("Unknown font '%s'", family)
if self.osWindows and "Arial" in fontFam:
self.textFont = "Arial"
elif self.osDarwin and "Courier" in fontFam:
self.textFont = "Courier"
else:
self.textFont = fontDB.systemFont(QFontDatabase.GeneralFont).family()
else:
self.textFont = family
return
## ##
# Methods # Methods
## ##
def pxInt(self, theSize): def pxInt(self, value: int) -> int:
"""Used to scale fixed gui sizes by the screen scale factor. """Used to scale fixed gui sizes by the screen scale factor.
This function returns an int, which is always rounded down. This function returns an int, which is always rounded down.
""" """
return int(theSize*self.guiScale) return int(value*self.guiScale)
def rpxInt(self, theSize): def rpxInt(self, value: int) -> int:
"""Used to un-scale fixed gui sizes by the screen scale factor. """Used to un-scale fixed gui sizes by the screen scale factor.
This function returns an int, which is always rounded down. This function returns an int, which is always rounded down.
""" """
return int(theSize/self.guiScale) return int(value/self.guiScale)
def dataPath(self, target=None): def dataPath(self, target: str | None = None) -> Path:
"""Return a path in the data folder.""" """Return a path in the data folder."""
if isinstance(target, str): if isinstance(target, str):
return self._dataPath / target return self._dataPath / target
return self._dataPath return self._dataPath
def assetPath(self, target=None): def assetPath(self, target: str | None = None) -> Path:
"""Return a path in the assets folder.""" """Return a path in the assets folder."""
if isinstance(target, str): if isinstance(target, str):
return self._appPath / "assets" / target return self._appPath / "assets" / target
return self._appPath / "assets" return self._appPath / "assets"
def lastPath(self): def lastPath(self) -> Path:
"""Return the last path used by the user, but ensure it exists. """Return the last path used by the user, but ensure it exists.
""" """
if isinstance(self._lastPath, Path): if isinstance(self._lastPath, Path):
@@ -376,14 +398,14 @@ class Config:
return self._lastPath return self._lastPath
return self._homePath return self._homePath
def backupPath(self): def backupPath(self) -> Path | None:
"""Return the backup path.""" """Return the backup path."""
if isinstance(self._backupPath, Path): if isinstance(self._backupPath, Path):
if self._backupPath.is_dir(): if self._backupPath.is_dir():
return self._backupPath return self._backupPath
return None return None
def errorText(self): def errorText(self) -> str:
"""Compile and return error messages from the initialisation of """Compile and return error messages from the initialisation of
the Config class, and clear the error buffer. the Config class, and clear the error buffer.
""" """
@@ -392,7 +414,7 @@ class Config:
self._errData = [] self._errData = []
return errMessage return errMessage
def listLanguages(self, lngSet): def listLanguages(self, lngSet: int) -> list[tuple[str, str]]:
"""List localisation files in the i18n folder. The default GUI """List localisation files in the i18n folder. The default GUI
language is British English (en_GB). language is British English (en_GB).
""" """
@@ -423,7 +445,7 @@ class Config:
# Config Actions # Config Actions
## ##
def initConfig(self, confPath=None, dataPath=None): def initConfig(self, confPath: str | Path | None = None, dataPath: str | Path | None = None):
"""Initialise the config class. The manual setting of confPath """Initialise the config class. The manual setting of confPath
and dataPath is mainly intended for the test suite. and dataPath is mainly intended for the test suite.
""" """
@@ -449,9 +471,10 @@ class Config:
# Also create the syntax, themes and icons folders if possible # Also create the syntax, themes and icons folders if possible
if self._dataPath.is_dir(): if self._dataPath.is_dir():
(self._dataPath / "cache").mkdir(exist_ok=True)
(self._dataPath / "icons").mkdir(exist_ok=True)
(self._dataPath / "syntax").mkdir(exist_ok=True) (self._dataPath / "syntax").mkdir(exist_ok=True)
(self._dataPath / "themes").mkdir(exist_ok=True) (self._dataPath / "themes").mkdir(exist_ok=True)
(self._dataPath / "icons").mkdir(exist_ok=True)
# Check if config file exists, and load it. If not, we save defaults # Check if config file exists, and load it. If not, we save defaults
if (self._confPath / nwFiles.CONF_FILE).is_file(): if (self._confPath / nwFiles.CONF_FILE).is_file():
-4
View File
@@ -23,7 +23,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. along with this program. If not, see <https://www.gnu.org/licenses/>.
""" """
from PyQt5.QtGui import QFontDatabase
from PyQt5.QtCore import QCoreApplication, QT_TRANSLATE_NOOP from PyQt5.QtCore import QCoreApplication, QT_TRANSLATE_NOOP
from novelwriter.enum import nwItemClass, nwItemLayout, nwOutline from novelwriter.enum import nwItemClass, nwItemLayout, nwOutline
@@ -54,9 +53,6 @@ class nwConst:
URL_HELP = "https://github.com/vkbo/novelWriter/discussions" URL_HELP = "https://github.com/vkbo/novelWriter/discussions"
URL_RELEASE = "https://github.com/vkbo/novelWriter/releases/latest" URL_RELEASE = "https://github.com/vkbo/novelWriter/releases/latest"
# System Values
SYSTEM_FONT = QFontDatabase.systemFont(QFontDatabase.GeneralFont).family()
# END Class nwConst # END Class nwConst
+2 -2
View File
@@ -36,7 +36,7 @@ from pathlib import Path
from PyQt5.QtCore import QT_TRANSLATE_NOOP from PyQt5.QtCore import QT_TRANSLATE_NOOP
from novelwriter.common import checkUuid, isHandle, jsonEncode from novelwriter.common import checkUuid, isHandle, jsonEncode
from novelwriter.constants import nwConst, nwFiles, nwHeadFmt from novelwriter.constants import nwFiles, nwHeadFmt
from novelwriter.core.item import NWItem from novelwriter.core.item import NWItem
from novelwriter.core.project import NWProject from novelwriter.core.project import NWProject
from novelwriter.error import logException from novelwriter.error import logException
@@ -65,7 +65,7 @@ SETTINGS_TEMPLATE = {
"text.includeBodyText": (bool, True), "text.includeBodyText": (bool, True),
"text.addNoteHeadings": (bool, True), "text.addNoteHeadings": (bool, True),
"format.buildLang": (str, "en_GB"), "format.buildLang": (str, "en_GB"),
"format.textFont": (str, nwConst.SYSTEM_FONT), "format.textFont": (str, ""),
"format.textSize": (int, 12), "format.textSize": (int, 12),
"format.lineHeight": (float, 1.15, 0.75, 3.0), "format.lineHeight": (float, 1.15, 0.75, 3.0),
"format.justifyText": (bool, False), "format.justifyText": (bool, False),
+1 -2
View File
@@ -613,8 +613,7 @@ class GuiPreferencesDocuments(QWidget):
"""Save the values set for this tab. """Save the values set for this tab.
""" """
# Text Style # Text Style
CONFIG.textFont = self.textFont.text() CONFIG.setTextFont(self.textFont.text(), self.textSize.value())
CONFIG.textSize = self.textSize.value()
# Text Flow # Text Flow
CONFIG.textWidth = self.textWidth.value() CONFIG.textWidth = self.textWidth.value()
+5 -20
View File
@@ -276,31 +276,16 @@ class GuiDocEditor(QTextEdit):
self.setDictionaries() self.setDictionaries()
# Set font # Set font
theFont = QFont() textFont = QFont()
qDoc = self.document() textFont.setFamily(CONFIG.textFont)
if CONFIG.textFont is None: textFont.setPointSize(CONFIG.textSize)
# If none is defined, set a default font self.setFont(textFont)
theFont = QFont()
if CONFIG.osWindows and "Arial" in self.mainTheme.guiFontDB.families():
theFont.setFamily("Arial")
theFont.setPointSize(12)
elif CONFIG.osDarwin and "Courier" in self.mainTheme.guiFontDB.families():
theFont.setFamily("Courier")
theFont.setPointSize(12)
else:
theFont = qDoc.defaultFont()
CONFIG.textFont = theFont.family()
CONFIG.textSize = theFont.pointSize()
theFont.setFamily(CONFIG.textFont)
theFont.setPointSize(CONFIG.textSize)
self.setFont(theFont)
# Set default text margins # Set default text margins
# Due to cursor visibility, a part of the margin must be # Due to cursor visibility, a part of the margin must be
# allocated to the document itself. See issue #1112. # allocated to the document itself. See issue #1112.
cW = self.cursorWidth() cW = self.cursorWidth()
qDoc = self.document()
qDoc.setDocumentMargin(cW) qDoc.setDocumentMargin(cW)
self._vpMargin = max(CONFIG.getTextMargin() - cW, 0) self._vpMargin = max(CONFIG.getTextMargin() - cW, 0)
self.setViewportMargins(self._vpMargin, self._vpMargin, self._vpMargin, self._vpMargin) self.setViewportMargins(self._vpMargin, self._vpMargin, self._vpMargin, self._vpMargin)
+4 -7
View File
@@ -114,13 +114,10 @@ class GuiDocViewer(QTextBrowser):
self._makeStyleSheet() self._makeStyleSheet()
# Set Font # Set Font
theFont = QFont() textFont = QFont()
if CONFIG.textFont is None: textFont.setFamily(CONFIG.textFont)
# If none is defined, set the default back to config textFont.setPointSize(CONFIG.textSize)
CONFIG.textFont = self.document().defaultFont().family() self.setFont(textFont)
theFont.setFamily(CONFIG.textFont)
theFont.setPointSize(CONFIG.textSize)
self.setFont(theFont)
# Set the widget colours to match syntax theme # Set the widget colours to match syntax theme
mainPalette = self.palette() mainPalette = self.palette()
+4 -4
View File
@@ -107,7 +107,6 @@ class GuiTheme:
# =========== # ===========
# Init GUI Font # Init GUI Font
self.guiFontDB = QFontDatabase()
self._setGuiFont() self._setGuiFont()
# Load Themes # Load Themes
@@ -366,13 +365,14 @@ class GuiTheme:
"""Update the GUI's font style from settings. """Update the GUI's font style from settings.
""" """
theFont = QFont() theFont = QFont()
if CONFIG.guiFont not in self.guiFontDB.families(): fontDB = QFontDatabase()
if CONFIG.osWindows and "Arial" in self.guiFontDB.families(): if CONFIG.guiFont not in fontDB.families():
if CONFIG.osWindows and "Arial" in fontDB.families():
# On Windows we default to Arial if possible # On Windows we default to Arial if possible
theFont.setFamily("Arial") theFont.setFamily("Arial")
theFont.setPointSize(10) theFont.setPointSize(10)
else: else:
theFont = self.guiFontDB.systemFont(QFontDatabase.GeneralFont) theFont = fontDB.systemFont(QFontDatabase.GeneralFont)
CONFIG.guiFont = theFont.family() CONFIG.guiFont = theFont.family()
CONFIG.guiFontSize = theFont.pointSize() CONFIG.guiFontSize = theFont.pointSize()
else: else:
-3
View File
@@ -1258,9 +1258,6 @@ class GuiBuildNovelDocView(QTextBrowser):
)) ))
theFont = QFont() theFont = QFont()
if CONFIG.textFont is None:
# If none is defined, set the default back to config
CONFIG.textFont = self.document().defaultFont().family()
theFont.setFamily(CONFIG.textFont) theFont.setFamily(CONFIG.textFont)
theFont.setPointSize(CONFIG.textSize) theFont.setPointSize(CONFIG.textSize)
self.setFont(theFont) self.setFont(theFont)
+1 -3
View File
@@ -41,7 +41,7 @@ from PyQt5.QtWidgets import (
) )
from novelwriter import CONFIG from novelwriter import CONFIG
from novelwriter.constants import nwConst, nwHeadFmt from novelwriter.constants import nwHeadFmt
from novelwriter.core.buildsettings import BuildSettings, FilterMode from novelwriter.core.buildsettings import BuildSettings, FilterMode
from novelwriter.extensions.switch import NSwitch from novelwriter.extensions.switch import NSwitch
from novelwriter.extensions.switchbox import NSwitchBox from novelwriter.extensions.switchbox import NSwitchBox
@@ -1032,8 +1032,6 @@ class GuiBuildFormatTab(QWidget):
textFont = self._build.getStr("format.textFont") textFont = self._build.getStr("format.textFont")
if not textFont: if not textFont:
textFont = str(CONFIG.textFont) textFont = str(CONFIG.textFont)
if not textFont:
textFont = nwConst.SYSTEM_FONT
self.textFont.setText(textFont) self.textFont.setText(textFont)
self.textSize.setValue(self._build.getInt("format.textSize")) self.textSize.setValue(self._build.getInt("format.textSize"))
+1
View File
@@ -49,6 +49,7 @@ def resetConfigVars():
""" """
CONFIG.setLastPath(_TMP_ROOT) CONFIG.setLastPath(_TMP_ROOT)
CONFIG.setBackupPath(_TMP_ROOT) CONFIG.setBackupPath(_TMP_ROOT)
CONFIG.setTextFont(None)
CONFIG._homePath = _TMP_ROOT CONFIG._homePath = _TMP_ROOT
CONFIG.guiLocale = "en_GB" CONFIG.guiLocale = "en_GB"
return return
+2 -2
View File
@@ -1,5 +1,5 @@
[Meta] [Meta]
timestamp = 2022-11-11 12:48:18 timestamp = 2023-05-31 10:52:21
[Main] [Main]
theme = default theme = default
@@ -29,7 +29,7 @@ backuponclose = False
askbeforebackup = True askbeforebackup = True
[Editor] [Editor]
textfont = None textfont =
textsize = 12 textsize = 12
width = 700 width = 700
margin = 40 margin = 40
+1 -1
View File
@@ -56,7 +56,7 @@ def testGuiEditor_Init(qtbot, nwGUI, projPath, ipsumText, mockRnd):
assert nwGUI.docEditor._typPadChar == nwUnicode.U_NBSP assert nwGUI.docEditor._typPadChar == nwUnicode.U_NBSP
# Check that editor handles settings # Check that editor handles settings
CONFIG.textFont = None CONFIG.textFont = ""
CONFIG.doJustify = True CONFIG.doJustify = True
CONFIG.showTabsNSpaces = True CONFIG.showTabsNSpaces = True
CONFIG.showLineEndings = True CONFIG.showLineEndings = True