Esempio n. 1
0
def check(cmd, mf):
    m = mf.findNode("PyQt5")
    if m and not isinstance(m, MissingModule):
        try:
            # PyQt5 with sipconfig module, handled
            # by sip recipe
            import sipconfig  # noqa: F401

            return None

        except ImportError:
            pass

        try:
            import PyQt5
            from PyQt5.QtCore import QLibraryInfo
        except ImportError:
            # PyQt5 in the graph, but not installed
            return None

        # All imports are done from C code, hence not visible
        # for modulegraph
        # 1. Use of 'sip'
        # 2. Use of other modules, datafiles and C libraries
        #    in the PyQt5 package.
        try:
            mf.import_hook("PyQt5.sip", m)
        except ImportError:
            mf.import_hook("sip", m, level=1)

        qtdir = QLibraryInfo.location(QLibraryInfo.LibrariesPath)
        if os.path.relpath(qtdir, os.path.dirname(PyQt5.__file__)).startswith("../"):
            # Qt5's prefix is not the PyQt5 package, which means
            # the "packages" directive below won't include everything
            # needed, and in particular won't include the plugins
            # folder.
            print("System install of Qt5")

            # Ensure that the Qt plugins are copied into the "Contents/plugins"
            # folder, that's where the bundles Qt expects them to be
            extra = {
                "resources": [("..", [QLibraryInfo.location(QLibraryInfo.PluginsPath)])]
            }

        else:
            extra = {}

        if sys.version[0] != 2:
            result = {
                "packages": ["PyQt5"],
                "expected_missing_imports": {"copy_reg", "cStringIO", "StringIO"},
            }
            result.update(extra)
            return result
        else:
            result = {"packages": ["PyQt5"]}
            result.update(extra)
            return result

    return None
Esempio n. 2
0
def run() -> None:
    import sys

    app: QApplication = QApplication(sys.argv)

    languages: Set[str] = set(
        QLocale().uiLanguages() +
        [QLocale().bcp47Name(), QLocale().name()])
    language: str
    qt_translator: QTranslator = QTranslator()
    for language in languages:
        if qt_translator.load(
                'qt_' + language,
                QLibraryInfo.location(QLibraryInfo.TranslationsPath)):
            app.installTranslator(qt_translator)
            break
    qtbase_translator: QTranslator = QTranslator()
    for language in languages:
        if qtbase_translator.load(
                'qtbase_' + language,
                QLibraryInfo.location(QLibraryInfo.TranslationsPath)):
            app.installTranslator(qtbase_translator)
            break

    window: MainWindow = MainWindow(application=app)
    argv: str
    for argv in sys.argv[1:]:
        if window.load_file(QUrl(argv).path()):
            break
    window.show()
    app.exec()
Esempio n. 3
0
    def config(self):
        if self.packages is not None:
            print("packages", self.packages)
            return self.packages

        import sipconfig, os

        try:
            from PyQt4 import pyqtconfig

            cfg = pyqtconfig.Configuration()
            qtdir = cfg.qt_lib_dir
            sipdir = os.path.dirname(cfg.pyqt_mod_dir)
            self.plugin_dir = os.path.join(cfg.qt_dir, 'plugins')
        except ImportError:
            from PyQt5.QtCore import QLibraryInfo

            qtdir = QLibraryInfo.location(QLibraryInfo.LibrariesPath)
            self.plugin_dir = QLibraryInfo.location(QLibraryInfo.PluginsPath)
            sipdir = os.path.dirname(sipconfig.__file__)

        if not os.path.exists(qtdir):
            print("sip: Qtdir %r does not exist"%(qtdir))
            # half-broken installation? ignore.
            raise ImportError

        # Qt is GHETTO!
        dyld_library_path = os.environ.get('DYLD_LIBRARY_PATH', '').split(':')

        if qtdir not in dyld_library_path:
            dyld_library_path.insert(0, qtdir)
            os.environ['DYLD_LIBRARY_PATH'] = ':'.join(dyld_library_path)

        self.packages = set()

        for fn in os.listdir(sipdir):
            fullpath = os.path.join(sipdir, fn)
            if os.path.isdir(fullpath):
                self.packages.add(fn)
                if fn in ('PyQt4', 'PyQt5'):
                    # PyQt4 and later has a nested structure, also import
                    # subpackage to ensure everything get seen.
                    for sub in os.listdir(fullpath):
                        if ".py" not in sub:
                            self.packages.add('%s.%s'%(fn, sub.replace(".so","")))

        # Causes a python3-related syntax error (metaclass keyword),
        # and you probably don't need it:
        #if "PyQt4.uic" in self.packages and sys.version_info.major != 3:
        #    print("WARNING: PyQt uic module found.")
        #    print("avoid python3 metaclass syntax errors by adding 'PyQt4.uic' to your excludes option.")
        print("sip: packages: %s"%(self.packages,))

        return self.packages
Esempio n. 4
0
def version():
    """Return a string with various version informations."""
    lines = ["qutebrowser v{}".format(qutebrowser.__version__)]
    gitver = _git_str()
    if gitver is not None:
        lines.append("Git commit: {}".format(gitver))

    lines.append("Backend: {}".format(_backend()))

    lines += [
        '',
        '{}: {}'.format(platform.python_implementation(),
                        platform.python_version()),
        'Qt: {}'.format(qt_version()),
        'PyQt: {}'.format(PYQT_VERSION_STR),
        '',
    ]

    lines += _module_versions()

    lines += ['pdf.js: {}'.format(_pdfjs_version())]

    lines += [
        'SSL: {}'.format(QSslSocket.sslLibraryVersionString()),
        '',
    ]

    qapp = QApplication.instance()
    if qapp:
        style = qapp.style()
        lines.append('Style: {}'.format(style.metaObject().className()))

    importpath = os.path.dirname(os.path.abspath(qutebrowser.__file__))

    lines += [
        'Platform: {}, {}'.format(platform.platform(),
                                  platform.architecture()[0]),
        'Frozen: {}'.format(hasattr(sys, 'frozen')),
        "Imported from {}".format(importpath),
        "Qt library executable path: {}, data path: {}".format(
            QLibraryInfo.location(QLibraryInfo.LibraryExecutablesPath),
            QLibraryInfo.location(QLibraryInfo.DataPath)
        )
    ]
    lines += _os_info()

    lines += [
        '',
        'Paths:',
    ]
    for name, path in _path_info().items():
        lines += ['{}: {}'.format(name, path)]

    return '\n'.join(lines)
Esempio n. 5
0
def version():
    """Return a string with various version informations."""
    lines = ["qutebrowser v{}".format(qutebrowser.__version__)]
    gitver = _git_str()
    if gitver is not None:
        lines.append("Git commit: {}".format(gitver))

    lines.append("Backend: {}".format(_backend()))

    lines += [
        '',
        '{}: {}'.format(platform.python_implementation(),
                        platform.python_version()),
        'Qt: {}'.format(qt_version()),
        'PyQt: {}'.format(PYQT_VERSION_STR),
        '',
    ]

    lines += _module_versions()

    lines += ['pdf.js: {}'.format(_pdfjs_version())]

    lines += [
        'SSL: {}'.format(QSslSocket.sslLibraryVersionString()),
        '',
    ]

    qapp = QApplication.instance()
    if qapp:
        style = qapp.style()
        lines.append('Style: {}'.format(style.metaObject().className()))

    importpath = os.path.dirname(os.path.abspath(qutebrowser.__file__))

    lines += [
        'Platform: {}, {}'.format(platform.platform(),
                                  platform.architecture()[0]),
        'Frozen: {}'.format(hasattr(sys, 'frozen')),
        "Imported from {}".format(importpath),
        "Qt library executable path: {}, data path: {}".format(
            QLibraryInfo.location(QLibraryInfo.LibraryExecutablesPath),
            QLibraryInfo.location(QLibraryInfo.DataPath)
        )
    ]
    lines += _os_info()

    lines += [
        '',
        'Paths:',
    ]
    for name, path in _path_info().items():
        lines += ['{}: {}'.format(name, path)]

    return '\n'.join(lines)
