def compile_imgs(): media_dir = hpxbuilder_utils.get_hprox_media_dir_path() hprox_dir = hpxbuilder_utils.get_hpqt_dir() qrc_files = [os.path.join(media_dir, 'images', 'images.qrc')] hpximg_file = os.path.join(hprox_dir, 'hpximg.py') processResourceFile(qrc_files, hpximg_file, False)
def pyrcc(c): """Compiles *.qrc files found in ASSETS_DIR into .py files in COMPILED_DIR""" from PyQt5.pyrcc_main import processResourceFile for path in ASSETS_DIR.glob('*.qrc'): target_path = COMPILED_DIR / path.with_suffix('.py').name print(f'Compiling {path.name} to {target_path}') processResourceFile([str(path)], str(target_path), False)
def build_resource_file(): """Compiles app and editor icons into Qt resource file""" resource_file = os.path.join(PROJECT_PATH, 'sscanss', '__resource.py') if os.path.isfile(resource_file): os.remove(resource_file) processResourceFile([os.path.join(INSTALLER_PATH, 'icons', 'images.qrc')], resource_file, False)
def run(self): fix_pyqt_import() try: from PyQt5.pyrcc_main import processResourceFile self.announce("Generating `parsec.core.gui._resources_rc`", level=distutils.log.INFO) processResourceFile( ["parsec/core/gui/rc/resources.qrc"], "parsec/core/gui/_resources_rc.py", False ) except ImportError: print("PyQt5 not installed, skipping `parsec.core.gui._resources_rc` generation.")
def gen_qrc(): for file in listdir('.'): if not file.endswith('.qrc'): continue target_name = re.sub(r"([\w ]+)\.qrc", r"\1_rc.py", file) processResourceFile([file], target_name, False) with open(target_name, 'r+', encoding='utf-8') as f: script_new = f.read().replace( "from PyQt5 import QtCore", "from core.QtModules import QtCore", ) f.seek(0) f.truncate() f.write(script_new)
def compile_rc(files, dst, force=False): """ Compile a list of Qt Designer resource files (qrc) `files` to a python module (`dst`). Similar to ``compile_ui`` this is a convenient wrapper around ``PyQt5.pyrcc_main``. Target will not be overwritten if it's newer than all of the input qrc files unless `force` is set to True. Input argument (`files`) can either be a string (for a single qrc file) or a list of strings (for many qrc files). Note that if you are using qrc file with Qt Designer target module MUST end in `_rc` unless a different suffix has been specified when invoking ``compile_ui``. So if a UI file (`sample.ui`) is to be compiled into a python module (`sample.py`) and makes use of a resources files (`sample.rc`) the following snippet will ensure that these are in sync when the module is loaded (using the default options). >>> from os.path import join, dirname >>> from arc1pyqt.modutils import compile_ui, compile_rc >>> # get directory of present module >>> THIS_DIR = dirname(__file__) >>> # and compile it >>> compile_ui(join(THIS_DIR, 'sample.ui'), join(THIS_DIR, 'sample.py')) >>> compile_rc(join(THIS_DIR, 'sample.qrc'), join(THIS_DIR, 'sample_rc.py')) >>> # module sample now exists and its resources are loaded properly >>> from .sample import * """ from collections.abc import Iterable import PyQt5.pyrcc_main as rcc # ensure `files` is a list if not isinstance(files, Iterable) or isinstance(files, str): files = [files] overwrite = False if os.path.exists(dst) and not force: dst_mtime = os.path.getmtime(dst) for f in files: src_mtime = os.path.getmtime(f) # check if rc file is newer than destination if src_mtime > dst_mtime: # if yes, destination must be recreated overwrite = True break else: overwrite = True if overwrite: rcc.processResourceFile(files, dst, False)
def gen_qrc(): count = 0 for root, _, files in walk("pyslvs_ui"): for file in files: if not file.endswith('.qrc'): continue target_name = re.sub(r"([\w ]+)\.qrc", r"\1_rc.py", file) processResourceFile([join(root, file).replace('\\', '/')], join(root, target_name), False) with open(join(root, target_name), 'r+', encoding='utf-8') as f: script_new = f.read().replace("from PyQt5 import", "from qtpy import") f.seek(0) f.truncate() f.write(script_new) count += 1 print(f"Compiled {count} resource file(s)")
def build_qt_resources(): print('Compiling resources...') try: from PyQt5 import pyrcc_main except ImportError as e: raise Exception("Building from source requires PyQt5") from e pyrcc_main.processResourceFile(['cutelog/resources/resources.qrc'], 'cutelog/resources.py', False) # Rewrite PyQt5 import statements to qtpy with open('cutelog/resources.py', 'r') as rf: lines = rf.readlines() for i, line in enumerate(lines): if 'import' in line and not line.startswith('\\x'): new_line = line.replace('PyQt5', 'qtpy') lines[i] = new_line with open('cutelog/resources.py', 'w') as wf: wf.writelines(lines) print('Resources compiled successfully')
def _compile_qrc_pyqt5(qrc) -> bytes: """Compile qrc file using the PyQt5 method. PyQt5 compiles qrc files using a direct function from the shared library PyQt5.pyrcc. They provide access via a helper function in `pyrcc_main`. """ from PyQt5.pyrcc_main import processResourceFile # could not capture stdout no matter what I tried, so using a temp file. # need to do it this way instead of context manager because of windows' # handling of "shared" temporary files. tf = NamedTemporaryFile(suffix='.py', delete=False) try: tf.close() processResourceFile([qrc], tf.name, False) out = Path(tf.name).read_bytes() finally: os.unlink(tf.name) return out
def update_qrc(): """ Conditionally updates the qrc file from QML and dependent resources. :return: True, if file was successfully updated or update is not required, else None """ file_types = 'qml qrc js ttf otf svg qm png'.split() last_modification = max( map( getmtime, chain( *( file_ for file_ in ( iglob(join( abspath(dirname(__file__)), '{base_path}/**/*.{file_type}'.format( file_type=file_type, base_path=base_path) ), recursive=True ) for file_type in file_types) ) ) ) ) if exists(RESOURCES_FILE) and (last_modification - getmtime(RESOURCES_FILE)) < 2: return True if exists(RESOURCES_FILE) and not access(RESOURCES_FILE, W_OK): print('Resources file {} is outdated.'.format( RESOURCES_FILE ), file=sys.stderr) return True print('Change in UI files detected, recompiling resources.py...', file=sys.stderr) try: open(RESOURCES_FILE, 'w') except PermissionError: print('Resources file {} not exists and is not writable, please call with write permissions.'.format( RESOURCES_FILE ), file=sys.stderr) return False from PyQt5.pyrcc_main import processResourceFile if processResourceFile([QRC_FILE], RESOURCES_FILE, False): print('Resources.py successfully recompiled.', file=sys.stderr) return True print('Problem with compiling resources.py.', file=sys.stderr)
def write_resources( path_qrc: Path, path_rcpy: Path, dir_themes: Path = None, ): """Create a ``.qrc`` and a ``_rc.py`` file for your project containing all themes’ icons. Make sure your icon themes have an index.theme (We have a function for creating them!). :param path_qrc: A path to a ``.qrc`` file to write. Usually directly in the project directory. :param path_rcpy: A path to a compiled python file containing the resources. Usually ``*_rc.py``. :param dir_themes: A directory containing freedesktop icon themes with the necessary icons for your application. The default is ``{}`` next to ``path_qrc``. Needs to be next to or below ``path_qrc``. """.format(PATH_ICON_THEME) warn_suffix(path_qrc, '.qrc') warn_suffix(path_rcpy, '.py') dir_project = path_qrc.parent if dir_themes is None: dir_themes = dir_project / PATH_ICON_THEME if not dir_themes.is_absolute(): dir_themes = dir_project / dir_themes if dir_project not in dir_themes.parents: raise ValueError( 'path_qrc needs to be in a parent directory of dir_themes') files = [] for dir_theme in dir_themes.iterdir(): path_index = dir_theme / 'index.theme' from .theme_index import write_theme_indices ensure_is_file(path_index, write_theme_indices.__name__) files.append(template_qrc_file(path_index.relative_to(dir_project))) for _, size_dir in size_dirs(dir_theme): for sec in size_dir.iterdir(): for icon in sec.iterdir(): files.append( template_qrc_file(icon.relative_to(dir_project))) logger.info('Creating QRC file: %s', path_qrc) path_qrc.parent.mkdir(parents=True, exist_ok=True) with path_qrc.open('wt', encoding='utf-8') as qrc: qrc.write(template_qrc('\n'.join(files))) logger.info('Creating RC.py file %s from %s', path_rcpy, path_qrc) path_rcpy.parent.mkdir(parents=True, exist_ok=True) if not processResourceFile([str(path_qrc)], str(path_rcpy), False): raise OSError('Error during processing of resource file')
def run(self): build_py.run(self) try: from PyQt5 import pyrcc_main if not pyrcc_main.processResourceFile(['icons.qrc'], 'build/lib/electrum_sparks/gui/qt/icons_rc.py', False): raise RuntimeError('Failed to generate icons_rc.py') except ImportError: import subprocess subprocess.run(['pyrcc5', 'icons.qrc', '-o', 'build/lib/electrum_sparks/gui/qt/icons_rc.py']) with open('build/lib/electrum_sparks/version.py', 'r+') as fp: verfile = fp.readlines() verfile[0] = "ELECTRUM_VERSION = '{}'\n".format( version.ELECTRUM_VERSION) fp.seek(0) fp.writelines(verfile) fp.truncate()
PKG_NAME = 'gis4wrf' THIS_DIR = os.path.abspath(os.path.dirname(__file__)) PKG_DIR = os.path.join(THIS_DIR, PKG_NAME) ZIP_FILE = PKG_DIR + '.zip' # All entries will be interpreted with wildcards around them ZIP_EXCLUDES = ['__pycache__', '.gif'] # Create QT resources file QT_RESOURCES_DIR = os.path.join(PKG_DIR, 'plugin', 'resources') QT_RESOURCES = glob.glob(os.path.join(QT_RESOURCES_DIR, '*.qrc')) PYQT_RESOURCE_FILE = os.path.join(QT_RESOURCES_DIR, 'resources.py') if not pyrcc.processResourceFile( QT_RESOURCES, PYQT_RESOURCE_FILE, listFiles=False): print('Error creating PyQT resources file', file=sys.stderr) sys.exit(1) # Symlink plugin into QGIS plugins folder if platform.system() == 'Windows' or platform.system() == 'Darwin': PLATFORM = platform.system() HOME = os.path.expanduser('~') if PLATFORM == 'Windows': QGIS_PLUGINS_DIR = os.path.join( HOME, 'AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins') elif PLATFORM == 'Darwin': QGIS_PLUGINS_DIR = os.path.join( HOME, 'Library/Application Support/QGIS/QGIS3/profiles/default/python/plugins'
def run(self): processResourceFile([os.path.join('src', 'ads.qrc')], os.path.join(SRC_PATH, 'rc.py'), False)
def build_qt_resources(): print('Compiling resources...') from PyQt5 import pyrcc_main pyrcc_main.processResourceFile(['cutelog/resources/resources.qrc'], 'cutelog/resources.py', False) print('Resources compiled successfully')
import sys import os from PyQt5.pyrcc_main import processResourceFile icons_qrc = sys.argv[1] py_file = os.path.abspath(sys.argv[2]) # make paths relative for pyrcc os.chdir(os.path.dirname(icons_qrc)) icons_qrc = os.path.basename(icons_qrc) processResourceFile([icons_qrc], py_file, False)