def __init__(self, config: Config) -> None: """ Main window with the GUI and whatever player is being used. """ super().__init__() self.setWindowTitle('vidify') # Setting the window to stay on top if config.stay_on_top: self.setWindowFlags(Qt.WindowStaysOnTopHint) # Setting the fullscreen and window size if config.fullscreen: self.showFullScreen() else: self.resize(config.width or 800, config.height or 600) self.layout = QHBoxLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.setSpacing(0) # Loading the used fonts (Inter) font_db = QFontDatabase() for font in Res.fonts: font_db.addApplicationFont(font) # Initializing the player and saving the config object in the window. self.player = initialize_player(config.player, config) logging.info("Using %s as the player", config.player) self.config = config # The audiosync feature is optional until it's more stable. if self.config.audiosync: from vidify.audiosync import AudiosyncWorker self.audiosync = AudiosyncWorker() else: self.audiosync = None # The API initialization is more complex. For more details, please # check the flow diagram in vidify.api. First we have to check if # the API is saved in the config: try: api_data = get_api_data(config.api) except KeyError: # Otherwise, the user is prompted for an API. After choosing one, # it will be initialized from outside this function. logging.info("API not found: prompting the user") self.API_selection = APISelection() self.layout.addWidget(self.API_selection) self.API_selection.api_chosen.connect(self.on_api_selection) else: logging.info("Using %s as the API", config.api) self.initialize_api(api_data)
def load_font(self, ttf_filename, charmap_filename): def hook(obj): result = {} for key in obj: result[key] = unichr(int(obj[key], 16)) return result if self.char_map is None: cache_key = ttf_filename + "|" + charmap_filename ttf_fname = os.path.join( os.path.dirname(os.path.realpath(__file__)), ttf_filename) font_id = QFontDatabase.addApplicationFont(ttf_fname) if font_id >= 0: font_families = QFontDatabase.applicationFontFamilies(font_id) else: cache = self.loaded_fonts.get(cache_key, None) if cache is None: raise OSError("Could not load ttf file for icon font.") else: self.char_map = cache['char_map'] self.font_name = cache['font_name'] return self.font_name = font_families[0] with open( os.path.join(os.path.dirname(os.path.realpath(__file__)), charmap_filename), 'r') as codes: self.char_map = json.load(codes, object_hook=hook) self.loaded_fonts[cache_key] = { 'char_map': self.char_map, 'font_name': self.font_name }
def load_font(self, ttf_filename, charmap_filename): def hook(obj): result = {} for key in obj: result[key] = unichr(int(obj[key], 16)) return result if self.char_map is None: cache_key = ttf_filename + "|" + charmap_filename ttf_fname = os.path.join(os.path.dirname(os.path.realpath(__file__)), ttf_filename) font_id = QFontDatabase.addApplicationFont(ttf_fname) if font_id >= 0: font_families = QFontDatabase.applicationFontFamilies(font_id) else: cache = self.loaded_fonts.get(cache_key, None) if cache is None: raise OSError("Could not load ttf file for icon font.") else: self.char_map = cache['char_map'] self.font_name = cache['font_name'] return self.font_name = font_families[0] with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), charmap_filename), 'r') as codes: self.char_map = json.load(codes, object_hook=hook) self.loaded_fonts[cache_key] = {'char_map': self.char_map, 'font_name': self.font_name}
def _test_imports(): print("start_test_import") from qtpy.QtWidgets import QApplication app = QApplication([]) from napari._qt.widgets.qt_console import QtConsole from PartSeg import plugins from PartSeg._launcher.main_window import MainWindow from PartSeg._roi_analysis.main_window import MainWindow as AnalysisMain from PartSeg._roi_mask.main_window import MainWindow as MaskMain from PartSeg.common_backend.base_argparser import _setup_sentry _setup_sentry() plugins.register() w1 = AnalysisMain("test") w2 = MaskMain("test") w3 = MainWindow("test") console = QtConsole() if QFontDatabase.addApplicationFont(os.path.join(font_dir, "Symbola.ttf")) == -1: raise ValueError("Error with loading Symbola font") del w1 del w2 del w3 del app del console print("end_test_import")
def loadFont(self, font_path): """Loads a font file into the font database. The path can specify the location of a font file or a qresource.""" LOG.debug("Loading custom font: %s" % font_path) res = QFontDatabase.addApplicationFont(font_path) if res != 0: LOG.error("Failed to load font: %s", font_path)
def addApplicationFont(self, font_path): """Loads a font file into the font database. The path can specify the location of a font file or a qresource.""" LOG.debug("Loading custom font: %s" % font_path) res = QFontDatabase.addApplicationFont(font_path) # per QT docs -1 is error and 0+ is index to font loaded for later use if res < 0: LOG.error("Failed to load font: %s", font_path)
def bootstrap(cfgmgr, theme='Breeze', aot=True, debug__no_scrcpy=False, hide_wm_frame=True): """ Launch the guiscrcpy window :return: """ config = cfgmgr.get_config() # enable High DPI scaling QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) # use HIGH DPI icons QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True) # init core app = QtWidgets.QApplication([]) # load fonts font_database = QFontDatabase() for font in FONTS: s = font_database.addApplicationFont( ':/font/fonts/{ttf}'.format(ttf=font)) if s == -1: # loading the font failed # https://doc.qt.io/qt-5/qfontdatabase.html print(fc("{y}Failed to load {ttf} font.{rst}", ttf=font)) # set theme app.setStyle(theme) # apply stylesheet if theme == 'Breeze': # The Qdarkstylesheet is based on Breeze, lets load them on default app.setStyleSheet(dark_stylesheet()) # load splash splash_pix = QPixmap(":/res/ui/guiscrcpy-branding.png") splash = QtWidgets.QSplashScreen(splash_pix) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # on windows, users are likely not to add the scrcpy-server to the # SCRCPY_SERVER_PATH cfgmgr.update_config(set_scrcpy_server_path(config)) cfgmgr.write_file() adb = AndroidDebugBridge(cfgmgr.get_config().get('adb')) scrcpy = ScrcpyBridge(cfgmgr.get_config().get('scrcpy')) cfgmgr['adb'] = adb.get_path() cfgmgr['scrcpy'] = scrcpy.get_path() guiscrcpy = InterfaceGuiscrcpy(cfgmgr=cfgmgr, adb=adb, scrcpy=scrcpy, force_window_frame=not hide_wm_frame, panels_not_always_on_top=not aot, debug__no_scrcpy=debug__no_scrcpy) guiscrcpy.show() app.processEvents() splash.hide() app.exec_()
def bootstrap( app: QtWidgets.QApplication, config_manager: InterfaceConfig, theme: str = "Breeze", aot: bool = True, debug_no_scrcpy: bool = False, hide_wm_frame: bool = True, ): """ Launch the guiscrcpy window :return: """ config = config_manager.get_config() # load fonts font_database = QFontDatabase() for font in FONTS: s = font_database.addApplicationFont( ":/font/fonts/{ttf}".format(ttf=font)) if s == -1: # loading the font failed # https://doc.qt.io/qt-5/qfontdatabase.html print(fc("{y}Failed to load {ttf} font.{rst}", ttf=font)) # set theme app.setStyle(theme) # apply stylesheet if theme == "Breeze": # The Qdarkstylesheet is based on Breeze, lets load them on default app.setStyleSheet(dark_stylesheet()) # load splash splash_pix = QPixmap(":/res/ui/guiscrcpy-branding.png") splash = QtWidgets.QSplashScreen(splash_pix) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # on windows, users are likely not to add the scrcpy-server to the # SCRCPY_SERVER_PATH config_manager.update_config(set_scrcpy_server_path(config)) config_manager.write_file() adb = AndroidDebugBridge(config_manager.get_config().get("adb")) scrcpy = ScrcpyBridge(config_manager.get_config().get("scrcpy")) config_manager["adb"] = adb.get_path() config_manager["scrcpy"] = scrcpy.get_path() guiscrcpy = InterfaceGuiscrcpy( config_manager=config_manager, adb=adb, scrcpy=scrcpy, force_window_frame=not hide_wm_frame, panels_not_always_on_top=not aot, debug_no_scrcpy=debug_no_scrcpy, ) guiscrcpy.show() app.processEvents() splash.hide() app.exec_()
def main(): app = QApplication(sys.argv) app.setWindowIcon(QIcon(':/icons/app.svg')) fontDB = QFontDatabase() fontDB.addApplicationFont(':/fonts/Roboto-Regular.ttf') app.setFont(QFont('Roboto')) f = QFile(':/style.qss') f.open(QFile.ReadOnly | QFile.Text) app.setStyleSheet(QTextStream(f).readAll()) f.close() translator = QTranslator() translator.load(':/translations/' + QLocale.system().name() + '.qm') app.installTranslator(translator) mw = MainWindow() mw.show() sys.exit(app.exec_())
def __init__(self, config: Config) -> None: """ Main window with the GUI and whatever player is being used. """ super().__init__() self.setWindowTitle('vidify') # Setting the window to stay on top if config.stay_on_top: self.setWindowFlags(Qt.WindowStaysOnTopHint) # Setting the fullscreen and window size if config.fullscreen: self.showFullScreen() else: self.setMinimumSize(800, 800) self.resize(config.width or 800, config.height or 800) # Loading the used fonts (Inter) font_db = QFontDatabase() for font in Res.fonts: font_db.addApplicationFont(font) # Initializing the player and saving the config object in the window. self.layout = QHBoxLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.setSpacing(0) self.config = config # Otherwise, the user is prompted for an API. After choosing one, # it will be initialized from outside this function. logging.info("Loading setup screen") self.setup_widget = SetupWidget(config.api, config.player) self.layout.addWidget(self.setup_widget) self.setup_widget.done.connect(self.on_setup_done) # Setting focus on the continue button after the first time. if None not in (config.api, config.player): self.setup_widget.continue_btn.setFocus()
def load_font(font_name, font_file): # NOTE: you need to have created a QApplication() first (see # qtw.Widgets.Application) for this to work correctly, or you will get # a crash! font_id = QFontDatabase.addApplicationFont(font_file) if font_id < 0: raise ValueError("Unspecified Qt problem loading font from '%s'" % ( font_file)) font_family = QFontDatabase.applicationFontFamilies(font_id)[0] if font_name != font_family: # If Qt knows this under a different name, add an alias font_asst.add_alias(font_name, font_family) return font_name
def load_font(font_name, font_file): # NOTE: you need to have created a QApplication() first (see # qtw.Widgets.Application) for this to work correctly, or you will get # a crash! font_id = QFontDatabase.addApplicationFont(font_file) if font_id < 0: raise ValueError("Unspecified Qt problem loading font from '%s'" % (font_file)) font_family = QFontDatabase.applicationFontFamilies(font_id)[0] if font_name != font_family: # If Qt knows this under a different name, add an alias font_asst.add_alias(font_name, font_family) return font_name
def start_ryven(): # import windows from MainConsole import init_main_console from startup_dialog.StartupDialog import StartupDialog from MainWindow import MainWindow # init application from qtpy.QtWidgets import QApplication app = QApplication(sys.argv) # register fonts from qtpy.QtGui import QFontDatabase db = QFontDatabase() db.addApplicationFont('../resources/fonts/poppins/Poppins-Medium.ttf') db.addApplicationFont('../resources/fonts/source_code_pro/SourceCodePro-Regular.ttf') db.addApplicationFont('../resources/fonts/asap/Asap-Regular.ttf') # StartupDialog sw = StartupDialog() sw.exec_() # exit if dialog couldn't initialize if sw.editor_startup_configuration == {}: sys.exit() window_theme = sw.window_theme # init main console console_stdout_redirect, \ console_errout_redirect = init_main_console(window_theme) # init main window mw = MainWindow(sw.editor_startup_configuration, window_theme) mw.show() if REDIRECT_CONSOLE_OUTPUT: # redirect console output from contextlib import redirect_stdout, redirect_stderr with redirect_stdout(console_stdout_redirect), \ redirect_stderr(console_errout_redirect): # run mw.print_info() sys.exit(app.exec_()) else: # run mw.print_info() sys.exit(app.exec_())
def _init_pyqt(self, exp): global app, font_database # Add the Qt plugin folders to the library path, if they exists. Where # these folders are depends on the version of Qt4, but these are two # possible locations. qt_plugin_path = os.path.join(os.path.dirname(sys.executable), 'Library', 'plugins') if os.path.isdir(qt_plugin_path): QCoreApplication.addLibraryPath( safe_decode(qt_plugin_path, enc=misc.filesystem_encoding())) qt_plugin_path = os.path.join(os.path.dirname(sys.executable), 'Library', 'lib', 'qt4', 'plugins') if os.path.isdir(qt_plugin_path): QCoreApplication.addLibraryPath( safe_decode(qt_plugin_path, enc=misc.filesystem_encoding())) # If no instance of QApplication exists, a segmentation fault seems to always # occur. So we create one. if QCoreApplication.instance() is None: app = QApplication([]) # Register the fonts bundled with OpenSesame if font_database is None: font_database = QFontDatabase() for font in FONTS: try: path = exp.resource(font + u'.ttf') except: warnings.warn(u'Font %s not found' % font) continue font_id = font_database.addApplicationFont(path) if font_id < 0: warnings.warn(u'Failed to load font %s' % font) continue font_families = font_database.applicationFontFamilies(font_id) if not font_families: warnings.warn(u'Font %s contains no families' % font) continue font_substitutions.append((font_families[0], font))
def load_font(self, prefix, ttf_filename, charmap_filename, directory=None): """Loads a font file and the associated charmap. If ``directory`` is None, the files will be looked for in ``./fonts/``. Parameters ---------- prefix: str Prefix string to be used when accessing a given font set ttf_filename: str Ttf font filename charmap_filename: str Charmap filename directory: str or None, optional Directory for font and charmap files """ def hook(obj): result = {} for key in obj: result[key] = unichr(int(obj[key], 16)) return result if directory is None: directory = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'fonts') with open(os.path.join(directory, charmap_filename), 'r') as codes: self.charmap[prefix] = json.load(codes, object_hook=hook) id_ = QFontDatabase.addApplicationFont(os.path.join(directory, ttf_filename)) loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_) if(loadedFontFamilies): self.fontname[prefix] = loadedFontFamilies[0] else: print('Font is empty')
def load_font(self, prefix, ttf_filename, charmap_filename, directory=None): """Loads a font file and the associated charmap. If ``directory`` is None, the files will be looked for in ``./fonts/``. Parameters ---------- prefix: str Prefix string to be used when accessing a given font set ttf_filename: str Ttf font filename charmap_filename: str Charmap filename directory: str or None, optional Directory for font and charmap files """ def hook(obj): result = {} for key in obj: result[key] = unichr(int(obj[key], 16)) return result if directory is None: directory = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'fonts') # Load font if QApplication.instance() is not None: id_ = QFontDatabase.addApplicationFont( os.path.join(directory, ttf_filename)) loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_) if (loadedFontFamilies): self.fontname[prefix] = loadedFontFamilies[0] else: raise FontError(u"Font at '{0}' appears to be empty. " "If you are on Windows 10, please read " "https://support.microsoft.com/" "en-us/kb/3053676 " "to know how to prevent Windows from blocking " "the fonts that come with QtAwesome.".format( os.path.join(directory, ttf_filename))) with open(os.path.join(directory, charmap_filename), 'r') as codes: self.charmap[prefix] = json.load(codes, object_hook=hook) # Verify that vendorized fonts are not corrupt if not SYSTEM_FONTS: md5_hashes = { 'fontawesome4.7-webfont.ttf': 'b06871f281fee6b241d60582ae9369b9', 'fontawesome5-regular-webfont.ttf': '0e2e26fb3527ae47f9eb1c217592b706', 'fontawesome5-solid-webfont.ttf': 'e143b57de78138e6d5963908afa7e393', 'fontawesome5-brands-webfont.ttf': 'dec02372212aab5a2e5294f1a11756ed', 'elusiveicons-webfont.ttf': '207966b04c032d5b873fd595a211582e', 'materialdesignicons-webfont.ttf': '023db9122f66b7d693bc52bcdf09e6b3' } ttf_hash = md5_hashes.get(ttf_filename, None) if ttf_hash is not None: hasher = hashlib.md5() with open(os.path.join(directory, ttf_filename), 'rb') as f: content = f.read() hasher.update(content) ttf_calculated_hash_code = hasher.hexdigest() if ttf_calculated_hash_code != ttf_hash: raise FontError(u"Font is corrupt at: '{0}'".format( os.path.join(directory, ttf_filename)))
from qtpy.QtCore import Slot, QRegExp from qtpy.QtGui import QFontDatabase, QRegExpValidator from qtpy.QtWidgets import QAbstractButton from qtpyvcp import actions from qtpyvcp.utilities import logger from qtpyvcp.widgets.form_widgets.main_window import VCPMainWindow import probe_basic_rc LOG = logger.getLogger('QtPyVCP.' + __name__) VCP_DIR = os.path.abspath(os.path.dirname(__file__)) # Add custom fonts QFontDatabase.addApplicationFont(os.path.join(VCP_DIR, 'fonts/BebasKai.ttf')) class ProbeBasic(VCPMainWindow): """Main window class for the ProbeBasic VCP.""" def __init__(self, *args, **kwargs): super(ProbeBasic, self).__init__(*args, **kwargs) self.run_from_line_Num.setValidator(QRegExpValidator(QRegExp("[0-9]*"))) self.dynatc_left.iniFilePrefix = "LEFT_" self.dynatc_right.iniFilePrefix = "RIGHT_" @Slot(QAbstractButton) def on_probetabGroup_buttonClicked(self, button): self.probe_tab_widget.setCurrentIndex(button.property('page')) @Slot(QAbstractButton) def on_guiaxisdisplayGroup_buttonClicked(self, button):
def main(): if len(sys.argv) > 1 and sys.argv[1] == "_test": _test_imports() return parser = CustomParser("PartSeg") parser.add_argument( "--multiprocessing-fork", dest="mf", action="store_true", help=argparse.SUPPRESS ) # Windows bug fix sp = parser.add_subparsers() sp_a = sp.add_parser("roi_analysis", help="Starts GUI for segmentation analysis") sp_s = sp.add_parser("mask_segmentation", help="Starts GUI for segmentation") parser.set_defaults(gui="launcher") sp_a.set_defaults(gui="roi_analysis") sp_s.set_defaults(gui="roi_mask") sp_a.add_argument("image", nargs="?", help="image to read on begin", default="") sp_a.add_argument("mask", nargs="?", help="mask to read on begin", default=None) sp_a.add_argument("--batch", action="store_true", help=argparse.SUPPRESS) sp_s.add_argument("image", nargs="?", help="image to read on begin", default="") argv = [x for x in sys.argv[1:] if not (x.startswith("parent") or x.startswith("pipe"))] args = parser.parse_args(argv) # print(args) logging.basicConfig(level=logging.INFO) CustomApplication.setAttribute(Qt.AA_EnableHighDpiScaling) my_app = CustomApplication(sys.argv, name="PartSeg", icon=os.path.join(icons_dir, "icon.png")) my_app.check_release() my_app.aboutToQuit.connect(wait_for_workers_to_quit) QFontDatabase.addApplicationFont(os.path.join(font_dir, "Symbola.ttf")) if args.gui == "roi_analysis" or args.mf: from PartSeg import plugins plugins.register() from PartSeg._roi_analysis.main_window import MainWindow title = f"{APP_NAME} {ANALYSIS_NAME}" if args.image: image = TiffImageReader.read_image(args.image, args.mask) MainWindow = partial(MainWindow, initial_image=image) wind = MainWindow(title=title) if args.batch: wind.main_menu.batch_window() elif args.gui == "roi_mask": from PartSeg import plugins plugins.register() from PartSeg._roi_mask.main_window import MainWindow title = f"{APP_NAME} {MASK_NAME}" if args.image: image = TiffImageReader.read_image(args.image) MainWindow = partial(MainWindow, initial_image=image) wind = MainWindow(title=title) else: from PartSeg._launcher.main_window import MainWindow title = f"{APP_NAME} Launcher" wind = MainWindow(title=title) wind.show() rc = my_app.exec_() del wind del my_app sys.exit(rc)
def load_font(self, prefix, ttf_filename, charmap_filename, directory=None): """Loads a font file and the associated charmap. If ``directory`` is None, the files will be looked for in ``./fonts/``. Parameters ---------- prefix: str Prefix string to be used when accessing a given font set ttf_filename: str Ttf font filename charmap_filename: str Charmap filename directory: str or None, optional Directory for font and charmap files """ def hook(obj): result = {} for key in obj: result[key] = unichr(int(obj[key], 16)) return result if directory is None: directory = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'fonts') # Load font if QApplication.instance() is not None: id_ = QFontDatabase.addApplicationFont( os.path.join(directory, ttf_filename)) loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_) if (loadedFontFamilies): self.fontname[prefix] = loadedFontFamilies[0] else: raise FontError(u"Font at '{0}' appears to be empty. " "If you are on Windows 10, please read " "https://support.microsoft.com/" "en-us/kb/3053676 " "to know how to prevent Windows from blocking " "the fonts that come with QtAwesome.".format( os.path.join(directory, ttf_filename))) with open(os.path.join(directory, charmap_filename), 'r') as codes: self.charmap[prefix] = json.load(codes, object_hook=hook) # Verify that vendorized fonts are not corrupt if not SYSTEM_FONTS: md5_hashes = { 'fontawesome4.7-webfont.ttf': 'b06871f281fee6b241d60582ae9369b9', 'fontawesome5-regular-webfont.ttf': '73fe7f1effbf382f499831a0a9f18626', 'fontawesome5-solid-webfont.ttf': '0079a0ab6bec4da7d6e16f2a2e87cd71', 'fontawesome5-brands-webfont.ttf': '947b9537bc0fecc8130d48eb753495a1', 'elusiveicons-webfont.ttf': '207966b04c032d5b873fd595a211582e', 'materialdesignicons-webfont.ttf': '64b96825d49e070ea87c7100f2db3f46' } ttf_hash = md5_hashes.get(ttf_filename, None) if ttf_hash is not None: hasher = hashlib.md5() with open(os.path.join(directory, ttf_filename), 'rb') as f: content = f.read() hasher.update(content) ttf_calculated_hash_code = hasher.hexdigest() if ttf_calculated_hash_code != ttf_hash: raise FontError(u"Font is corrupt at: '{0}'".format( os.path.join(directory, ttf_filename)))
def load_font(self, prefix, ttf_filename, charmap_filename, directory=None): """Loads a font file and the associated charmap. If ``directory`` is None, the files will be looked for in ``./fonts/``. Parameters ---------- prefix: str Prefix string to be used when accessing a given font set ttf_filename: str Ttf font filename charmap_filename: str Charmap filename directory: str or None, optional Directory for font and charmap files """ def hook(obj): result = {} for key in obj: result[key] = unichr(int(obj[key], 16)) return result if directory is None: directory = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'fonts') # Load font if QApplication.instance() is not None: id_ = QFontDatabase.addApplicationFont( os.path.join(directory, ttf_filename)) loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_) if (loadedFontFamilies): self.fontname[prefix] = loadedFontFamilies[0] else: raise FontError(u"Font at '{0}' appears to be empty. " "If you are on Windows 10, please read " "https://support.microsoft.com/" "en-us/kb/3053676 " "to know how to prevent Windows from blocking " "the fonts that come with QtAwesome.".format( os.path.join(directory, ttf_filename))) with open(os.path.join(directory, charmap_filename), 'r') as codes: self.charmap[prefix] = json.load(codes, object_hook=hook) # Verify that vendorized fonts are not corrupt if not SYSTEM_FONTS: md5_hashes = { 'fontawesome-webfont.ttf': 'a3de2170e4e9df77161ea5d3f31b2668', 'elusiveicons-webfont.ttf': '207966b04c032d5b873fd595a211582e' } ttf_hash = md5_hashes.get(ttf_filename, None) if ttf_hash is not None: hasher = hashlib.md5() with open(os.path.join(directory, ttf_filename), 'rb') as f: content = f.read() hasher.update(content) ttf_calculated_hash_code = hasher.hexdigest() if ttf_calculated_hash_code != ttf_hash: raise FontError(u"Font is corrupt at: '{0}'".format( os.path.join(directory, ttf_filename)))
def load_font(self, prefix, ttf_filename, charmap_filename, directory=None): """Loads a font file and the associated charmap. If ``directory`` is None, the files will be looked for in ``./fonts/``. Parameters ---------- prefix: str Prefix string to be used when accessing a given font set ttf_filename: str Ttf font filename charmap_filename: str Charmap filename directory: str or None, optional Directory for font and charmap files """ def hook(obj): result = {} for key in obj: try: result[key] = unichr(int(obj[key], 16)) except ValueError: if int(obj[key], 16) > 0xffff: # ignoring unsupported code in Python 2.7 32bit Windows # ValueError: unichr() arg not in range(0x10000) warnings.warn("Your Python version doesn't support " "character {0}:{1}".format( key, obj[key])) else: raise FontError(u'Failed to load character ' '{0}:{1}'.format(key, obj[key])) return result if directory is None: directory = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'fonts') # Load font if QApplication.instance() is not None: id_ = QFontDatabase.addApplicationFont( os.path.join(directory, ttf_filename)) loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_) if (loadedFontFamilies): self.fontname[prefix] = loadedFontFamilies[0] else: raise FontError(u"Font at '{0}' appears to be empty. " "If you are on Windows 10, please read " "https://support.microsoft.com/" "en-us/kb/3053676 " "to know how to prevent Windows from blocking " "the fonts that come with QtAwesome.".format( os.path.join(directory, ttf_filename))) with open(os.path.join(directory, charmap_filename), 'r') as codes: self.charmap[prefix] = json.load(codes, object_hook=hook) # Verify that vendorized fonts are not corrupt if not SYSTEM_FONTS: ttf_hash = MD5_HASHES.get(ttf_filename, None) if ttf_hash is not None: hasher = hashlib.md5() with open(os.path.join(directory, ttf_filename), 'rb') as f: content = f.read() hasher.update(content) ttf_calculated_hash_code = hasher.hexdigest() if ttf_calculated_hash_code != ttf_hash: raise FontError(u"Font is corrupt at: '{0}'".format( os.path.join(directory, ttf_filename)))