Esempio n. 6
0
    def config(self):
        if self.packages is not None:
            print("packages", self.packages)
            return self.packages

        import os

        import sipconfig

        try:
            from PyQt4 import pyqtconfig

            cfg = pyqtconfig.Configuration()
            qtdir = cfg.qt_lib_dir
            sipdir = os.path.dirname(cfg.pyqt_mod_dir)
            self.plugin_dir = os.path.join(cfg.qt_dir, "plugins")
        except ImportError:
            from PyQt5.QtCore import QLibraryInfo

            qtdir = QLibraryInfo.location(QLibraryInfo.LibrariesPath)
            self.plugin_dir = QLibraryInfo.location(QLibraryInfo.PluginsPath)
            sipdir = os.path.dirname(sipconfig.__file__)

        if not os.path.exists(qtdir):
            print("sip: Qtdir %r does not exist" % (qtdir))
            # half-broken installation? ignore.
            raise ImportError

        # Qt is GHETTO!
        # This looks wrong, setting DYLD_LIBRARY_PATH should not be needed!
        dyld_library_path = os.environ.get("DYLD_LIBRARY_PATH", "").split(":")

        if qtdir not in dyld_library_path:
            dyld_library_path.insert(0, qtdir)
            os.environ["DYLD_LIBRARY_PATH"] = ":".join(dyld_library_path)

        self.packages = set()

        for fn in os.listdir(sipdir):
            fullpath = os.path.join(sipdir, fn)
            if os.path.isdir(fullpath):
                self.packages.add(fn)
                if fn in ("PyQt4", "PyQt5"):
                    # PyQt4 and later has a nested structure, also import
                    # subpackage to ensure everything get seen.
                    for sub in os.listdir(fullpath):
                        if ".py" not in sub:
                            self.packages.add("{}.{}".format(
                                fn, sub.replace(".so", "")))

        print(f"sip: packages: {self.packages}")

        return self.packages
Esempio n. 7
0
def version():
    """Return a string with various version information."""
    lines = ["luminos v{}".format(luminos.__version__)]

    lines.append("Backend: {}".format(_backend()))

    lines += [
        '',
        '{}: {}'.format(platform.python_implementation(),
                        platform.python_version()),
        'Qt: {}'.format(constants.qt_version()),
        'PyQt: {}'.format(PYQT_VERSION_STR),
        '',
    ]

    lines += [
        'QtNetwork SSL: {}\n'.format(QSslSocket.sslLibraryVersionString()
                                     if QSslSocket.supportsSsl() else 'no'),
    ]

    lapp = QApplication.instance()
    if lapp:
        style = lapp.style()
        lines.append('Style: {}'.format(style.metaObject().className()))

    importpath = os.path.dirname(os.path.abspath(luminos.__file__))

    lines += [
        'Platform: {}, {}'.format(platform.platform(),
                                  platform.architecture()[0]),
    ]
    dist = distribution()
    if dist is not None:
        lines += [
            'Linux distribution: {} ({})'.format(dist.pretty, dist.parsed.name)
        ]

    lines += [
        'Frozen: {}'.format(hasattr(sys, 'frozen')),
        "Imported from {}".format(importpath),
        "Using Python from {}".format(sys.executable),
        "Qt library executable path: {}, data path: {}".format(
            QLibraryInfo.location(QLibraryInfo.LibraryExecutablesPath),
            QLibraryInfo.location(QLibraryInfo.DataPath)
        )
    ]

    if not dist or dist.parsed == Distribution.unknown:
        lines += _os_info()

    return '\n'.join(lines)
Esempio n. 8
0
    def config(self):
        if self.packages is not None:
            print("packages", self.packages)
            return self.packages

        import sipconfig
        import os

        try:
            from PyQt4 import pyqtconfig

            cfg = pyqtconfig.Configuration()
            qtdir = cfg.qt_lib_dir
            sipdir = os.path.dirname(cfg.pyqt_mod_dir)
            self.plugin_dir = os.path.join(cfg.qt_dir, 'plugins')
        except ImportError:
            from PyQt5.QtCore import QLibraryInfo

            qtdir = QLibraryInfo.location(QLibraryInfo.LibrariesPath)
            self.plugin_dir = QLibraryInfo.location(QLibraryInfo.PluginsPath)
            sipdir = os.path.dirname(sipconfig.__file__)

        if not os.path.exists(qtdir):
            print("sip: Qtdir %r does not exist" % (qtdir))
            # half-broken installation? ignore.
            raise ImportError

        # Qt is GHETTO!
        dyld_library_path = os.environ.get('DYLD_LIBRARY_PATH', '').split(':')

        if qtdir not in dyld_library_path:
            dyld_library_path.insert(0, qtdir)
            os.environ['DYLD_LIBRARY_PATH'] = ':'.join(dyld_library_path)

        self.packages = set()

        for fn in os.listdir(sipdir):
            fullpath = os.path.join(sipdir, fn)
            if os.path.isdir(fullpath):
                self.packages.add(fn)
                if fn in ('PyQt4', 'PyQt5'):
                    # PyQt4 and later has a nested structure, also import
                    # subpackage to ensure everything get seen.
                    for sub in os.listdir(fullpath):
                        if ".py" not in sub:
                            self.packages.add('%s.%s' %
                                              (fn, sub.replace(".so", "")))

        print("sip: packages: %s" % (self.packages, ))

        return self.packages
Esempio n. 9
0
def main():
    parser = argparse.ArgumentParser(
        description='A tool to crop pdf handout with multiple pages per sheet.'
    )
    parser.add_argument("fileInput",
                        metavar='FILE',
                        nargs='?',
                        default="",
                        help='input file')
    parser.add_argument(
        "-o",
        "--output",
        default="",
        help='auto detect and save to OUTPUT file without showing GUI')
    args = parser.parse_args()

    if args.output:
        return commandline(args)
    else:
        app = QApplication(sys.argv)

        translator = QTranslator()
        translator.load(
            QLocale(), "pdfhandoutcrop", "_",
            os.path.dirname(os.path.abspath(__file__)) + "/language")
        app.installTranslator(translator)

        # load Qt translation
        qtTranslator = QTranslator()
        qtTranslator.load(QLocale(), "qt", "_",
                          QLibraryInfo.location(QLibraryInfo.TranslationsPath))
        app.installTranslator(qtTranslator)
        w = MainWindow(args)
        w.showMaximized()
        sys.exit(app.exec_())
Esempio n. 10
0
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        model = FileListModel(self)
        model.setDirPath(QLibraryInfo.location(QLibraryInfo.PrefixPath))

        label = QLabel("Directory")
        lineEdit = QLineEdit()
        label.setBuddy(lineEdit)

        view = QListView()
        view.setModel(model)

        self.logViewer = QTextBrowser()
        self.logViewer.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred))

        lineEdit.textChanged.connect(model.setDirPath)
        lineEdit.textChanged.connect(self.logViewer.clear)
        model.numberPopulated.connect(self.updateLog)

        layout = QGridLayout()
        layout.addWidget(label, 0, 0)
        layout.addWidget(lineEdit, 0, 1)
        layout.addWidget(view, 1, 0, 1, 2)
        layout.addWidget(self.logViewer, 2, 0, 1, 2)

        self.setLayout(layout)
        self.setWindowTitle("Fetch More Example")
Esempio n. 11
0
def run():
    """start GUI

    The function will create the main thread for Qt Gui. It will set the
    language to system locals an start an instance of the main window.
    """
    def install_translator(filename, folder, app):
        locale = QtCore.QLocale.system().name()
        translator = QtCore.QTranslator()
        if translator.load(filename.format(locale), folder):
            app.installTranslator(translator)
        return translator
    args = handle_cli_args()
    sys.excepthook = handle_exception
    multiprocessing.freeze_support()
    app = QtWidgets.QApplication(sys.argv)
    # set translation language
    folder = godirec.resource_filename("godirec", 'data/language')
    translator1 = install_translator("godirec_{}", folder, app)
    if hasattr(sys, "frozen"):
        qt_folder = godirec.resource_filename("godirec", "translations")
    else:
        qt_folder = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
    translator2 = install_translator("qtbase_{}", qt_folder, app)
    window = main.GodiRecWindow()
    window.show()
    if "gdr_file" in args:
        window.setupProject(args["gdr_file"], False)
    else:
        audio.WaveConverter.confirm_converter_backend()
        if window.isNewProjectCreatedDialog():
            window.createNewProject()
    sys.exit(app.exec_())
