From 0618fff03cc23fa8599c1f191f6f4969c10e37d2 Mon Sep 17 00:00:00 2001 From: Oren Date: Sat, 1 Mar 2025 18:34:17 +0200 Subject: [PATCH] Cache font-ids that were already loaded `get_font_id` also saves the trouble of specifying the entire path of the fonts. --- electrum/gui/common_qt/util.py | 16 +++++++++++++++- electrum/gui/qml/qeapp.py | 7 ++++--- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/electrum/gui/common_qt/util.py b/electrum/gui/common_qt/util.py index ef3d07e46..11d06a913 100644 --- a/electrum/gui/common_qt/util.py +++ b/electrum/gui/common_qt/util.py @@ -1,13 +1,27 @@ from typing import Optional +import os.path from PyQt6 import QtGui from PyQt6.QtCore import Qt -from PyQt6.QtGui import QColor, QPen, QPaintDevice +from PyQt6.QtGui import QColor, QPen, QPaintDevice, QFontDatabase import qrcode from electrum.i18n import _ +_cached_font_ids: dict[str, int] = {} + +def get_font_id(filename: str) -> int: + font_id = _cached_font_ids.get(filename) + if font_id is not None: + return font_id + # font_id will be negative on error + font_id = QFontDatabase.addApplicationFont( + os.path.join(os.path.dirname(__file__), '..', 'fonts', filename) + ) + _cached_font_ids[filename] = font_id + return font_id + def draw_qr( *, qr: Optional[qrcode.main.QRCode], diff --git a/electrum/gui/qml/qeapp.py b/electrum/gui/qml/qeapp.py index 2f5108dda..b6dfb2f1f 100644 --- a/electrum/gui/qml/qeapp.py +++ b/electrum/gui/qml/qeapp.py @@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, Set from PyQt6.QtCore import (pyqtSlot, pyqtSignal, pyqtProperty, QObject, QT_VERSION_STR, PYQT_VERSION_STR, qInstallMessageHandler, QTimer, QSortFilterProxyModel) -from PyQt6.QtGui import QGuiApplication, QFontDatabase +from PyQt6.QtGui import QGuiApplication from PyQt6.QtQml import qmlRegisterType, QQmlApplicationEngine import electrum @@ -20,6 +20,7 @@ from electrum.bip21 import BITCOIN_BIP21_URI_SCHEME, LIGHTNING_URI_SCHEME from electrum.base_crash_reporter import BaseCrashReporter, EarlyExceptionsQueue from electrum.network import Network from electrum.plugin import run_hook +from electrum.gui.common_qt.util import get_font_id from .qeconfig import QEConfig from .qedaemon import QEDaemon @@ -426,8 +427,8 @@ class ElectrumQmlApplication(QGuiApplication): # add a monospace font as we can't rely on device having one self.fixedFont = 'PT Mono' - not_loaded = QFontDatabase.addApplicationFont('electrum/gui/fonts/PTMono-Regular.ttf') < 0 - not_loaded = QFontDatabase.addApplicationFont('electrum/gui/fonts/PTMono-Bold.ttf') < 0 and not_loaded + not_loaded = get_font_id('PTMono-Regular.ttf') < 0 + not_loaded = get_font_id('PTMono-Bold.ttf') < 0 and not_loaded if not_loaded: self.logger.warning('Could not load font PT Mono') self.fixedFont = 'Monospace' # hope for the best