Esempio n. 12
0
def getQtSystemTranslation(locale_name: str) -> Optional[QTranslator]:
    """
    Attempt to install Qt base system translations (for QMessageBox and QDialogBox buttons)
    :return: translator if loaded, else None
    """

    # These locales are found in the path QLibraryInfo.TranslationsPath
    convert_locale = dict(
        cs_CZ='cs',
        da_DK='da',
        de_DE='de',
        es_ES='es',
        fi_FI='fi',
        fr_FR='fr',
        it_IT='it',
        ja_JP='ja',
        hu_HU='hu',
        pl_PL='pl',
        ru_RU='ru',
        sk_SK='sk',
        uk_UA='uk',
    )

    qtTranslator = QTranslator()
    location = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
    qm_file = "qtbase_{}.qm".format(
        convert_locale.get(locale_name, locale_name))
    qm_file = os.path.join(location, qm_file)
    if os.path.isfile(qm_file):
        if qtTranslator.load(qm_file):
            logging.debug("Installing Qt support for locale %s", locale_name)
            return qtTranslator
        else:
            logging.debug("Could not load Qt locale file %s", qm_file)
Esempio n. 13
0
def main():
    parser = argparse.ArgumentParser(
        description='EPUB reader supporting vertical text')
    parser.add_argument("file",
                        metavar='FILE',
                        nargs='?',
                        default="",
                        help='EPUB document')
    args = parser.parse_args()

    app = QApplication(sys.argv)

    translator = QTranslator()
    translator.load(QLocale(), "vertreader", "_",
                    os.path.dirname(os.path.abspath(__file__)) + "/language")
    app.installTranslator(translator)

    # load Qt translation
    qtTranslator = QTranslator()
    qtTranslator.load(QLocale(), "qt", "_",
                      QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qtTranslator)

    window = MainWindow(args)
    sys.exit(app.exec_())
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Fetch More Example")

        label = QLabel("&Directory:")
        lineEdit = QLineEdit()
        label.setBuddy(lineEdit)

        self.model = FileListModel()
        self.model.numberPopulated.connect(self.updateLog)

        self.list_view = QListView()
        self.list_view.setModel(self.model)

        self.logViewer = QTextBrowser()
        self.logViewer.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)

        lineEdit.textChanged.connect(self.model.setDirPath)
        lineEdit.textChanged.connect(self.logViewer.clear)

        lineEdit.setText(
            str(Path(QLibraryInfo.location(QLibraryInfo.PrefixPath)).resolve())
        )

        layout = QGridLayout()
        layout.addWidget(label, 0, 0)
        layout.addWidget(lineEdit, 0, 1)
        layout.addWidget(self.list_view, 1, 0, 1, 2)
        layout.addWidget(self.logViewer, 2, 0, 1, 2)

        self.setCentralWidget(QWidget())
        self.centralWidget().setLayout(layout)
Esempio n. 15
0
    def setLanguage(self, language):
        # file dialog
        if not self.file_dialog_translator.isEmpty():
            QApplication.removeTranslator(self.file_dialog_translator)

        qmfile = "qtbase_" + QLocale.system().name().split('_')[0] + '.qm'
        self.file_dialog_translator.load(
            qmfile, QLibraryInfo.location(QLibraryInfo.TranslationsPath))
        QApplication.installTranslator(self.file_dialog_translator)

        # rest of app
        if language == Language.ENGLISH:
            self.actionEnglish.setChecked(True)

        elif language == Language.GERMAN:
            self.actionGerman.setChecked(True)

        else:
            # Fall back to english
            self.actionEnglish.setChecked(True)
            language = Language.ENGLISH

        self.activeConfig.language = language
        self.activeConfig.saveConfig()
        if not self.translator.isEmpty():
            QApplication.removeTranslator(self.translator)
        self.translator.load(
            f':/l10n/gui_{self.activeConfig.language.value}.qm')
        QApplication.installTranslator(self.translator)
        self.retranslateUi(self)
        self.resetEncText()
        self.resetDecText()
Esempio n. 16
0
def main():
    """Main app function."""
    import sys
    from os.path import dirname, realpath, exists
    app = QApplication(sys.argv)
    filePath = dirname(realpath(__file__))
    locale = QLocale.system().name()
    if locale == 'es_CU':
        locale = 'es_ES'
    # locale = 'es_ES'
    appTranslator = QTranslator()
    if exists(filePath + '/translations/'):
        appTranslator.load(filePath + "/translations/videomorph_" + locale)
    else:
        appTranslator.load(
            "/usr/share/videomorph/translations/videomorph_" + locale)
    app.installTranslator(appTranslator)
    qtTranslator = QTranslator()
    qtTranslator.load("qt_" + locale,
                      QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qtTranslator)
    mainWin = MMWindow()
    if mainWin.check_conversion_lib():
        mainWin.show()
        sys.exit(app.exec_())
Esempio n. 17
0
def build_localizations(ui, edition):
    loc.compile_all_po('locale')
    if ui == 'cocoa':
        app = cocoa_app(edition)
        loc.build_cocoa_localizations(app,
                                      en_stringsfile=op.join(
                                          'cocoa', 'base', 'en.lproj',
                                          'Localizable.strings'))
        locale_dest = op.join(app.resources, 'locale')
    elif ui == 'qt':
        build_qt_localizations()
        locale_dest = op.join('build', 'locale')
    if op.exists(locale_dest):
        shutil.rmtree(locale_dest)
    shutil.copytree('locale',
                    locale_dest,
                    ignore=shutil.ignore_patterns('*.po', '*.pot'))
    if ui == 'qt' and not ISLINUX:
        print("Copying qt_*.qm files into the 'locale' folder")
        from PyQt5.QtCore import QLibraryInfo
        trfolder = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
        for lang in loc.get_langs('locale'):
            qmname = 'qt_%s.qm' % lang
            src = op.join(trfolder, qmname)
            if op.exists(src):
                copy(src, op.join('build', 'locale', qmname))
Esempio n. 18
0
def main():
    """Main app function."""
    # Create the app
    app = QApplication(sys.argv)

    # Setup app translator
    app_translator = QTranslator()

    translator_pwd = Path(BASE_DIR, VM_PATHS.i18n)

    if translator_pwd.exists():
        app_translator.load(
            str(translator_pwd.joinpath('videomorph_{0}'.format(LOCALE))))
    else:
        translator_sys_path = Path(SYS_PATHS.i18n,
                                   'videomorph_{0}'.format(LOCALE))
        app_translator.load(str(translator_sys_path))

    app.installTranslator(app_translator)
    qt_translator = QTranslator()
    qt_translator.load("qt_" + LOCALE,
                       QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qt_translator)

    # Run the app
    run_app(app=app)
Esempio n. 19
0
def dictionary_dir(old=False):
    """Return the path (str) to the QtWebEngine's dictionaries directory."""
    if can_use_data_path() and not old:
        datapath = standarddir.data()
    else:
        datapath = QLibraryInfo.location(QLibraryInfo.DataPath)
    return os.path.join(datapath, 'qtwebengine_dictionaries')
Esempio n. 20
0
    def showDocInAssistant(self, name):
        url = self.resolveDocUrl(name)
        Colors.debug("Sending URL to Assistant:", url)

        # Start assistant if it's not already running.
        if self.assistantProcess.state() != QProcess.Running:
            app = QLibraryInfo.location(
                QLibraryInfo.BinariesPath) + QDir.separator()

            if sys.platform == 'darwin':
                app += 'Assistant.app/Contents/MacOS/Assistant'
            else:
                app += 'assistant'

            args = ['-enableRemoteControl']
            self.assistantProcess.start(app, args)
            if not self.assistantProcess.waitForStarted():
                QMessageBox.critical(None, "PyQt Demo",
                                     "Could not start %s." % app)
                return

        # Send command through remote control even if the process was just
        # started to activate assistant and bring it to the front.
        cmd_str = QTextStream(self.assistantProcess)
        cmd_str << 'SetSource ' << url << '\n'
Esempio n. 21
0
def install_gettext_trans_under_qt(base_folder, lang=None):
    # So, we install the gettext locale, great, but we also should try to install qt_*.qm if
    # available so that strings that are inside Qt itself over which I have no control are in the
    # right language.
    from PyQt5.QtCore import QCoreApplication, QTranslator, QLocale, QLibraryInfo
    if not lang:
        lang = str(QLocale.system().name())[:2]
    localename = get_locale_name(lang)
    if localename is not None:
        try:
            locale.setlocale(locale.LC_ALL, localename)
        except locale.Error:
            logging.warning("Couldn't set locale %s", localename)
    qmname = 'qt_%s' % lang
    if ISLINUX:
        # Under linux, a full Qt installation is already available in the system, we didn't bundle
        # up the qm files in our package, so we have to load translations from the system.
        qmpath = op.join(QLibraryInfo.location(QLibraryInfo.TranslationsPath),
                         qmname)
    else:
        qmpath = op.join(base_folder, qmname)
    qtr = QTranslator(QCoreApplication.instance())
    qtr.load(qmpath)
    QCoreApplication.installTranslator(qtr)
    install_gettext_trans(base_folder, lang)
Esempio n. 22
0
def dictionary_dir(old=False):
    """Return the path (str) to the QtWebEngine's dictionaries directory."""
    if qtutils.version_check('5.10', compiled=False) and not old:
        datapath = standarddir.data()
    else:
        datapath = QLibraryInfo.location(QLibraryInfo.DataPath)
    return os.path.join(datapath, 'qtwebengine_dictionaries')
Esempio n. 23
0
def switchQtTranslator(cur_lang):
	from PyQt5.QtCore import QTranslator, QLibraryInfo

	translatorQt = QTranslator()
	translatorQt_help = QTranslator()
	translatorQt_base = QTranslator()
	translatorQt_connectivity = QTranslator()
	translatorQt_declarative = QTranslator()
	translatorQt_location = QTranslator()
	translatorQt_multimedia = QTranslator()

	try:
		# PyInstaller creates a temp folder and stores path in _MEIPASS
		base_path = sys._MEIPASS
		pathToTransaltionsQT = os.path.join(base_path, "translations")
	except Exception:
		pathToTransaltionsQT = QLibraryInfo.location(QLibraryInfo.TranslationsPath)

	switchTranslator(translatorQt, 
					 "qt_" + cur_lang, pathToTransaltionsQT)
	switchTranslator(translatorQt_help,
					 "qt_help_" + cur_lang, pathToTransaltionsQT)
	switchTranslator(translatorQt_base, 
					 "qtbase_" + cur_lang, pathToTransaltionsQT)
	switchTranslator(translatorQt_connectivity,
					 "qtconnectivity_" + cur_lang, pathToTransaltionsQT)
	switchTranslator(translatorQt_declarative,
					 "qtdeclarative_" + cur_lang, pathToTransaltionsQT)
	switchTranslator(translatorQt_location,
					 "qtlocation_" + cur_lang, pathToTransaltionsQT)
	switchTranslator(translatorQt_multimedia,
					 "qtmultimedia_" + cur_lang, pathToTransaltionsQT)
Esempio n. 24
0
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        model = FileListModel(self)
        model.setDirPath(QLibraryInfo.location(QLibraryInfo.PrefixPath))

        label = QLabel("Directory")
        lineEdit = QLineEdit()
        label.setBuddy(lineEdit)

        view = QListView()
        view.setModel(model)

        self.logViewer = QTextBrowser()
        self.logViewer.setSizePolicy(
            QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred))

        lineEdit.textChanged.connect(model.setDirPath)
        lineEdit.textChanged.connect(self.logViewer.clear)
        model.numberPopulated.connect(self.updateLog)

        layout = QGridLayout()
        layout.addWidget(label, 0, 0)
        layout.addWidget(lineEdit, 0, 1)
        layout.addWidget(view, 1, 0, 1, 2)
        layout.addWidget(self.logViewer, 2, 0, 1, 2)

        self.setLayout(layout)
        self.setWindowTitle("Fetch More Example")
Esempio n. 25
0
def _main() -> None:
    """
    Execute the main application loop.

    :return: nothing
    :rtype: None
    """

    app = QApplication(sys.argv)
    QLocale.setDefault(QLocale.c())

    # translation
    language = QLocale.system().name()[:2]
    translations_path = QLibraryInfo.location(QLibraryInfo.TranslationsPath)

    base_translator = QTranslator()
    base_translator.load("qtbase_{}".format(language), translations_path)
    app.installTranslator(base_translator)

    custom_translator = QTranslator()
    custom_translator.load("cafog_{}".format(language))
    app.installTranslator(custom_translator)

    # generate main window
    frame = MainWindow()
    frame.show()
    sys.exit(app.exec_())
Esempio n. 26
0
def getQtSystemTranslation(locale_name: str) -> Optional[QTranslator]:
    """
    Attempt to install Qt base system translations (for QMessageBox and QDialogBox buttons)
    :return: translator if loaded, else None
    """

    # These locales are found in the path QLibraryInfo.TranslationsPath
    convert_locale = dict(
        cs_CZ="cs",
        da_DK="da",
        de_DE="de",
        es_ES="es",
        fi_FI="fi",
        fr_FR="fr",
        it_IT="it",
        ja_JP="ja",
        hu_HU="hu",
        pl_PL="pl",
        ru_RU="ru",
        sk_SK="sk",
        uk_UA="uk",
    )

    qtTranslator = QTranslator()
    location = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
    qm_file = "qtbase_{}.qm".format(convert_locale.get(locale_name, locale_name))
    qm_file = os.path.join(location, qm_file)
    if os.path.isfile(qm_file):
        if qtTranslator.load(qm_file):
            logging.debug("Installing Qt support for locale %s", locale_name)
            return qtTranslator
        else:
            logging.debug("Could not load Qt locale file %s", qm_file)
Esempio n. 27
0
    def _runFile(self, file):
        """子进程运行文件
        :param file:    文件
        """
        file = os.path.abspath(file)
        process = QProcess(self)
        process.setProperty('file', file)
        process.readChannelFinished.connect(self.onReadChannelFinished)

        env = QProcessEnvironment.systemEnvironment()
#         libpath = get_python_lib()
#         env.insert('QT_QPA_PLATFORM_PLUGIN_PATH', os.path.join(
#             libpath, 'PyQt5', 'Qt', 'plugins', 'platforms'))
#         env.insert('QT_QPA_PLATFORM_PLUGIN_PATH',
#                    os.path.abspath('platforms'))
        env.insert('QML_IMPORT_PATH', os.path.abspath('qml'))
        env.insert('QML2_IMPORT_PATH', env.value('QML_IMPORT_PATH'))
        if os.name == 'nt':
            env.insert(
                'PATH', QLibraryInfo.location(
                    QLibraryInfo.BinariesPath) + os.pathsep + env.value('PATH')
            )
        env.insert(
            'PATH', os.path.dirname(
                os.path.abspath(sys.argv[0])) + os.pathsep + env.value('PATH')
        )
        process.setProcessEnvironment(env)

        if sys.executable.endswith('python.exe'):
            process.setWorkingDirectory(os.path.dirname(file))
        process.start(sys.executable, [file])
Esempio n. 28
0
def main():
    if int(QtCore.PYQT_VERSION_STR.split('.')[1]) > 5:
        # for > Qt 5.5
        os.putenv('QT_AUTO_SCREEN_SCALE_FACTOR', '1')
    else:
        # for Qt 5.5
        os.putenv('QT_DEVICE_PIXEL_RATIO', 'auto')
    if os.name == 'nt':
        os.environ['PATH'] = QLibraryInfo.location(
            QLibraryInfo.BinariesPath) + os.pathsep + os.environ['PATH']
    os.makedirs(Constants.DirErrors, exist_ok=True)
    os.makedirs(Constants.DirProject, exist_ok=True)
    os.makedirs(os.path.dirname(Constants.UpgradeFile), exist_ok=True)
    # 异常捕捉
    sys.excepthook = cgitb.Hook(1, Constants.DirErrors, 5, sys.stderr, '')
    # 初始化日志
    initLog(Constants.LogName, Constants.LogFile)
    # 运行app
    app = QSingleApplication('qtsingleapp-pyqtclient', sys.argv)
    if app.isRunning():
        # 激活窗口
        app.sendMessage('show', 1000)
    else:
        app.setQuitOnLastWindowClosed(True)
        app.setWindowIcon(QIcon('Resources/Images/app.ico'))
        # 第一次运行
        w = MainWindow()
        app.setActivationWindow(w)
        w.show()
        sys.exit(app.exec_())
Esempio n. 29
0
def _get_lang_override(
        webengine_version: utils.VersionNumber,
        locale_name: str
) -> Optional[str]:
    """Get a --lang switch to override Qt's locale handling.

    This is needed as a WORKAROUND for https://bugreports.qt.io/browse/QTBUG-91715
    There is no fix yet, but we assume it'll be fixed with QtWebEngine 5.15.4.
    """
    if not config.val.qt.workarounds.locale:
        return None

    if webengine_version != utils.VersionNumber(5, 15, 3) or not utils.is_linux:
        return None

    locales_path = pathlib.Path(
        QLibraryInfo.location(QLibraryInfo.TranslationsPath)) / 'qtwebengine_locales'
    if not locales_path.exists():
        log.init.debug(f"{locales_path} not found, skipping workaround!")
        return None

    pak_path = _get_locale_pak_path(locales_path, locale_name)
    if pak_path.exists():
        log.init.debug(f"Found {pak_path}, skipping workaround")
        return None

    pak_name = _get_pak_name(locale_name)
    pak_path = _get_locale_pak_path(locales_path, pak_name)
    if pak_path.exists():
        log.init.debug(f"Found {pak_path}, applying workaround")
        return pak_name

    log.init.debug(f"Can't find pak in {locales_path} for {locale_name} or {pak_name}")
    return 'en-US'
Esempio n. 30
0
def dictionary_dir(old=False):
    """Return the path (str) to the QtWebEngine's dictionaries directory."""
    if qtutils.version_check('5.10', compiled=False) and not old:
        datapath = standarddir.data()
    else:
        datapath = QLibraryInfo.location(QLibraryInfo.DataPath)
    return os.path.join(datapath, 'qtwebengine_dictionaries')
Esempio n. 31
0
def parse_webenginecore() -> Optional[Versions]:
    """Parse the QtWebEngineCore library file."""
    if version.is_flatpak():
        # Flatpak has Qt in /usr/lib/x86_64-linux-gnu, but QtWebEngine in /app/lib.
        library_path = pathlib.Path("/app/lib")
    else:
        library_path = pathlib.Path(QLibraryInfo.location(QLibraryInfo.LibrariesPath))

    library_name = sorted(library_path.glob('libQt5WebEngineCore.so*'))
    if not library_name:
        log.misc.debug(f"No QtWebEngine .so found in {library_path}")
        return None
    else:
        lib_file = library_name[-1]
        log.misc.debug(f"QtWebEngine .so found at {lib_file}")

    try:
        with lib_file.open('rb') as f:
            versions = _parse_from_file(f)

        log.misc.debug(f"Got versions from ELF: {versions}")
        return versions
    except ParseError as e:
        log.misc.debug(f"Failed to parse ELF: {e}", exc_info=True)
        return None
Esempio n. 32
0
 def webengine_include_private_codec(self):
     ''' Return bool of whether the QtWebEngineProcess include private codec. '''
     path = os.path.join(
         QLibraryInfo.location(QLibraryInfo.LibraryExecutablesPath),
         "QtWebEngineProcess")
     return self.get_command_result(
         "ldd {} | grep libavformat".format(path)) != ""
Esempio n. 33
0
def main():
    if sys.version_info < (3, 5):
        raise RuntimeError('This package requires Python 3.5 or later')

    site_packages = get_python_lib()
    print('site_packages', site_packages)
    current_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
    print('current_dir', current_dir)

    env = QProcessEnvironment.systemEnvironment()
    PATH = '{0};{1};{2}'.format(os.path.dirname(PyQt5.__file__), sys.prefix,
                                env.value('PATH', ''))
    env.insert('PATH', PATH)
    env.insert('PYQTDESIGNERPATH', os.path.join(current_dir, 'Plugins'))
    env.insert('PYTHONPATH', os.path.join(current_dir))

    print('PATH', env.value('PATH', ''))
    print('PYQTDESIGNERPATH', env.value('PYQTDESIGNERPATH', ''))
    print('PYTHONPATH', env.value('PYTHONPATH', ''))

    ext = '.exe' if os.name == 'nt' else ''
    designer = QProcess()
    designer.setProcessEnvironment(env)

    # for PyQt5.5 latter,pyqt5-tools maybe have problem
    designer_bin = QLibraryInfo.location(
        QLibraryInfo.BinariesPath) + os.sep + 'designer' + ext
    print('designer_bin', designer_bin)

    if os.path.exists(designer_bin):
        designer.start(designer_bin)
        designer.waitForFinished(-1)
        sys.exit(designer.exitCode())
    else:
        raise Exception('Can not find designer')
Esempio n. 34
0
def getQtBinariesPath():
    """
    Module function to get the path of the Qt binaries.
    
    @return path of the Qt binaries (string)
    """
    import Preferences

    path = ""

    # step 1: check, if the user has configured a tools path
    path = Preferences.getQt("QtToolsDir")

    if not path and isWindowsPlatform():
        # step 2.1: check for PyQt5 Windows installer (designer is test object)
        modDir = getPyQt5ModulesDirectory()
        if os.path.exists(os.path.join(modDir, "bin", "designer.exe")):
            path = os.path.join(modDir, "bin")
        elif os.path.exists(os.path.join(modDir, "designer.exe")):
            path = modDir

    if not path:
        # step 2.2: get the path from Qt
        # Note: no Qt tools are to found there for PyQt 5.7.0
        path = QLibraryInfo.location(QLibraryInfo.BinariesPath)
        if not os.path.exists(path):
            path = ""

    return QDir.toNativeSeparators(path)
Esempio n. 35
0
def main():
    global app
    # register representation factories
    baseRepresentationFactories.registerAllFactories()
    representationFactories.registerAllFactories()
    # initialize the app
    app = Application(sys.argv)
    app.setOrganizationName("TruFont")
    app.setOrganizationDomain("trufont.github.io")
    app.setApplicationName("TruFont")
    app.setApplicationVersion(__version__)
    app.setWindowIcon(QIcon(":app.png"))
    app.setAttribute(Qt.AA_UseHighDpiPixmaps, True)

    # Install stream redirection
    app.outputWindow = OutputWindow()
    # Exception handling
    sys.excepthook = exceptionCallback

    # Qt's translation for itself. May not be installed.
    qtTranslator = QTranslator()
    qtTranslator.load("qt_" + QLocale.system().name(),
                      QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qtTranslator)

    appTranslator = QTranslator()
    appTranslator.load("trufont_" + QLocale.system().name(),
                       os.path.dirname(os.path.realpath(__file__)) +
                       "/resources")
    app.installTranslator(appTranslator)

    # parse options and open fonts
    parser = QCommandLineParser()
    parser.setApplicationDescription(QApplication.translate(
        "Command-line parser", "The TruFont font editor."))
    parser.addHelpOption()
    parser.addVersionOption()
    parser.addPositionalArgument(QApplication.translate(
        "Command-line parser", "files"), QApplication.translate(
        "Command-line parser", "The UFO files to open."))
    parser.process(app)
    args = parser.positionalArguments()
    if not args:
        fontPath = None
        # maybe load recent file
        settings = QSettings()
        loadRecentFile = settings.value("misc/loadRecentFile", False, bool)
        if loadRecentFile:
            recentFiles = settings.value("core/recentFiles", [], type=str)
            if len(recentFiles) and os.path.exists(recentFiles[0]):
                fontPath = recentFiles[0]
                app.openFile(fontPath)
        # otherwise, create a new file
        if fontPath is None:
            app.newFile()
    else:
        for fontPath in args:
            app.openFile(fontPath)
    sys.exit(app.exec_())
Esempio n. 36
0
def simpleAppStartup(
    argv, appinfo, mwFactory, quitOnLastWindowClosed=True, app=None, raiseIt=True, installErrorHandler=False
):
    """
    Module function to start up an application that doesn't need a specialized
    start up.
    
    This function is used by all of eric6's helper programs.
    
    @param argv list of commandline parameters (list of strings)
    @param appinfo dictionary describing the application
    @param mwFactory factory function generating the main widget. This
        function must accept the following parameter.
        <dl>
            <dt>argv</dt>
            <dd>list of commandline parameters (list of strings)</dd>
        </dl>
    @keyparam quitOnLastWindowClosed flag indicating to quit the application,
        if the last window was closed (boolean)
    @keyparam app reference to the application object (QApplication or None)
    @keyparam raiseIt flag indicating to raise the generated application
        window (boolean)
    @keyparam installErrorHandler flag indicating to install an error
        handler dialog (boolean)
    @return exit result (integer)
    """
    handleArgs(argv, appinfo)
    if app is None:
        # set the library paths for plugins
        setLibraryPaths()
        app = E5Application(argv)
    app.setQuitOnLastWindowClosed(quitOnLastWindowClosed)

    # the following code depends upon a valid application object
    import Preferences

    initializeResourceSearchPath()
    QApplication.setWindowIcon(UI.PixmapCache.getIcon("eric.png"))

    qt4TransDir = Preferences.getQt4TranslationsDir()
    if not qt4TransDir:
        qt4TransDir = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
    loadTranslators(qt4TransDir, app)

    w = mwFactory(argv)
    if quitOnLastWindowClosed:
        app.lastWindowClosed.connect(app.quit)
    w.show()
    if raiseIt:
        w.raise_()

    if installErrorHandler:
        # generate a graphical error handler
        from E5Gui import E5ErrorMessage

        eMsg = E5ErrorMessage.qtHandler()
        eMsg.setMinimumSize(600, 400)

    return app.exec_()
Esempio n. 37
0
def simpleAppStartup(argv, appinfo, mwFactory, quitOnLastWindowClosed=True,
                     app=None, raiseIt=True, installErrorHandler=False):
    """
    Module function to start up an application that doesn't need a specialized
    start up.
    
    This function is used by all of eric6's helper programs.
    
    @param argv list of commandline parameters (list of strings)
    @param appinfo dictionary describing the application
    @param mwFactory factory function generating the main widget. This
        function must accept the following parameter.
        <dl>
            <dt>argv</dt>
            <dd>list of commandline parameters (list of strings)</dd>
        </dl>
    @keyparam quitOnLastWindowClosed flag indicating to quit the application,
        if the last window was closed (boolean)
    @keyparam app reference to the application object (QApplication or None)
    @keyparam raiseIt flag indicating to raise the generated application
        window (boolean)
    @keyparam installErrorHandler flag indicating to install an error
        handler dialog (boolean)
    @return exit result (integer)
    """
    handleArgs(argv, appinfo)
    if app is None:
        # set the library paths for plugins
        setLibraryPaths()
        app = E5Application(argv)
    app.setQuitOnLastWindowClosed(quitOnLastWindowClosed)
    
    # the following code depends upon a valid application object
    import Preferences
    
    initializeResourceSearchPath()
    QApplication.setWindowIcon(UI.PixmapCache.getIcon("eric.png"))
    
    qtTransDir = Preferences.getQtTranslationsDir()
    if not qtTransDir:
        qtTransDir = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
    loadTranslators(qtTransDir, app, ("qscintilla",))
    # qscintilla needed for web browser
    
    w = mwFactory(argv)
    if quitOnLastWindowClosed:
        app.lastWindowClosed.connect(app.quit)
    w.show()
    if raiseIt:
        w.raise_()
    
    if installErrorHandler:
        # generate a graphical error handler
        from E5Gui import E5ErrorMessage
        eMsg = E5ErrorMessage.qtHandler()
        eMsg.setMinimumSize(600, 400)
    
    return app.exec_()
Esempio n. 38
0
def getSystemTranslationsPath():
    res = ""
    if platform.system() == 'Darwin':
        if inBundle():
            res = QApplication.applicationDirPath() + "/../Resources/translations/"
        else:
            res = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
    elif platform.system() == "Linux":
        if isFrozen():
            res = QApplication.applicationDirPath() + "/translations/"
        else:
            res = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
    else:
        if main_is_frozen():
            res = os.path.dirname(sys.executable) + "\\translations\\"
        else:
            res = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
    return res
Esempio n. 39
0
def copy_qt_plugins(folder_names, dest): # This is only for Windows
    from PyQt5.QtCore import QLibraryInfo
    qt_plugin_dir = QLibraryInfo.location(QLibraryInfo.PluginsPath)
    def ignore(path, names):
        if path == qt_plugin_dir:
            return [n for n in names if n not in folder_names]
        else:
            return [n for n in names if not n.endswith('.dll')]
    shutil.copytree(qt_plugin_dir, dest, ignore=ignore)
Esempio n. 40
0
def install_qt_trans():
    # So, we install the gettext locale, great, but we also should try to install qt_*.qm if
    # available so that strings that are inside Qt itself over which I have no control are in the
    # right language.
    from PyQt5.QtCore import QCoreApplication, QTranslator, QLocale, QLibraryInfo
    lang = str(QLocale.system().name())[:2]
    qmname = 'qt_%s' % lang
    qtr = QTranslator(QCoreApplication.instance())
    qtr.load(qmname, QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    QCoreApplication.installTranslator(qtr)
Esempio n. 41
0
def main():
	if markups.__version_tuple__ < (2, ):
		sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')

	# If we're running on Windows without a console, then discard stdout
	# and save stderr to a file to facilitate debugging in case of crashes.
	if sys.executable.endswith('pythonw.exe'):
		sys.stdout = open(devnull, 'w')
		sys.stderr = open('stderr.log', 'w')

	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7
		app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qt_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	print('Using configuration file:', settings.fileName())
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()
	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, sys.argv[1:]))
	previewMode = False
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if previewMode:
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '--preview':
			previewMode = True
	inputData = '' if (sys.stdin is None or sys.stdin.isatty()) else sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
Esempio n. 42
0
def init_language():
    """ Find the current locale, and install the correct translators """

    # Get app instance
    app = QCoreApplication.instance()

    # Setup of our list of translators and paths
    translator_types = (
        {"type": "QT", "pattern": "qt_%s", "path": QLibraryInfo.location(QLibraryInfo.TranslationsPath)},
        {
            "type": "OpenShot",
            "pattern": os.path.join("%s", "LC_MESSAGES", "OpenShot"),
            "path": os.path.join(info.PATH, "locale"),
        },
    )

    # Determine the environment locale, or default to system locale name
    locale_names = [
        os.environ.get("LANG", QLocale().system().name()),
        os.environ.get("LOCALE", QLocale().system().name()),
    ]

    # Output all system languages detected
    log.info("Qt Detected Languages: {}".format(QLocale().system().uiLanguages()))
    log.info("LANG Environment Variable: {}".format(os.environ.get("LANG", QLocale().system().name())))
    log.info("LOCALE Environment Variable: {}".format(os.environ.get("LOCALE", QLocale().system().name())))

    # Default the locale to C, for number formatting
    locale.setlocale(locale.LC_ALL, "C")

    # Loop through environment variables
    found_language = False
    for locale_name in locale_names:

        # Don't try on default locale, since it fails to load what is the default language
        if "en_US" in locale_name:
            log.info("Skipping English language (no need for translation): {}".format(locale_name))
            continue

        # Go through each translator and try to add for current locale
        for type in translator_types:
            trans = QTranslator(app)
            if find_language_match(type["pattern"], type["path"], trans, locale_name):
                # Install translation
                app.installTranslator(trans)
                found_language = True

        # Exit if found language
        if found_language:
            log.info("Exiting translation system (since we successfully loaded: {})".format(locale_name))
            break
Esempio n. 43
0
    def launchQml(self, name):
        import_path = self.resolveDataDir(name)
        qml = self.resolveQmlFile(name)

        process = QProcess(self)
        process.error.connect(self.launchError)

        env = QProcessEnvironment.systemEnvironment()
        env.insert('QML2_IMPORT_PATH', import_path)
        process.setProcessEnvironment(env)

        executable = QLibraryInfo.location(QLibraryInfo.BinariesPath) + '/qmlscene'
        Colors.debug("Launching:", executable)
        process.start(executable, [qml])
Esempio n. 44
0
def main():
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)
    app.setOrganizationName('meteo-qt')
    app.setOrganizationDomain('meteo-qt')
    app.setApplicationName('meteo-qt')
    app.setWindowIcon(QIcon(':/logo'))
    filePath = os.path.dirname(os.path.realpath(__file__))
    settings = QSettings()
    locale = settings.value('Language')
    if locale is None or locale == '':
        locale = QLocale.system().name()
    appTranslator = QTranslator()
    if os.path.exists(filePath + '/translations/'):
        appTranslator.load(filePath + "/translations/meteo-qt_" + locale)
    else:
        appTranslator.load("/usr/share/meteo_qt/translations/meteo-qt_" +
                           locale)
    app.installTranslator(appTranslator)
    qtTranslator = QTranslator()
    qtTranslator.load("qt_" + locale,
                      QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qtTranslator)

    log_level = settings.value('Logging/Level')
    if log_level == '' or log_level is None:
        log_level = 'INFO'
        settings.setValue('Logging/Level', 'INFO')

    log_filename = os.path.dirname(settings.fileName())
    if not os.path.exists(log_filename):
        os.makedirs(log_filename)
    log_filename = log_filename + '/meteo-qt.log'

    logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s - %(module)s - %(name)s',
                        datefmt='%m/%d/%Y %H:%M:%S',
                        filename=log_filename, level=log_level)
    logger = logging.getLogger('meteo-qt')
    logger.setLevel(log_level)
    handler = logging.handlers.RotatingFileHandler(
        log_filename, maxBytes=20, backupCount=5)
    logger1 = logging.getLogger()
    handler1 = logging.StreamHandler()
    logger1Formatter = logging.Formatter('%(levelname)s: %(message)s - %(module)s')
    handler1.setFormatter(logger1Formatter)
    logger.addHandler(handler)
    logger1.addHandler(handler1)

    m = SystemTrayIcon()
    app.exec_()
Esempio n. 45
0
def build_localizations():
    build_base_localizations()
    build_qt_localizations()
    locale_dest = op.join('build', 'locale')
    if op.exists(locale_dest):
        shutil.rmtree(locale_dest)
    shutil.copytree('locale', locale_dest, ignore=shutil.ignore_patterns('*.po', '*.pot'))
    if not ISLINUX:
        print("Copying qt_*.qm files into the 'locale' folder")
        from PyQt5.QtCore import QLibraryInfo
        trfolder = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
        for lang in loc.get_langs('locale'):
            qmname = 'qt_%s.qm' % lang
            src = op.join(trfolder, qmname)
            if op.exists(src):
                copy(src, op.join('build', 'locale', qmname))
Esempio n. 46
0
def main():
	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7
		app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qt_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()
	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, sys.argv[1:]))
	previewMode = False
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if previewMode:
				window.actionPreview.trigger()
		elif fileName == '--preview':
			previewMode = True
	if sys.stdin:
		inputData = '' if sys.stdin.isatty() else sys.stdin.read()
		if inputData or not window.tabWidget.count():
			window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
Esempio n. 47
0
def get_current_locale():
    """Get the current locale name from the current system"""

    # Get app instance
    app = QCoreApplication.instance()

    # Setup of our list of translators and paths
    translator_types = (
        {"type": "QT", "pattern": "qt_%s", "path": QLibraryInfo.location(QLibraryInfo.TranslationsPath)},
        {
            "type": "OpenShot",
            "pattern": os.path.join("%s", "LC_MESSAGES", "OpenShot"),
            "path": os.path.join(info.PATH, "locale"),
        },
    )

    # Determine the environment locale, or default to system locale name
    locale_names = [
        os.environ.get("LANG", QLocale().system().name()),
        os.environ.get("LOCALE", QLocale().system().name()),
    ]

    # Loop through environment variables
    found_language = False
    for locale_name in locale_names:

        # Don't try on default locale, since it fails to load what is the default language
        if "en_US" in locale_name:
            continue

        # Go through each translator and try to add for current locale
        for type in translator_types:
            trans = QTranslator(app)
            if find_language_match(type["pattern"], type["path"], trans, locale_name):
                found_language = True

        # Exit if found language
        if found_language:
            return locale_name.replace(".UTF8", "").replace(".UTF-8", "")

    # default locale
    return "en"
Esempio n. 48
0
    def __init__(self, app_dir):

        app_dir = os.path.realpath(app_dir)
        manifest_path = os.path.join(app_dir, "manifest.json")

        try:
            manifest = json.load(codecs.open(manifest_path, 'r', 'utf-8'))
        except:
            manifest = {}

        for key in manifest:
            assets.manifest[key] = manifest[key]

        app = QApplication(sys.argv)
        app.setApplicationName(assets.manifest['name'])
        app.setApplicationVersion(assets.manifest['version'])

        assets.sys = System()
        assets.codec = Codec()
        assets.fs = FileSystem()
        assets.dataJar = DataJar()

        translator = QTranslator()
        translateLocaleName = "qt_" + QLocale.system().name()
        translator.load(translateLocaleName, QLibraryInfo.location(QLibraryInfo.TranslationsPath))
        app.installTranslator(translator)

        if assets.manifest.get("plugins"):
            plugindir = os.path.join(app_dir, assets.manifest["plugins"])
            plugin_manager = PluginsManager(plugindir)
            plugin_manager.load(assets)

        assets.manifest['icon'] = os.path.join(app_dir, assets.manifest["icon"])
        assets.manifest['app_dir'] = app_dir
        if "--debug" in sys.argv:
            assets.manifest['debug'] = True

        index_path = os.path.join(app_dir, assets.manifest['path'] + 'index.html')
        self.window = Window(None, index_path)

        sys.exit(app.exec_())
Esempio n. 49
0
def qtDesignerStart():
    """ Set widgets/plugins paths and start QtDesigner """

    # Get base path and QProcess system environment
    base = os.path.dirname(__file__)
    env = QProcessEnvironment.systemEnvironment()

    # Path for tell python where it can find the widgets directory
    pybase = os.path.join(base, 'python')
    # Path for tell QtDesigner where it can find the plugins directory
    wbase = os.path.join(base, 'widgets')

    # Insert paths to QProcess system environment
    env.insert('PYQTDESIGNERPATH', pybase)
    env.insert('PYTHONPATH', wbase)

    # inform user
    inform('env add "PYQTDESIGNERPATH" plugins path - ' + pybase)
    inform('env add "PYTHONPATH" widgets path - ' + wbase)

    # Create QProcess and set environment
    designer = QProcess()
    designer.setProcessEnvironment(env)

    # Get QtDesigner binaries path
    designer_bin = QLibraryInfo.location(QLibraryInfo.BinariesPath)

    # Platform specefic
    if sys.platform == 'darwin':
        designer_bin += '/Designer.app/Contents/MacOS/Designer'
    else:
        designer_bin += '/designer'

    # inform user
    inform('designer bin - ' + designer_bin)
    inform('start QtDesigner...')

    # Start QtDesigner
    designer.start(designer_bin)
    designer.waitForFinished(-1)
    sys.exit(designer.exitCode())
Esempio n. 50
0
    def __init__(self, config, use_qt_notifications):

        # This is done dynamically so localization
        # support can be configure beforehand.
        from plover.gui_qt.main_window import MainWindow

        self._app = None
        self._win = None
        self._engine = None
        self._translator = None

        QCoreApplication.setApplicationName(__software_name__.capitalize())
        QCoreApplication.setApplicationVersion(__version__)
        QCoreApplication.setOrganizationName('Open Steno Project')
        QCoreApplication.setOrganizationDomain('openstenoproject.org')

        self._app = QApplication([])
        self._app.setAttribute(Qt.AA_UseHighDpiPixmaps)

        # Enable localization of standard Qt controls.
        self._translator = QTranslator()
        translations_dir = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
        self._translator.load('qtbase_' + get_language(), translations_dir)
        self._app.installTranslator(self._translator)

        QApplication.setQuitOnLastWindowClosed(False)

        self._app.engine = self._engine = Engine(config, KeyboardEmulation())
        # On macOS, quitting through the dock will result
        # in a direct call to `QCoreApplication.quit`.
        self._app.aboutToQuit.connect(self._app.engine.quit)

        signal.signal(signal.SIGINT, lambda signum, stack: self._engine.quit())

        # Make sure the Python interpreter runs at least every second,
        # so signals have a chance to be processed.
        self._timer = QTimer()
        self._timer.timeout.connect(lambda: None)
        self._timer.start(1000)

        self._win = MainWindow(self._engine, use_qt_notifications)
Esempio n. 51
0
def build_localizations(ui, edition):
    loc.compile_all_po('locale')
    if ui == 'cocoa':
        app = cocoa_app(edition)
        loc.build_cocoa_localizations(app, en_stringsfile=op.join('cocoa', 'base', 'en.lproj', 'Localizable.strings'))
        locale_dest = op.join(app.resources, 'locale')
    elif ui == 'qt':
        build_qt_localizations()
        locale_dest = op.join('build', 'locale')
    if op.exists(locale_dest):
        shutil.rmtree(locale_dest)
    shutil.copytree('locale', locale_dest, ignore=shutil.ignore_patterns('*.po', '*.pot'))
    if ui == 'qt' and not ISLINUX:
        print("Copying qt_*.qm files into the 'locale' folder")
        from PyQt5.QtCore import QLibraryInfo
        trfolder = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
        for lang in loc.get_langs('locale'):
            qmname = 'qt_%s.qm' % lang
            src = op.join(trfolder, qmname)
            if op.exists(src):
                copy(src, op.join('build', 'locale', qmname))
Esempio n. 52
0
    def installTranslators(self):
        # Delete previous translators
        del self.mQtTranslator
        del self.mAppTranslator
        self.mQtTranslator = QTranslator()
        self.mAppTranslator = QTranslator()
        language = preferences.Preferences.instance().language()
        if language=='':
            language = QLocale.system().name()
        qtTranslationsDir = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
        if (self.mQtTranslator.load("qt_" + language, qtTranslationsDir)):
            QCoreApplication.installTranslator(self.mQtTranslator)
        else:
            del self.mQtTranslator
            self.mQtTranslator = None

        if (self.mAppTranslator.load("tiled_" + language, self.mTranslationsDir)):
            QCoreApplication.installTranslator(self.mAppTranslator)
        else:
            del self.mAppTranslator
            self.mAppTranslator = None
Esempio n. 53
0
    def launchExample(self, name):
        executable = self.resolveExeFile(name)

        process = QProcess(self)
        process.error.connect(self.launchError)

        if sys.platform == 'win32':
            # Make sure it finds the DLLs on Windows.
            env = QProcessEnvironment.systemEnvironment()
            env.insert('PATH',
                    QLibraryInfo.location(QLibraryInfo.BinariesPath) + ';' +
                            env.value('PATH'))
            process.setProcessEnvironment(env)

        if self.info[name]['changedirectory'] != 'false':
            workingDirectory = self.resolveDataDir(name)
            process.setWorkingDirectory(workingDirectory)
            Colors.debug("Setting working directory:", workingDirectory)

        Colors.debug("Launching:", executable)
        process.start(sys.executable, [executable])
Esempio n. 54
0
def getQtBinariesPath():
    """
    Module function to get the path of the Qt binaries.
    
    @return path of the Qt binaries (string)
    """
    path = ""
    if isWindowsPlatform():
        # check for PyQt5 installer first (designer is test object)
        modDir = getPyQt5ModulesDirectory()
        if os.path.exists(os.path.join(modDir, "bin", "designer.exe")):
            path = os.path.join(modDir, "bin")
        elif os.path.exists(os.path.join(modDir, "designer.exe")):
            path = modDir

    if not path:
        path = QLibraryInfo.location(QLibraryInfo.BinariesPath)
        if not os.path.exists(path):
            path = ""

    return QDir.toNativeSeparators(path)
Esempio n. 55
0
def build_localizations(ui):
    build_base_localizations()
    if ui == "cocoa":
        app = cocoa_app()
        loc.build_cocoa_localizations(app)
        locale_dest = op.join(app.resources, "locale")
    elif ui == "qt":
        build_qt_localizations()
        locale_dest = op.join("build", "locale")
    if op.exists(locale_dest):
        shutil.rmtree(locale_dest)
    shutil.copytree("locale", locale_dest, ignore=shutil.ignore_patterns("*.po", "*.pot"))
    if ui == "qt" and not ISLINUX:
        print("Copying qt_*.qm files into the 'locale' folder")
        from PyQt5.QtCore import QLibraryInfo

        trfolder = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
        for lang in loc.get_langs("locale"):
            qmname = "qt_%s.qm" % lang
            src = op.join(trfolder, qmname)
            if op.exists(src):
                copy(src, op.join("build", "locale", qmname))
Esempio n. 56
0
    def showDocInAssistant(self, name):
        url = self.resolveDocUrl(name)
        Colors.debug("Sending URL to Assistant:", url)

        # Start assistant if it's not already running.
        if self.assistantProcess.state() != QProcess.Running:
            app = QLibraryInfo.location(QLibraryInfo.BinariesPath) + QDir.separator()

            if sys.platform == 'darwin':
                app += 'Assistant.app/Contents/MacOS/Assistant'
            else:
                app += 'assistant'

            args = ['-enableRemoteControl']
            self.assistantProcess.start(app, args)
            if not self.assistantProcess.waitForStarted():
                QMessageBox.critical(None, "PyQt Demo",
                        "Could not start %s." % app)
                return

        # Send command through remote control even if the process was just
        # started to activate assistant and bring it to the front.
        cmd_str = QTextStream(self.assistantProcess)
        cmd_str << 'SetSource ' << url << '\n'
Esempio n. 57
0
def install_gettext_trans_under_qt(base_folder, lang=None):
    # So, we install the gettext locale, great, but we also should try to install qt_*.qm if
    # available so that strings that are inside Qt itself over which I have no control are in the
    # right language.
    from PyQt5.QtCore import QCoreApplication, QTranslator, QLocale, QLibraryInfo
    if not lang:
        lang = str(QLocale.system().name())[:2]
    localename = get_locale_name(lang)
    if localename is not None:
        try:
            locale.setlocale(locale.LC_ALL, localename)
        except locale.Error:
            logging.warning("Couldn't set locale %s", localename)
    qmname = 'qt_%s' % lang
    if ISLINUX:
        # Under linux, a full Qt installation is already available in the system, we didn't bundle
        # up the qm files in our package, so we have to load translations from the system.
        qmpath = op.join(QLibraryInfo.location(QLibraryInfo.TranslationsPath), qmname)
    else:
        qmpath = op.join(base_folder, qmname)
    qtr = QTranslator(QCoreApplication.instance())
    qtr.load(qmpath)
    QCoreApplication.installTranslator(qtr)
    install_gettext_trans(base_folder, lang)
Esempio n. 58
0
def tellall( The_QApplication = None ) :

    def fink(title=str, value=None) :
        if value : # is not None
            print( title, 'is:', value )
        else :
            print( title )

    from PyQt5.Qt import PYQT_VERSION_STR, QT_VERSION_STR
    fink( 'PyQt version', PYQT_VERSION_STR )
    fink( 'Qt version', QT_VERSION_STR )

    import sys
    if getattr( sys, 'frozen', False ) :
        fink( '_MEIPASS', sys._MEIPASS )
    else :
        fink( '(not frozen)' )

    import os
    fink( 'QTWEBENGINEPROCESS_PATH', os.environ.get('QTWEBENGINEPROCESS_PATH',None) )


    from PyQt5.QtCore import QLibraryInfo

    fink( 'Qt Prefix Path', QLibraryInfo.location( QLibraryInfo.PrefixPath ) )
    fink( 'Qt LibraryExecutables', QLibraryInfo.location( QLibraryInfo.LibraryExecutablesPath ) )
    fink( 'Qt Plugins Path', QLibraryInfo.location( QLibraryInfo.PluginsPath ) )
    fink( 'QML 2 Imports Path', QLibraryInfo.location( QLibraryInfo.Qml2ImportsPath ) )
    fink( 'Qt Data (resources) path', QLibraryInfo.location( QLibraryInfo.DataPath ) )
    fink( 'Qt arch-dep. data', QLibraryInfo.location( QLibraryInfo.ArchDataPath ) )
    fink( 'Qt Translations', QLibraryInfo.location( QLibraryInfo.TranslationsPath ) )

    if The_QApplication :
        fink( 'QApplication dir path', The_QApplication.applicationDirPath() )
        # QApplication.libraryPaths() returns a list of strings
        library_paths = The_QApplication.libraryPaths()
        for (index, one_path) in enumerate(library_paths) :
            fink( 'QApplication library path {}'.format(index), one_path )
Esempio n. 59
0
        "modules.</p>"
        "<p>It also sets the <tt>PYTHONPATH</tt> environment variable to the "
        "<tt>widgets</tt> directory that is also part of this example.  This "
        "directory contains the Python modules that implement the example "
        "custom widgets.</p>"
        "<p>All of the example custom widgets should then appear in "
        "Designer's widget box in the <b>PyQt Examples</b> group.</p>")

# Tell Qt Designer where it can find the directory containing the plugins and
# Python where it can find the widgets.
base = os.path.dirname(__file__)
env = QProcessEnvironment.systemEnvironment()
env.insert('PYQTDESIGNERPATH', os.path.join(base, 'python'))
env.insert('PYTHONPATH', os.path.join(base, 'widgets'))

# Start Designer.
designer = QProcess()
designer.setProcessEnvironment(env)

designer_bin = QLibraryInfo.location(QLibraryInfo.BinariesPath)

if sys.platform == 'darwin':
    designer_bin += '/Designer.app/Contents/MacOS/Designer'
else:
    designer_bin += '/designer'

designer.start(designer_bin)
designer.waitForFinished(-1)

sys.exit(designer.exitCode())