Example #1
0
def run(image_path = None):
    # Global exceptions
    sys.excepthook = excepthook

    app = QApplication(sys.argv) 

    # Splash screen
    splash_pix = QPixmap('resources/splash.jpg')
    splash = QSplashScreen(splash_pix)
    splash.setMask(splash_pix.mask())
    splash.show()
    
    app.processEvents()
    
    # Load translation
    locale_code = SettingsModel().get('Language', 'code')
    if locale_code != "en_US": # Standard language
        # Standard translator for the generated GUI
        translator = QTranslator()
        translator.load('localization/' + locale_code + '.qm')
        app.installTranslator(translator)

        # Translator for various GUI elements
        translator_2 = QTranslator()
        translator_2.load('localization/' + locale_code + '_2.qm')
        app.installTranslator(translator_2)

    # Start
    m = Hitagi(image_path) # Pass image path
    
    splash.finish(m)
    sys.exit(app.exec())
def main():
    # DBUS MainLoop
    if not dbus.get_default_main_loop():
        from dbus.mainloop.pyqt5 import DBusQtMainLoop
        DBusQtMainLoop(set_as_default = True)


    # Application Stuff
    from libhistorymanager.window import MainManager

    app = QApplication(sys.argv)
    app.setOrganizationName("history-manager")
    app.setApplicationName("history-manager")
    app.setApplicationVersion("0.2.8b")

    locale = QLocale.system().name()
    translator = QTranslator(app)
    translator.load(join("/usr/share/history-manager", "languages/{}.qm".format(locale)))
    app.installTranslator(translator)

    # Create Main Widget and make some settings
    mainWindow = MainManager(None, app= app)
    mainWindow.resize(640, 480)
    mainWindow.setWindowIcon(QIcon.fromTheme("view-history"))
    mainWindow.show()

    # Create connection for lastWindowClosed signal to quit app
    app.lastWindowClosed.connect(app.quit)

    # Run the applications
    app.exec_()
def main():
    app = QApplication([i.encode('utf-8') for i in sys.argv])
    app.setOrganizationName(ffmc.__name__)
    app.setOrganizationDomain(ffmc.__url__)
    app.setApplicationName('FF Multi Converter')
    app.setWindowIcon(QIcon(':/ffmulticonverter.png'))

    locale = QLocale.system().name()
    qtTranslator = QTranslator()
    if qtTranslator.load('qt_' + locale, ':/'):
        app.installTranslator(qtTranslator)
    appTranslator = QTranslator()
    if appTranslator.load('ffmulticonverter_' + locale, ':/'):
        app.installTranslator(appTranslator)

    if not os.path.exists(config.log_dir):
        os.makedirs(config.log_dir)

    logging.basicConfig(
            filename=config.log_file,
            level=logging.DEBUG,
            format=config.log_format,
            datefmt=config.log_dateformat
            )

    converter = MainWindow()
    converter.show()
    app.exec_()
Example #4
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_())
Example #5
0
def main():
    if settings.get('log:errors'):
        log_filename = settings.get('log:filename')
        if log_filename:
            try:
                log_file = open(log_filename,"w")
                print ('Redirecting stderr/stdout... to %s' % log_filename)
                sys.stderr = log_file
                sys.stdout = log_file
            except IOError:
                print("Lector could not open log file '%s'!\n" % log_filename \
                      + " Redirecting will not work.")
        else:
            print("Log file is not set. Please set it in settings.")

    app = QApplication(sys.argv)
    opts = [str(arg) for arg in app.arguments()[1:]]
    if '--no-scanner' in opts:
        scanner = False
    else:
        scanner = True
    qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime()))

    locale = settings.get('ui:lang')
    if not locale:
        locale = QLocale.system().name()
    qtTranslator = QTranslator()
    if qtTranslator.load(":/translations/ts/lector_" + locale, 'ts'):
        app.installTranslator(qtTranslator)

    window = Window(scanner)
    window.show()
    app.exec_()
Example #6
0
 def set(self, name):
     """
     Public slot to set a translator by name.
     
     @param name name (language) of the translator to set (string)
     """
     nTranslator = None
     
     if name != noTranslationName:
         trans = self.__findName(name)
         if trans is None:
             E5MessageBox.warning(
                 self.parent(),
                 self.tr("Set Translator"),
                 self.tr(
                     """<p>The translator <b>{0}</b> is not known.</p>""")
                 .format(name))
             return
             
         nTranslator = trans.translator
     
     if nTranslator == self.currentTranslator:
         return
     
     if self.currentTranslator is not None:
         QApplication.removeTranslator(self.currentTranslator)
     if nTranslator is not None:
         QApplication.installTranslator(nTranslator)
     self.currentTranslator = nTranslator
     
     self.selector.blockSignals(True)
     self.selector.setCurrentIndex(self.selector.findText(name))
     self.selector.blockSignals(False)
     
     self.translationChanged.emit()
def main():
    app = QApplication(sys.argv)
    locale = QLocale.system().name()
    conf = prepare.Config()
    local_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                             'data', 'locale'))
    translator = QTranslator()

    if not os.path.isfile(conf.config_file):
        if locale in prepare.LANGUISH.keys():
            conf.write_config('squares', 'gray', 30, 30,
                              prepare.LANGUISH[locale]['Lang'], __version__)
            translator.load(os.path.join(local_dir, 'pybigpixel_' +
                                         locale + '.qm'))
            app.installTranslator(translator)

        else:
            conf.write_config('squares', 'gray', 30, 30, 'English',
                              __version__)

    else:
        key = [key for key in prepare.LANGUISH.keys() if
               prepare.LANGUISH[key]['Lang'] == conf.get_languish()]

        if key[0] != 'default':
            translator.load(os.path.join(local_dir, 'pybigpixel_' +
                                         key[0] + '.qm'))
            app.installTranslator(translator)

    window = Window(conf)
    window.show()
    sys.exit(app.exec_())
Example #8
0
def start_gui():
    from .frontends import MainWindow

    app = QApplication(sys.argv)
    trans = QTranslator()
    trans.load(config['lang'], Constant.locale_dir)
    app.installTranslator(trans)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
Example #9
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())
Example #10
0
class Application(object):

    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)

        signal.signal(signal.SIGINT, lambda signum, stack: QCoreApplication.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._engine = Engine(config, KeyboardEmulation())

        self._win = MainWindow(self._engine, use_qt_notifications)

        self._app.aboutToQuit.connect(self._win.on_quit)

    def __del__(self):
        del self._win
        del self._app
        del self._engine
        del self._translator

    def run(self):
        self._app.exec_()
        self._engine.quit()
        self._engine.wait()
Example #11
0
def main():
    logging.basicConfig(level=logging.WARN,
                        format="%(asctime)s %(levelname)s %(message)s")
    app = QApplication(sys.argv)
    translator = QTranslator(app)
    path = os.path.dirname(rect.__file__)
    if QLocale.system().language() == QLocale.Japanese:
        translator.load(path+"/i18n/trainscanner_ja")
    app.installTranslator(translator)
    se = SettingsGUI()
    se.show()
    se.raise_()
    sys.exit(app.exec_())
Example #12
0
def main():
    #pyqt_set_trace()
    app = QApplication(sys.argv)
    translator = QTranslator(app)
    rpath = getattr(sys, '_MEIPASS', os.getcwd())
    loc = SystemLanguage()
    if loc[:2] == "ja":
        translator.load(rpath+"/i18n/trainscanner_ja")
    app.installTranslator(translator)
    se = SettingsGUI()
    se.show()
    se.raise_()
    sys.exit(app.exec_())
Example #13
0
def main():
    app = QApplication(sys.argv)
    parser = argparse.ArgumentParser()
    parser.add_argument("binary", nargs='?', help="Binary File to open.")
    parser.add_argument("-s", "--schema", help="Load schema file of binary format.")
    args = parser.parse_args()
    translator = QTranslator()
    app.installTranslator(translator)
    win = MainWindow()
    if args.schema:
        win.loadSchema(os.path.expanduser(args.schema))
    if args.binary:
        win.loadBinary(os.path.expanduser(args.binary))
    return app, win
Example #14
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_()
Example #15
0
def main():

    dirPath = dirname(__file__)

    app = QApplication(sys.argv)
    #app.setStyleSheet(open(join(dirPath, "data/kaptan.qss").read())

    locale = QLocale.system().name()
    translator = QTranslator(app)
    translator.load(join(dirPath, "languages/{}.qm".format(locale)))
    app.installTranslator(translator)

    kaptan = Kaptan()
    kaptan.show()
    app.exec_()
Example #16
0
def main():
    app = QApplication(sys.argv)
    app.setApplicationName("Kaptan")
    app.setOrganizationName("Kaptan")
    app.setApplicationVersion("5.0 Beta3")
    #app.setStyleSheet(open(join(dirPath, "data/libkaptan.qss").read())

    locale = QLocale.system().name()
    translator = QTranslator(app)
    translator.load("/usr/share/kaptan/languages/kaptan_{}.qm".format(locale))
    app.installTranslator(translator)

    kaptan = Kaptan()
    kaptan.show()
    app.exec_()
def _ensureQApplication():
    if not QApplication.instance():
        app = QApplication(["ubuntu-release-upgrader"])
        # Try to load default Qt translations so we don't have to worry about
        # QStandardButton translations.
        # FIXME: make sure we dep on l10n
        translator = QTranslator(app)
        if type(PYQT_VERSION) == int:
            translator.load(QLocale.system(), 'qt', '_',
                            '/usr/share/qt5/translations')
        else:
            translator.load(QLocale.system(), 'qt', '_',
                            '/usr/share/qt4/translations')
        app.installTranslator(translator)
        return app
    return QApplication.instance()
def main():
  sys.setrecursionlimit(60)  # to find infinite signal loops?
  
  app = QApplication(sys.argv)
  
  QCoreApplication.setOrganizationName("testPrintFramework")
  QCoreApplication.setOrganizationDomain("testPrintFramework.com")
  QCoreApplication.setApplicationName("testPrintFramework")
  
  # To test translations, in shell  >export LANG=es     or >export LANG=cn
  translator = QTranslator()
  result = translator.load("/home/bootch/Downloads/SubprojectsPensool/qtPrintFramework/resources/translations/qtPrintFramework_es.qm")
  if not result:
      print("Not load translation")
      # Not a failure nor exception: program continues in default (usually English)
  if not app.installTranslator(translator):
      print("Not install translator.")
  
  if config.useQML:
    from qtEmbeddedQmlFramework.resourceManager import resourceMgr
    resourceMgr.setResourceRoot(__file__, 'qtPrintFramework')
    
  mainWindow = MainWindow()
  mainWindow.show()
  sys.exit(app.exec_())
Example #19
0
def run():
    app = QApplication(sys.argv)
    app.setOrganizationName("manuskript")
    app.setOrganizationDomain("www.theologeek.ch")
    app.setApplicationName("manuskript")
    app.setApplicationVersion(_version)

    icon = QIcon()
    for i in [16, 31, 64, 128, 256, 512]:
        icon.addFile(appPath("icons/Manuskript/icon-{}px.png".format(i)))
    qApp.setWindowIcon(icon)

    app.setStyle("Fusion")

    # Load style from QSettings
    settings = QSettings(app.organizationName(), app.applicationName())
    if settings.contains("applicationStyle"):
        style = settings.value("applicationStyle")
        app.setStyle(style)

    # Translation process
    locale = QLocale.system().name()

    appTranslator = QTranslator()
    # By default: locale
    translation = appPath(os.path.join("i18n", "manuskript_{}.qm".format(locale)))

    # Load translation from settings
    if settings.contains("applicationTranslation"):
        translation = appPath(os.path.join("i18n", settings.value("applicationTranslation")))
        print("Found translation in settings:", translation)

    if appTranslator.load(translation):
        app.installTranslator(appTranslator)
        print(app.tr("Loaded translation: {}.").format(translation))

    else:
        print(app.tr("Warning: failed to load translator for locale {}...").format(locale))

    QIcon.setThemeSearchPaths(QIcon.themeSearchPaths() + [appPath("icons")])
    QIcon.setThemeName("NumixMsk")
    # qApp.setWindowIcon(QIcon.fromTheme("im-aim"))

    # Seperating launch to avoid segfault, so it seem.
    # Cf. http://stackoverflow.com/questions/12433491/is-this-pyqt-4-python-bug-or-wrongly-behaving-code
    launch()
Example #20
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())
Example #21
0
def gui():
    app = QApplication(sys.argv)

    translator = QTranslator()
    if translator.load('wise_'+ QLocale.system().name()+'.qm',":/translations/"):
        app.installTranslator(translator)

    translator_qt = QTranslator()
    if translator_qt.load('qt_'+ QLocale.system().name()+'.qm',":/translations/"):
        print('i found qt')
        app.installTranslator(translator_qt)


    timer = Timer()
    def beep():
        print('\a')
    timer.timeout.connect(beep)
    timer.show()
    sys.exit(app.exec_())
Example #22
0
def main(argv=None):
    if not argv:
        argv = sys.argv

    app = QApplication(argv)

    translator = QTranslator()
    translator.load("qt_" + QLocale.system().name(), os.path.join(
        getResourcesPath(), "translations"))
    app.installTranslator(translator)

    myTranslator = QTranslator()
    myTranslator.load("Tiles_" + QLocale.system().name(), os.path.join(
        getResourcesPath(), "translations"))
    app.installTranslator(myTranslator)

    window = MainWindow()
    window.show()
    return app.exec_()
Example #23
0
def main():
    app = QApplication(sys.argv)

    translator = QTranslator()
    if translator.load('editor_'+ QLocale.system().name()+'.qm',":/translations/"):
        app.installTranslator(translator)

    translator_qt = QTranslator()
    if translator_qt.load('qt_'+ QLocale.system().name()+'.qm',":/translations/"):
    #    print('i found qt')
        app.installTranslator(translator_qt)


    mainwindow = Editor()
    mainwindow.setWindowTitle('simple text editor')
    mainwindow.setWindowIcon(QIcon(':/icons/editor.ico'))
    mainwindow.show()

    sys.exit(app.exec_())
Example #24
0
    def checkBoxToggled(self):
        checkBox = self.sender()
        window = self.mainWindowForCheckBoxMap.get(checkBox)

        if not window:
            translator = QTranslator()
            translator.load(self.qmFileForCheckBoxMap[checkBox])
            QApplication.installTranslator(translator)

            # Because we will be installing an event filter for the main window
            # it is important that this instance isn't garbage collected before
            # the main window when the program terminates.  We ensure this by
            # making the main window a child of this one.
            window = MainWindow(self)
            window.setPalette(QPalette(self.colorForLanguage(checkBox.text())))

            window.installEventFilter(self)
            self.mainWindowForCheckBoxMap[checkBox] = window

        window.setVisible(checkBox.isChecked())
Example #25
0
File: Start.py Project: nixz/covise
def main():
    import sys
    import os
    

    global qapp 
    qapp = QApplication(sys.argv)
    
    # translation of standard dialogs BEGIN #
    
    if os.getenv('QT_HOME') != None:
        translationsPath = os.getenv('QT_HOME') + os.sep + "translations"
        qtTranslator = QtCore.QTranslator()
        succ = qtTranslator.load("qt_%s" % languageLocale,  translationsPath)
        
        if (succ != True):
            print("Translator for standard dialogs not loaded!")
        else:
            qapp.installTranslator(qtTranslator)
    
    # translation of standard dialogs BEGIN #
    
    ui = MainWindow()
    vrpApp.mw = ui # global hook
    
    # removes the message "event loop already running" when using pdb
    QtCore.pyqtRemoveInputHook()

    # Set up connections. Needs Neg2Gui and Gui2Neg
    initHandlers(vrpApp.mw.coverWidgetId)
    if os.getenv('COVISE_HIDDEN') == "1":
        vrpApp.mw.hide()
    else:
        vrpApp.mw.show()
    acceptedOrRejected = vrpApp.mw.openInitialDialog()
    if acceptedOrRejected == QtWidgets.QDialog.Accepted:
        qapp.exec_()

    covise.clean()
    covise.quit()
class DistUpgradeViewKDE(DistUpgradeView):
    """KDE frontend of the distUpgrade tool"""
    def __init__(self, datadir=None, logdir=None):
        DistUpgradeView.__init__(self)
        # silence the PyQt4 logger
        logger = logging.getLogger("PyQt4")
        logger.setLevel(logging.INFO)
        if not datadir or datadir == '.':
          localedir=os.path.join(os.getcwd(),"mo")
        else:
          localedir="/usr/share/locale/ubuntu-release-upgrader"

        # FIXME: i18n must be somewhere relative do this dir
        try:
          gettext.bindtextdomain("ubuntu-release-upgrader", localedir)
          gettext.textdomain("ubuntu-release-upgrader")
        except Exception as e:
          logging.warning("Error setting locales (%s)" % e)

        # we test for DISPLAY here, QApplication does not throw a 
        # exception when run without DISPLAY but dies instead
        if not "DISPLAY" in os.environ:
            raise Exception("No DISPLAY in os.environ found")
        self.app = QApplication(["ubuntu-release-upgrader"])

        # Try to load default Qt translations so we don't have to worry about
        # QStandardButton translations.
        translator = QTranslator(self.app)
        if type(PYQT_VERSION) == int:
            translator.load(QLocale.system(), 'qt', '_', '/usr/share/qt5/translations')
        else:
            translator.load(QLocale.system(), 'qt', '_', '/usr/share/qt4/translations')
        self.app.installTranslator(translator)

        QUrlOpener().setupUrlHandles()

        if os.path.exists("/usr/share/icons/oxygen/48x48/apps/system-software-update.png"):
            messageIcon = QPixmap("/usr/share/icons/oxygen/48x48/apps/system-software-update.png")
        else:
            messageIcon = QPixmap("/usr/share/icons/hicolor/48x48/apps/adept_manager.png")
        self.app.setWindowIcon(QIcon(messageIcon))

        self.window_main = UpgraderMainWindow()
        self.window_main.setParent(self)
        self.window_main.show()

        self.prev_step = 0 # keep a record of the latest step

        self._opCacheProgress = KDEOpProgress(self.window_main.progressbar_cache, self.window_main.progress_text)
        self._acquireProgress = KDEAcquireProgressAdapter(self)
        self._cdromProgress = KDECdromProgressAdapter(self)

        self._installProgress = KDEInstallProgressAdapter(self)

        # reasonable fault handler
        sys.excepthook = self._handleException

        self.window_main.showTerminalButton.setEnabled(False)
        self.window_main.showTerminalButton.clicked.connect(self.showTerminal)

        # init gettext
        gettext.bindtextdomain("ubuntu-release-upgrader",localedir)
        gettext.textdomain("ubuntu-release-upgrader")
        self.translate_widget_children()
        self.window_main.label_title.setText(self.window_main.label_title.text().replace("Ubuntu", "Kubuntu"))

        # setup terminal text in hidden by default spot
        self.window_main.konsole_frame.hide()
        self.konsole_frame_layout = QHBoxLayout(self.window_main.konsole_frame)
        self.window_main.konsole_frame.setMinimumSize(600, 400)
        self.terminal_text = DumbTerminal(self._installProgress, self.window_main.konsole_frame)
        self.konsole_frame_layout.addWidget(self.terminal_text)
        self.terminal_text.show()

        # for some reason we need to start the main loop to get everything displayed
        # this app mostly works with processEvents but run main loop briefly to keep it happily displaying all widgets
        QTimer.singleShot(10, self.exitMainLoop)
        self.app.exec_()

    def exitMainLoop(self):
        print("exitMainLoop")
        self.app.exit()

    def translate_widget_children(self, parentWidget=None):
        if parentWidget == None:
            parentWidget = self.window_main
        if isinstance(parentWidget, QDialog) or isinstance(parentWidget, QWidget):
            if str(parentWidget.windowTitle()) == "Error":
                parentWidget.setWindowTitle( gettext.dgettext("kdelibs", "Error"))
            else:
                parentWidget.setWindowTitle(_( str(parentWidget.windowTitle()) ))

        if parentWidget.children() != None:
            for widget in parentWidget.children():
                self.translate_widget(widget)
                self.translate_widget_children(widget)

    def translate_widget(self, widget):
        if isinstance(widget, QLabel) or isinstance(widget, QPushButton):
            if str(widget.text()) == "&Cancel":
                kdelibs = gettext.translation(
                    "kdelibs", gettext.textdomain("kdelibs"), fallback=True)
                widget.setText(unicode_gettext(kdelibs, "&Cancel"))
            elif str(widget.text()) == "&Close":
                kdelibs = gettext.translation(
                    "kdelibs", gettext.textdomain("kdelibs"), fallback=True)
                widget.setText(unicode_gettext(kdelibs, "&Close"))
            elif str(widget.text()) != "":
                widget.setText( _(str(widget.text())).replace("_", "&") )

    def _handleException(self, exctype, excvalue, exctb):
        """Crash handler."""

        if (issubclass(exctype, KeyboardInterrupt) or
            issubclass(exctype, SystemExit)):
            return

        # we handle the exception here, hand it to apport and run the
        # apport gui manually after it because we kill u-m during the upgrade
        # to prevent it from popping up for reboot notifications or FF restart
        # notifications or somesuch
        lines = traceback.format_exception(exctype, excvalue, exctb)
        logging.error("not handled exception in KDE frontend:\n%s" % "\n".join(lines))
        # we can't be sure that apport will run in the middle of a upgrade
        # so we still show a error message here
        apport_crash(exctype, excvalue, exctb)
        if not run_apport():
            tbtext = ''.join(traceback.format_exception(exctype, excvalue, exctb))
            dialog = QDialog(self.window_main)
            loadUi("dialog_error.ui", dialog)
            self.translate_widget_children(self.dialog)
            dialog.crash_detail.setText(tbtext)
            # Make sure we have a suitable size depending on whether or not the view is shown
            dialog.adjustSize()
            dialog.exec_()
        sys.exit(1)

    def showTerminal(self):
        if self.window_main.konsole_frame.isVisible():
            self.window_main.konsole_frame.hide()
            self.window_main.showTerminalButton.setText(_("Show Terminal >>>"))
        else:
            self.window_main.konsole_frame.show()
            self.window_main.showTerminalButton.setText(_("<<< Hide Terminal"))
        self.window_main.resize(self.window_main.sizeHint())

    def getAcquireProgress(self):
        return self._acquireProgress

    def getInstallProgress(self, cache):
        self._installProgress._cache = cache
        return self._installProgress

    def getOpCacheProgress(self):
        return self._opCacheProgress

    def getCdromProgress(self):
        return self._cdromProgress

    def update_status(self, msg):
        self.window_main.label_status.setText(msg)

    def hideStep(self, step):
        image = getattr(self.window_main,"image_step%i" % step)
        label = getattr(self.window_main,"label_step%i" % step)
        image.hide()
        label.hide()

    def abort(self):
        step = self.prev_step
        if step > 0:
            image = getattr(self.window_main,"image_step%i" % step)
            if os.path.exists("/usr/share/icons/oxygen/16x16/actions/dialog-cancel.png"):
                cancelIcon = QPixmap("/usr/share/icons/oxygen/16x16/actions/dialog-cancel.png")
            elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-cancel.png"):
                cancelIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-cancel.png")
            else:
                cancelIcon = QPixmap("/usr/share/icons/crystalsvg/16x16/actions/cancel.png")
            image.setPixmap(cancelIcon)
            image.show()

    def setStep(self, step):
        if os.path.exists("/usr/share/icons/oxygen/16x16/actions/dialog-ok.png"):
            okIcon = QPixmap("/usr/share/icons/oxygen/16x16/actions/dialog-ok.png")
        elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-ok.png"):
            okIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-ok.png")
        else:
            okIcon = QPixmap("/usr/share/icons/crystalsvg/16x16/actions/ok.png")

        if os.path.exists("/usr/share/icons/oxygen/16x16/actions/arrow-right.png"):
            arrowIcon = QPixmap("/usr/share/icons/oxygen/16x16/actions/arrow-right.png")
        elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/16x16/actions/arrow-right.png"):
            arrowIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/16x16/actions/arrow-right.png")
        else:
            arrowIcon = QPixmap("/usr/share/icons/crystalsvg/16x16/actions/1rightarrow.png")

        if self.prev_step:
            image = getattr(self.window_main,"image_step%i" % self.prev_step)
            label = getattr(self.window_main,"label_step%i" % self.prev_step)
            image.setPixmap(okIcon)
            image.show()
            ##arrow.hide()
        self.prev_step = step
        # show the an arrow for the current step and make the label bold
        image = getattr(self.window_main,"image_step%i" % step)
        label = getattr(self.window_main,"label_step%i" % step)
        image.setPixmap(arrowIcon)
        image.show()
        label.setText("<b>" + label.text() + "</b>")

    def information(self, summary, msg, extended_msg=None):
        msg = "<big><b>%s</b></big><br />%s" % (summary,msg)

        dialogue = QDialog(self.window_main)
        loadUi("dialog_error.ui", dialogue)
        self.translate_widget_children(dialogue)
        dialogue.label_error.setText(msg)
        if extended_msg != None:
            dialogue.textview_error.setText(extended_msg)
            dialogue.textview_error.show()
        else:
            dialogue.textview_error.hide()
        dialogue.setWindowTitle(_("Information"))

        if os.path.exists("/usr/share/icons/oxygen/48x48/status/dialog-information.png"):
            messageIcon = QPixmap("/usr/share/icons/oxygen/48x48/status/dialog-information.png")
        elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-information.png"):
            messageIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-information.png")
        else:
            messageIcon = QPixmap("/usr/share/icons/crystalsvg/32x32/actions/messagebox_info.png")
        dialogue.image.setPixmap(messageIcon)
        # Make sure we have a suitable size depending on whether or not the view is shown
        dialogue.adjustSize()
        dialogue.exec_()

    def error(self, summary, msg, extended_msg=None):
        msg="<big><b>%s</b></big><br />%s" % (summary, msg)

        dialogue = QDialog(self.window_main)
        loadUi("dialog_error.ui", dialogue)
        self.translate_widget_children(dialogue)
        dialogue.label_error.setText(msg)
        if extended_msg != None:
            dialogue.textview_error.setText(extended_msg)
            dialogue.textview_error.show()
        else:
            dialogue.textview_error.hide()

        if os.path.exists("/usr/share/icons/oxygen/48x48/status/dialog-error.png"):
            messageIcon = QPixmap("/usr/share/icons/oxygen/48x48/status/dialog-error.png")
        elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-error.png"):
            messageIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-error.png")
        else:
            messageIcon = QPixmap("/usr/share/icons/crystalsvg/32x32/actions/messagebox_critical.png")
        dialogue.image.setPixmap(messageIcon)
        # Make sure we have a suitable size depending on whether or not the view is shown
        dialogue.adjustSize()
        dialogue.exec_()

        return False

    def confirmChanges(self, summary, changes, demotions, downloadSize, 
                       actions=None, removal_bold=True):
        """show the changes dialogue"""
        # FIXME: add a whitelist here for packages that we expect to be
        # removed (how to calc this automatically?)
        DistUpgradeView.confirmChanges(self, summary, changes, demotions, 
                                       downloadSize)
        self.changesDialogue = QDialog(self.window_main)
        loadUi("dialog_changes.ui", self.changesDialogue)

        self.changesDialogue.treeview_details.hide()
        self.changesDialogue.buttonBox.helpRequested.connect(self.showChangesDialogueDetails)
        self.translate_widget_children(self.changesDialogue)
        self.changesDialogue.buttonBox.button(QDialogButtonBox.Ok).setText(_("&Start Upgrade"))
        self.changesDialogue.buttonBox.button(QDialogButtonBox.Help).setIcon(QIcon())
        self.changesDialogue.buttonBox.button(QDialogButtonBox.Help).setText(_("Details") + " >>>")
        self.changesDialogue.resize(self.changesDialogue.sizeHint())

        if os.path.exists("/usr/share/icons/oxygen/48x48/status/dialog-warning.png"):
            warningIcon = QPixmap("/usr/share/icons/oxygen/48x48/status/dialog-warning.png")
        elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-warning.png"):
            warningIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-warning.png")
        else:
            warningIcon = QPixmap("/usr/share/icons/crystalsvg/32x32/actions/messagebox_warning.png")

        self.changesDialogue.question_pixmap.setPixmap(warningIcon)

        if actions != None:
            cancel = actions[0].replace("_", "")
            self.changesDialogue.buttonBox.button(QDialogButtonBox.Cancel).setText(cancel)
            confirm = actions[1].replace("_", "")
            self.changesDialogue.buttonBox.button(QDialogButtonBox.Ok).setText(confirm)

        summaryText = "<big><b>%s</b></big>" % summary
        self.changesDialogue.label_summary.setText(summaryText)
        self.changesDialogue.label_changes.setText(self.confirmChangesMessage)
        # fill in the details
        self.changesDialogue.treeview_details.clear()
        self.changesDialogue.treeview_details.setHeaderLabels(["Packages"])
        self.changesDialogue.treeview_details.header().hide()
        for demoted in self.demotions:
            self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("No longer supported %s") % demoted.name]) )
        for rm in self.toRemove:
            self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Remove %s") % rm.name]) )
        for rm in self.toRemoveAuto:
            self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Remove (was auto installed) %s") % rm.name]) )
        for inst in self.toInstall:
            self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Install %s") % inst.name]) )
        for up in self.toUpgrade:
            self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Upgrade %s") % up.name]) )

        #FIXME resize label, stop it being shrinkable
        res = self.changesDialogue.exec_()
        if res == QDialog.Accepted:
            return True
        return False

    def showChangesDialogueDetails(self):
        if self.changesDialogue.treeview_details.isVisible():
            self.changesDialogue.treeview_details.hide()
            self.changesDialogue.buttonBox.button(QDialogButtonBox.Help).setText(_("Details") + " >>>")
            # Make sure we shrink the dialog otherwise it looks silly
            self.changesDialogue.adjustSize()
        else:
            self.changesDialogue.treeview_details.show()
            self.changesDialogue.buttonBox.button(QDialogButtonBox.Help).setText("<<< " + _("Details"))
        self.changesDialogue.resize(self.changesDialogue.sizeHint())

    def askYesNoQuestion(self, summary, msg, default='No'):
        answer = QMessageBox.question(self.window_main, summary, "<font>" + msg, QMessageBox.Yes|QMessageBox.No, QMessageBox.No)
        if answer == QMessageBox.Yes:
            return True
        return False

    def confirmRestart(self):
        messageBox = QMessageBox(QMessageBox.Question, _("Restart required"), _("<b><big>Restart the system to complete the upgrade</big></b>"), QMessageBox.NoButton, self.window_main)
        yesButton = messageBox.addButton(QMessageBox.Yes)
        noButton = messageBox.addButton(QMessageBox.No)
        yesButton.setText(_("_Restart Now").replace("_", "&"))
        noButton.setText(gettext.dgettext("kdelibs", "&Close"))
        answer = messageBox.exec_()
        if answer == QMessageBox.Yes:
            return True
        return False

    def processEvents(self):
        QApplication.processEvents()

    def pulseProgress(self, finished=False):
        # FIXME: currently we do nothing here because this is
        # run in a different python thread and QT explodes if the UI is
        # touched from a non QThread
        pass

    def on_window_main_delete_event(self):
        #FIXME make this user friendly
        text = _("""<b><big>Cancel the running upgrade?</big></b>

The system could be in an unusable state if you cancel the upgrade. You are strongly advised to resume the upgrade.""")
        text = text.replace("\n", "<br />")
        cancel = QMessageBox.warning(self.window_main, _("Cancel Upgrade?"), text, QMessageBox.Yes, QMessageBox.No)
        if cancel == QMessageBox.Yes:
            return True
        return False
Example #27
0
#!/usr/bin/env python3
import sys
import fix_qt_import_error

from PyQt5.QtCore import QTranslator, QLocale, QLibraryInfo
from PyQt5.QtWidgets import QApplication

from ui.Main import Main

if __name__ == '__main__':
    # create application
    app = QApplication(sys.argv)

    # install translator
    qtSystemTranslator = QTranslator()
    qtSystemTranslator.load(
        QLocale.system().name(),
        QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    qtTranslator = QTranslator()
    qtTranslator.load(QLocale.system().name() + '.qm', 'translations')
    app.installTranslator(qtTranslator)
    app.installTranslator(qtSystemTranslator)

    # create and show window
    window = Main()
    window.show()
    sys.exit(app.exec_())
Example #28
0
    
    signal.signal(signal.SIGINT, signalHandler)
    signal.signal(signal.SIGTERM, signalHandler)

    # Translation process
    locale = QLocale.system().name()
    appTranslator = QTranslator()
    
    if appTranslator.load(
        "%s/locale/raysession_%s" %
        (os.path.dirname(
            os.path.dirname(
                os.path.dirname(
                    sys.argv[0]))),
         locale)):
        app.installTranslator(appTranslator)
    _translate = app.translate

    timer = QTimer()
    timer.setInterval(200)
    timer.timeout.connect(lambda: None)
    timer.start()

    signaler = nsm_client.NSMSignaler()
    
    server = nsm_client.NSMThread('ray-proxy', signaler,
                                  daemon_address, debug)
    server.start()
    
    proxy = Proxy(executable)
    proxy_dialog = ProxyDialog()
Example #29
0
EXT_GUI = True

if __name__ == "__main__":
    # Default material data path

    # Script to be used to test in dev
    a = QApplication(argv)

    # Set CSS
    # a.setStyleSheet("QLineEdit { background-color: yellow }")

    # Setup the translation
    translationFile = "pyleecan_fr.qm"
    translator = QTranslator()
    translator.load(translationFile, "GUI//i18n")
    a.installTranslator(translator)

    # Machine Setup Widget
    c = DMachineSetup(machine_path=join(DATA_DIR, "Machine"),
                      matlib_path=MATLIB_DIR)

    if EXT_GUI:
        # Setup extended GUI with sub windows
        icon = dirname(__file__) + "/GUI/Resources/images/icon/pyleecan_64.png"
        window = SidebarWindow()
        window.setWindowIcon(QIcon(icon))

        update_step = lambda: c.set_nav(c.nav_step.currentRow())
        window.addSubWindow("Design", c, update_step)
        window.DesignWidget = c
    @staticmethod
    def open_link(link):
        """
        Opens link in browser
        """
        QDesktopServices.openUrl(QUrl(link))
        logging.info(f'{link} opened')

    def open_about(self):
        """
        Opens About box
        """
        self.about_box.setup_ui(self.about_box)
        self.about_box.show()


if __name__ == '__main__':
    logging.basicConfig(filename='data/last_run.log', filemode='w',
                        format='(%(asctime)s) - %(name)s - %(levelname)s - %(message)s',
                        datefmt='%d-%b-%y %H:%M:%S',
                        level=logging.INFO)
    APP = QApplication(sys.argv)
    SETTINGS = load_settings()
    LANG = SETTINGS['language']
    logging.info(f'Language {LANG} loaded')
    TRANSLATOR = QtCore.QTranslator(APP)
    TRANSLATOR.load(f'i18n/{LANG}.qm')
    APP.installTranslator(TRANSLATOR)
    WINDOW = MainWindowUi()
    sys.exit(APP.exec_())
Example #31
0
        )
        self.connect = db.connect(filename, self.err_callback)
        #TODO récupérer les projets

    def newDB(self):
        filename, filter = QFileDialog().getSaveFileName(
            caption=self.tr("Creer un nouveau fichier DB"),
            filter=self.tr("Fichier DB (*.db)"))
        self.connect = db.connect(filename, self.err_callback)
        db.create_tables(self.connect, self.err_callback)

    def err_callback(self, message):
        QMessageBox.critical(title=self.tr("Erreur"), text=message)


# Lancement du programme principal
if __name__ == '__main__':  # Recette de cuisine n°2 ligne 1
    app = QApplication(sys.argv)  # ligne 2
    # Recette de cuisine du traducteur
    translator = QTranslator()
    if len(sys.argv) == 1:  # si pas de langue spécifiée
        locale = QLocale()
        translator.load(locale, "i18n", ".")  # nom du fichier de traduction
    else:
        translator.load("i18n." + sys.argv[1])  # on charge la langue indiquée
    app.installTranslator(translator)  # on installe le traducteur
    # fin de la recette du traducteur
    window = Application()  # ligne 3, on appelle la "class" au-dessus
    window.show()  # ligne 4, on affiche l’écran
    app.exec_()  # ligne 5, on démarre l’application
Example #32
0
def main():
    try:
        locale.setlocale(locale.LC_ALL, '')
    except:
        # Work around system locale not specified (under Linux or Mac OS)
        pass

    app = QApplication(sys.argv)

    QCoreApplication.setOrganizationName(version.Company)
    QCoreApplication.setApplicationName(version.AppName)

    if OpenNumismat.PORTABLE:
        QCoreApplication.setOrganizationName('.')
        QSettings.setDefaultFormat(QSettings.IniFormat)
        QSettings.setPath(QSettings.IniFormat, QSettings.UserScope,
                          OpenNumismat.PRJ_PATH)

    settings = Settings()
    if settings['error']:
        sys.excepthook = exceptHook

    if not os.path.exists(settings['reference']):
        # Create default dirs and files if not exists
        try:
            ref_path = os.path.dirname(settings['reference'])
            dst_ref = os.path.join(ref_path, 'reference.ref')
            if not os.path.exists(dst_ref):
                os.makedirs(ref_path, exist_ok=True)
                src_ref = os.path.join(OpenNumismat.PRJ_PATH, 'db',
                                   'reference_%s.ref' % settings['locale'])
                if not os.path.exists(src_ref):
                    src_ref = os.path.join(OpenNumismat.PRJ_PATH, 'db',
                                       'reference_en.ref')

                shutil.copy(src_ref, dst_ref)

            dst_demo_db = os.path.join(OpenNumismat.HOME_PATH, 'demo.db')
            if not os.path.exists(dst_demo_db):
                os.makedirs(OpenNumismat.HOME_PATH, exist_ok=True)
                src_demo_db = os.path.join(OpenNumismat.PRJ_PATH, 'db',
                                           'demo_%s.db' % settings['locale'])
                if not os.path.exists(src_demo_db):
                    src_demo_db = os.path.join(OpenNumismat.PRJ_PATH, 'db',
                                       'demo_en.ref')

                shutil.copy(src_demo_db, dst_demo_db)

            templates_path = os.path.join(OpenNumismat.HOME_PATH, 'templates')
            os.makedirs(templates_path, exist_ok=True)
        except:
            pass

    TemporaryDir.init(version.AppName)

    lang = settings['locale']

    translator = QTranslator()
    translator.load('translations/lang_' + lang, OpenNumismat.PRJ_PATH)
    app.installTranslator(translator)

    translatorQt = QTranslator()
    translatorQt.load('translations/qtbase_' + lang, OpenNumismat.PRJ_PATH)
    app.installTranslator(translatorQt)

    if not settings['verify_ssl']:
        ssl._create_default_https_context = ssl._create_unverified_context

    mainWindow = MainWindow()
    mainWindow.show()
    mainWindow.raise_()  # this will raise the window on Mac OS X
    status = app.exec_()

    # Clear temporary files
    TemporaryDir.remove()

    sys.exit(status)
Example #33
0
            self.app_win.addFiles([event.file()])
            return True
        else:
            return super(AppEventFilter, self).eventFilter(receiver, event)


if __name__ == '__main__':
    app = QApplication(sys.argv)

    app_path = os.path.normpath(fb2mobi.get_executable_path())
    locale_path = os.path.join(app_path, 'ui/locale')
    locale = QLocale.system().name()[:2]

    qt_translator = QTranslator()
    qt_translator.load(os.path.join(locale_path, 'qtbase_' + locale + '.qm'))
    app.installTranslator(qt_translator)

    app_translator = QTranslator()
    app_translator.load(os.path.join(locale_path, 'fb2mobi_' + locale + '.qm'))
    app.installTranslator(app_translator)

    app.setStyleSheet('QStatusBar::item { border: 0px }');

    mainAppWindow = MainAppWindow()
    mainAppWindow.show()

    appEventFilter = AppEventFilter(mainAppWindow)
    app.installEventFilter(appEventFilter)

    sys.exit(app.exec_())
Example #34
0
from res import resources

os.environ["OMP_THREAD_LIMIT"] = "1"

if __name__ == "__main__":
    app = QApplication(sys.argv)

    # Load settings
    app_settings = Settings()

    # translation settings
    app_translator = QTranslator()
    app_translator.load(":/translations/application_" +
                        Settings.ApplicationLang)

    schedule_translator = QTranslator()
    schedule_translator.load(":/translations/schedule_" +
                             Settings.ScheduleLang)

    app.installTranslator(app_translator)
    app.installTranslator(schedule_translator)

    Settings.ApplicationTranslator = app_translator
    Settings.ScheduleTranslator = schedule_translator

    # application setup
    w = ScheduleEditorWindow()
    w.show()

    sys.exit(app.exec_())
Example #35
0
def main():
	multiprocessing.set_start_method('spawn')

	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')

	try:
		# See https://github.com/retext-project/retext/issues/399
		# and https://launchpad.net/bugs/941826
		ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL)
	except OSError:
		pass

	# Needed for Qt WebEngine on Windows
	QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
	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)

	parser = QCommandLineParser()
	parser.addHelpOption()
	parser.addVersionOption()
	previewOption = QCommandLineOption('preview',
		QApplication.translate('main', 'Open the files in preview mode'))
	newWindowOption = QCommandLineOption('new-window',
		QApplication.translate('main', 'Create a new window even if there is an existing one'))
	parser.addOption(previewOption)
	parser.addOption(newWindowOption)
	parser.addPositionalArgument('files',
		QApplication.translate('main', 'List of files to open'),
		'[files...]')

	parser.process(app)
	filesToOpen = parser.positionalArguments()

	initializeDataDirs()
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qtbase_" + 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()

	openInExistingWindow = (globalSettings.openFilesInExistingWindow
		and not parser.isSet(newWindowOption))
	connection = QDBusConnection.sessionBus()
	if connection.isConnected() and openInExistingWindow:
		connection.registerObject('/', window, QDBusConnection.ExportAllSlots)
		serviceName = 'me.mitya57.ReText'
		if not connection.registerService(serviceName) and filesToOpen:
			print('Opening the file(s) in the existing window of ReText.')
			iface = QDBusInterface(serviceName, '/', '', connection)
			for fileName in filesToOpen:
				iface.call('openFileWrapper', fileName)
			qWidgetIface = QDBusInterface(serviceName, '/', 'org.qtproject.Qt.QWidget', connection)
			qWidgetIface.call('raise')
			sys.exit(0)

	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, filesToOpen))
	readStdIn = False

	if globalSettings.openLastFilesOnStartup:
		window.restoreLastOpenedFiles()
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if parser.isSet(previewOption):
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '-':
			readStdIn = True

	inputData = ''
	if readStdIn and sys.stdin is not None:
		if sys.stdin.isatty():
			print('Reading stdin, press ^D to end...')
		inputData = 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())
Example #36
0
            "ign": "534fff80a3a7292c64a77e41",
            "insee": "534fff81a3a7292c64a77e5c",
            "isogeo": "54a13044c751df096c04805a",
        }
        org = "ign"
        org_ds = self.client_dg.org_datasets(org_id=orgas.get(org))

        self.winTitler(window=self,
                       new_title="{} results on {}".format(
                           org_ds.get("total"), org))
        pass


# #############################################################################
# ##### Stand alone program ########
# ##################################
if __name__ == "__main__":
    import sys
    # create the application and the main window
    app = QApplication(sys.argv)
    # languages
    locale_path = path.join(
        app_dir, 'i18n',
        'datagouvfrbrowser_{}.qm'.format(current_locale.system().name()))
    translator = QTranslator()
    translator.load(path.realpath(locale_path))
    app.installTranslator(translator)
    # ui execution
    searchForm = DataGouvFrBrowser_Main()
    sys.exit(app.exec_())
Example #37
0
def main(argv):
    global server_thread
    print("Starting %s %s..." % (common.app_name, common.app_version))
    print("""         __
        /  \_
     __(     )_
   _(          \_
 _(              )_
(__________________)
""")
    app = QApplication(argv)
    
    network.setup()
    filtering.setup()
    
    # Create extension server.
    server_thread = extension_server.ExtensionServerThread(QCoreApplication.instance())
    
    # Start DBus loop
    if has_dbus:
        print("DBus available. Creating main loop...", end=" ")
        mainloop = DBusQtMainLoop(set_as_default = True)
        dbus.set_default_main_loop(mainloop)
        print("done.")
    else:
        print("DBus unavailable.")

    # Create app.
    app.setApplicationName(common.app_name)
    app.setApplicationVersion(common.app_version)
    app.installTranslator(translate.translator)

    # We want Nimbus to stay open when the last window is closed,
    # so we set this.
    app.setQuitOnLastWindowClosed(False)

    # If D-Bus is present...
    if has_dbus:
        print("Creating DBus session bus...", end=" ")
        try:
            bus = dbus.SessionBus()
        except:
            print("failed.")
        else:
            print("done.")

    try:
        print("Checking for running instances of %s..." % (common.app_name,), end=" ")
        proxy = bus.get_object("org.nimbus.%s" % (common.app_name,), "/%s" % common.app_name,)
    except:
        dbus_present = False
    else:
        dbus_present = True
    print("done.")

    # If Nimbus detects the existence of another Nimbus process, it
    # will send all the requested URLs to the existing process and
    # exit.
    if dbus_present:
        print("An instance of Nimbus is already running. Passing arguments via DBus.")
        for arg in argv[1:]:
            proxy.addTab(arg)
        if len(argv) < 2:
            proxy.addWindow()
        return
    elif has_dbus:
        print("No prior instances found. Continuing on our merry way.")

    # Hack together the browser's icon. This needs to be improved.
    common.app_icon = common.complete_icon("nimbus")

    app.setWindowIcon(common.app_icon)

    common.searchEditor = search_manager.SearchEditor()
    common.downloadManager = DownloadManager(windowTitle=tr("Downloads"))
    common.downloadManager.resize(QSize(480, 320))
    common.downloadManager.loadSession()

    # Create tray icon.
    common.trayIcon = SystemTrayIcon()
    common.trayIcon.newWindowRequested.connect(addWindow)
    #common.trayIcon.windowReopenRequested.connect(reopenWindow)
    common.trayIcon.show()

    # Creates a licensing information dialog.
    common.licenseDialog = custom_widgets.LicenseDialog()

    # Create instance of clear history dialog.
    common.chistorydialog = clear_history_dialog.ClearHistoryDialog()

    uc = QUrl.fromUserInput(settings.user_css)
    websettings = QWebSettings.globalSettings()
    websettings.setUserStyleSheetUrl(uc)
    websettings.enablePersistentStorage(settings.settings_folder)
    websettings.setAttribute(websettings.LocalContentCanAccessRemoteUrls, True)
    websettings.setAttribute(websettings.LocalContentCanAccessFileUrls, True)
    websettings.setAttribute(websettings.DeveloperExtrasEnabled, True)
    try: websettings.setAttribute(websettings.ScrollAnimatorEnabled, True)
    except: pass
    common.applyWebSettings()

    # Set up settings dialog.
    settings.settingsDialog = settings_dialog.SettingsDialog()
    settings.settingsDialog.setWindowFlags(Qt.Dialog)
    closeSettingsDialogAction = QAction(settings.settingsDialog)
    closeSettingsDialogAction.setShortcuts(["Esc", "Ctrl+W"])
    closeSettingsDialogAction.triggered.connect(settings.settingsDialog.hide)
    settings.settingsDialog.addAction(closeSettingsDialogAction)

    # Set up clippings manager.
    settings.clippingsManager = settings_dialog.ClippingsPanel()
    settings.clippingsManager.setWindowFlags(Qt.Dialog)
    closeClippingsManagerAction = QAction(settings.clippingsManager)
    closeClippingsManagerAction.setShortcuts(["Esc", "Ctrl+W"])
    closeClippingsManagerAction.triggered.connect(settings.clippingsManager.hide)
    settings.clippingsManager.addAction(closeClippingsManagerAction)

    # Create DBus server
    if has_dbus:
        print("Creating DBus server...", end=" ")
        server = DBusServer(bus)
        print("done.")

    # Load adblock rules.
    filtering.adblock_filter_loader.start()

    if not os.path.isdir(settings.extensions_folder):
        try:
            print("Copying extensions...", end=" ")
            shutil.copytree(common.extensions_folder,\
                             settings.extensions_folder)
        except:
            print("failed.")
        else:
            print("done.")
    if not os.path.isfile(settings.startpage):
        try:
            print("Copying start page...", end=" ")
            shutil.copy2(common.startpage, settings.startpage)
        except:
            print("failed.")
        else:
            print("done.")

    settings.reload_extensions()
    settings.reload_userscripts()

    server_thread.setDirectory(settings.extensions_folder)

    # Start extension server.
    server_thread.start()

    # On quit, save settings.
    app.aboutToQuit.connect(prepareQuit)

    # Load settings.
    data.loadData()

    # View source dialog.
    common.viewSourceDialog = ViewSourceDialogTabber()
    #common.viewSourceDialog.show()
    
    # This is a baaad name.
    common.sessionSaver = QTimer(QCoreApplication.instance())
    common.sessionSaver.timeout.connect(saveSession)
    common.sessionSaver.timeout.connect(data.saveData)
    if common.portable:
        common.sessionSaver.start(50000)
    else:
        common.sessionSaver.start(30000)

    common.desktop = QDesktopWidget()

    changeSettings = False
    if os.path.isfile(settings.crash_file):
        print("Crash file detected.", end="")
        if not has_dbus:
            print(" With no DBus, %s may already be running." % common.app_name,)
            multInstances = QMessageBox.question(None, tr("Hm."), tr("It's not good to run multiple instances of %(app_name)s. Is an instance of %(app_name)s already running?") % {"app_name": common.app_name}, QMessageBox.Yes | QMessageBox.No)
            if multInstances == QMessageBox.Yes:
                print("%s will now halt." % common.app_name,)
                return
        else:
            print()
        clearCache = QMessageBox()
        clearCache.setWindowTitle(tr("Ow."))
        clearCache.setText(tr("%(app_name)s seems to have crashed during your last session. Fortunately, your tabs were saved up to 30 seconds beforehand. Would you like to restore them?") % {"app_name": common.app_name})
        clearCache.addButton(QPushButton(tr("Yes and change &settings")), QMessageBox.YesRole)
        clearCache.addButton(QMessageBox.Yes)
        clearCache.addButton(QMessageBox.No)
        returnValue = clearCache.exec_()
        if returnValue == QMessageBox.No:
            try: os.remove(settings.session_file)
            except: pass
        if returnValue == 0:
            changeSettings = True
    else:
        f = open(settings.crash_file, "w")
        f.write("")
        f.close()

    if not "--daemon" in argv and os.path.exists(settings.session_file):
        print("Loading previous session...", end=" ")
        if changeSettings:
            settings.settingsDialog.exec_()
        loadSession()
        print("done.")
    if not "--daemon" in argv and len(argv[1:]) > 0:
        # Create instance of MainWindow.
        print("Loading the URLs you requested...", end=" ")
        if len(browser.windows) > 0:
            win = browser.windows[-1]
        else:
            win = MainWindow(appMode = ("--app" in argv))

        # Open URLs from command line.
        if len(argv[1:]) > 0:
            for arg in argv[1:]:
                if "." in arg or ":" in arg:
                    win.addTab(url=arg)

        if win.tabWidget().count() < 1:
            win.addTab(url=settings.settings.value("general/Homepage"))

            # Show window.
        win.show()
        print("done.")
    elif not "--daemon" in argv and len(argv[1:]) == 0 and len(browser.windows) == 0:
        win = MainWindow(appMode = ("--app" in argv))
        win.addTab(url=settings.settings.value("general/Homepage"))
        win.show()

    # Load filtering stuff.
    if not os.path.isdir(filtering.hosts_folder):
        common.trayIcon.showMessage(tr("Downloading content filters"), ("Ad blocking and host filtering will not work until this completes."))
        filtering.update_filters()
    else:
        filtering.load_host_rules()

    # Start app.
    print("Kon~!")
    sys.exit(app.exec_())
Example #38
0
    def chuanLogo(self):
        chuanqi_image = base64.b64decode(chuanqi.image)
        pixmap = QPixmap()
        pixmap.loadFromData(chuanqi_image)
        return pixmap

    def change_func(self):
        self.ChangeBtn()
        self.time.start()  # 计时开始

    def referch(self):
        self.time.stop()  # 计时结束
        self.IpChangeBtn.setText('一键修改')


# 汉化
def translator():
    SetTranslator = QTranslator()
    SetTranslator.load('./lib/qt_zh_CN.qm')
    return SetTranslator


if __name__ == '__main__':
    app = QApplication(sys.argv)
    translatorLoad = translator()
    app.installTranslator(translatorLoad)
    view = ShowFunc()
    view.show()
    sys.exit(app.exec_())
Example #39
0
def main():
    # Parse the command-line arguments
    parser = argparse.ArgumentParser(description='Linux Show Player')
    parser.add_argument('-f',
                        '--file',
                        default='',
                        nargs='?',
                        const='',
                        help='Session file path')
    parser.add_argument('-l',
                        '--log',
                        choices=['debug', 'info', 'warning'],
                        default='warning',
                        help='Log level')
    parser.add_argument('--locale', default='', help='Force specified locale')

    args = parser.parse_args()

    # Set the logging level
    if args.log == 'debug':
        log = logging.DEBUG

        # If something bad happen at low-level (e.g. segfault) print the stack
        import faulthandler
        faulthandler.enable()
    elif args.log == 'info':
        log = logging.INFO
    else:
        log = logging.WARNING

    logging.basicConfig(
        format='%(asctime)s.%(msecs)03d %(levelname)s:: %(message)s',
        datefmt='%H:%M:%S',
        level=log)

    # Detect qt5ct (icons do not appear when qt5ct is installed)
    if 'QT_QPA_PLATFORMTHEME' in environ and environ[
            'QT_QPA_PLATFORMTHEME'] == 'qt5ct':
        logging.warning(
            'qt5ct detected. Linux Show Player and qt5ct are not compatible. Overriding.'
        )
        del environ['QT_QPA_PLATFORMTHEME']

    # Create the QApplication
    qt_app = QApplication(sys.argv)
    qt_app.setApplicationName('Linux Show Player')
    qt_app.setQuitOnLastWindowClosed(True)

    # Force light font, for environment with "bad" QT support.
    appFont = qt_app.font()
    appFont.setWeight(QFont.Light)
    qt_app.setFont(appFont)
    # Set icons and theme from the application configuration
    QIcon.setThemeSearchPaths(styles.IconsThemePaths)
    QIcon.setThemeName(config['Theme']['icons'])
    styles.apply_style(config['Theme']['theme'])

    # Set application icon (from the theme)
    qt_app.setWindowIcon(QIcon.fromTheme('linux-show-player'))

    # Get/Set the locale
    locale = args.locale
    if locale:
        QLocale().setDefault(QLocale(locale))

    logging.info('Using {} locale'.format(QLocale().name()))

    # Main app translations
    translator = QTranslator()
    translator.load(QLocale(), 'lisp', '_',
                    path.join(path.dirname(path.realpath(__file__)), 'i18n'))

    qt_app.installTranslator(translator)
    ui_translators = [translator]

    # Qt platform translation
    translator = QTranslator()
    translator.load(QLocale(), 'qt', '_',
                    QLibraryInfo.location(QLibraryInfo.TranslationsPath))

    qt_app.installTranslator(translator)
    ui_translators.append(translator)

    # Modules and plugins translations
    for tr_file in chain(modules.translations(), plugins.translations()):
        translator = QTranslator()
        translator.load(QLocale(), tr_file, '_')

        qt_app.installTranslator(translator)
        ui_translators.append(translator)

    # Create the application
    lisp_app = Application()
    # Load modules and plugins
    modules.load_modules()
    plugins.load_plugins()

    # Start/Initialize LiSP Application
    lisp_app.start(session_file=args.file)
    # Start Qt Application (block until exit)
    exit_code = qt_app.exec_()

    # Finalize the application
    lisp_app.finalize()
    # Exit
    sys.exit(exit_code)
Example #40
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')

    try:
        # See https://github.com/retext-project/retext/issues/399
        # and https://launchpad.net/bugs/941826
        ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL)
    except OSError:
        pass

    # Needed for Qt WebEngine on Windows
    QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
    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)
    initializeDataDirs()
    RtTranslator = QTranslator()
    for path in datadirs:
        if RtTranslator.load('retext_' + globalSettings.uiLanguage,
                             join(path, 'locale')):
            break
    QtTranslator = QTranslator()
    QtTranslator.load("qtbase_" + 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
    readStdIn = False
    if globalSettings.openLastFilesOnStartup:
        window.restoreLastOpenedFiles()
    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
        elif fileName == '-':
            readStdIn = True

    inputData = ''
    if readStdIn and sys.stdin is not None:
        if sys.stdin.isatty():
            print('Reading stdin, press ^D to end...')
        inputData = 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())
Example #41
0
def main():
    try:
        locale.setlocale(locale.LC_ALL, '')
    except:
        # Work around system locale not specified (under Linux or Mac OS)
        pass

    app = QApplication(sys.argv)

    QCoreApplication.setOrganizationName(version.Company)
    QCoreApplication.setApplicationName(version.AppName)

    settings = Settings()
    if settings['error']:
        sys.excepthook = exceptHook

    if not os.path.exists(settings['reference']):
        # Create default dirs and files if not exists
        try:
            ref_path = os.path.dirname(settings['reference'])
            dst_ref = os.path.join(ref_path, 'reference.ref')
            if not os.path.exists(dst_ref):
                os.makedirs(ref_path, exist_ok=True)
                src_ref = os.path.join(OpenNumismat.PRJ_PATH, 'db',
                                   'reference_%s.ref' % settings['locale'])
                if not os.path.exists(src_ref):
                    src_ref = os.path.join(OpenNumismat.PRJ_PATH, 'db',
                                       'reference_en.ref')

                shutil.copy(src_ref, dst_ref)

            dst_demo_db = os.path.join(OpenNumismat.HOME_PATH, 'demo.db')
            if not os.path.exists(dst_demo_db):
                os.makedirs(OpenNumismat.HOME_PATH, exist_ok=True)
                src_demo_db = os.path.join(OpenNumismat.PRJ_PATH, 'db',
                                           'demo_%s.db' % settings['locale'])
                if not os.path.exists(src_demo_db):
                    src_demo_db = os.path.join(OpenNumismat.PRJ_PATH, 'db',
                                       'demo_en.ref')

                shutil.copy(src_demo_db, dst_demo_db)

            templates_path = os.path.join(OpenNumismat.HOME_PATH, 'templates')
            os.makedirs(templates_path, exist_ok=True)
        except:
            pass

    TemporaryDir.init(version.AppName)

    lang = settings['locale']

    translator = QTranslator()
    translator.load('lang_' + lang, OpenNumismat.PRJ_PATH)
    app.installTranslator(translator)

    translatorQt = QTranslator()
    translatorQt.load('qtbase_' + lang, OpenNumismat.PRJ_PATH)
    app.installTranslator(translatorQt)

    if not settings['verify_ssl']:
        ssl._create_default_https_context = ssl._create_unverified_context

    mainWindow = MainWindow()
    mainWindow.show()
    mainWindow.raise_()  # this will raise the window on Mac OS X
    status = app.exec_()

    # Clear temporary files
    TemporaryDir.remove()

    sys.exit(status)
Example #42
0
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtCore import QTranslator
from PyQt5.QtWidgets import QApplication
from Function import function


class show_func(function):
    def __init__(self):
        function.__init__(self)
        self.setWindowTitle("NC-UpLoader")
        self.connectBtn.clicked.connect(self.btnFunc)


def translate():
    translateLoad = QTranslator()
    translateLoad.load('./res/qt_zh_CN.qm')
    return translateLoad


if __name__ == '__main__':
    app = QApplication([])
    translateInstall = translate()
    app.installTranslator(translateInstall)
    win = show_func()
    win.show()
    sys.exit(app.exec_())
Example #43
0
        self.syncGo.setEnabled(True)
        self.listIsos.setEnabled(True)
        self.selectAll.setEnabled(True)


    def main(self):
        self.show()
        #   Load or look for intitial parameters
        self.prefsInit()
        # look for Isos list and add it to the isoSync list. Update preferences
        self.updateList()
        self.multiSelect()

    def close(self):
        self.rsyncThread.stop()
        exit(0)

if __name__=='__main__':
    app = QApplication(sys.argv)
    locale = QtCore.QLocale.system().name()
    qtTranslator = QtCore.QTranslator()
    if qtTranslator.load("qt_" + locale,QLibraryInfo.location(QLibraryInfo.TranslationsPath)):
        app.installTranslator(qtTranslator)
    appTranslator = QtCore.QTranslator()
    if appTranslator.load("mageiaSync_" + locale,QLibraryInfo.location(QLibraryInfo.TranslationsPath)):
        app.installTranslator(appTranslator)
    isosSync = IsosViewer()
    isosSync.main()
    sys.exit(app.exec_())

def main_script():
    if len(sys.argv) < 3:
        sys.stderr.write('Not enought arguments.\n')
        sys.exit(1)

    extension = sys.argv[1]
    if not extension.lower() in Mo.EXTENSIONS:
        sys.stderr.write('extension can only be %s.\n' %
                         ' '.join(Mo.EXTENSIONS))
        sys.exit(1)

    arg_files = []
    for arg in sys.argv[2:]:
        arg_files.append(os.path.realpath(arg))

    main_obj = Mo.MainObject(extension, arg_files)

    # start to list files before displaying the first dialog
    walk_thread = threading.Thread(target=main_obj.walk)
    walk_thread.start()

    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon.fromTheme(Mo.EXTENSIONS[extension]))

    settings = QSettings()

    ### Translation process
    code_root = os.path.dirname(os.path.dirname(sys.argv[0]))

    appTranslator = QTranslator()
    if appTranslator.load(QLocale(), 'converter', '_', code_root + '/locale'):
        app.installTranslator(appTranslator)

    sysTranslator = QTranslator()
    pathSysTranslations = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
    if sysTranslator.load(QLocale(), 'qt', '_', pathSysTranslations):
        app.installTranslator(sysTranslator)

    _translate = QApplication.translate

    dialog = first_dialog.FirstDialog(main_obj, settings)
    label = _translate('terminal', "Conversion to %s") % extension.upper()
    label += '\n'
    label += _translate(
        'terminal', "Please select options in the dialog window and press Ok")
    label += '\n'
    sys.stderr.write(label)

    dialog.exec()
    if not dialog.result():
        sys.exit(0)

    dialog.remember_settings(settings)

    progress_dlg = progress_dialog.ProgressDialog(main_obj, settings)
    main_obj.progress_dialog = progress_dlg
    main_obj.read_parameters(dialog.get_parameters())
    main_obj.start_next_process()
    progress_dlg.exec()

    close_terminal = progress_dlg.close_terminal_at_end()
    settings.setValue('close_terminal', close_terminal)

    walk_thread.join()
    app.quit()

    notif = notifier.Notifier(main_obj)
    notif.notify()

    if main_obj.files_error_indexes:
        sys.stderr.write(_translate('terminal', "Some errors appears, "))
    if main_obj.files_error_indexes or not close_terminal:
        sys.stderr.write(
            _translate('terminal', "Press Enter to close this terminal:"))
        input()
Example #45
0
class DistUpgradeViewKDE(DistUpgradeView):
    """KDE frontend of the distUpgrade tool"""
    def __init__(self, datadir=None, logdir=None):
        DistUpgradeView.__init__(self)

        get_telemetry().set_updater_type('KDE')
        # silence the PyQt4 logger
        logger = logging.getLogger("PyQt4")
        logger.setLevel(logging.INFO)
        if not datadir or datadir == '.':
            localedir = os.path.join(os.getcwd(), "mo")
        else:
            localedir = "/usr/share/locale/ubuntu-release-upgrader"

        # FIXME: i18n must be somewhere relative do this dir
        try:
            gettext.bindtextdomain("ubuntu-release-upgrader", localedir)
            gettext.textdomain("ubuntu-release-upgrader")
        except Exception as e:
            logging.warning("Error setting locales (%s)" % e)

        # we test for DISPLAY here, QApplication does not throw a
        # exception when run without DISPLAY but dies instead
        if not "DISPLAY" in os.environ:
            raise Exception("No DISPLAY in os.environ found")

        # Force environment to make sure Qt uses suitable theming and UX.
        os.environ["QT_PLATFORM_PLUGIN"] = "kde"
        # For above settings to apply automatically we need to indicate that we
        # are inside a full KDE session.
        os.environ["KDE_FULL_SESSION"] = "TRUE"
        # We also need to indicate version as otherwise KDElibs3 compatibility
        # might kick in such as in QIconLoader.cpp:QString fallbackTheme.
        os.environ["KDE_SESSION_VERSION"] = "5"
        # Pretty much all of the above but for Qt5
        os.environ["QT_QPA_PLATFORMTHEME"] = "kde"

        self.app = QApplication(["ubuntu-release-upgrader"])

        # Try to load default Qt translations so we don't have to worry about
        # QStandardButton translations.
        translator = QTranslator(self.app)
        if type(PYQT_VERSION) == int:
            translator.load(QLocale.system(), 'qt', '_',
                            '/usr/share/qt5/translations')
        else:
            translator.load(QLocale.system(), 'qt', '_',
                            '/usr/share/qt4/translations')
        self.app.installTranslator(translator)

        QUrlOpener().setupUrlHandles()

        messageIcon = _icon(
            "system-software-update",
            fallbacks=[
                "/usr/share/icons/oxygen/48x48/apps/system-software-update.png",
                "/usr/share/icons/hicolor/48x48/apps/adept_manager.png"
            ])
        self.app.setWindowIcon(messageIcon)

        self.window_main = UpgraderMainWindow()
        self.window_main.setParent(self)
        self.window_main.show()

        self.prev_step = None  # keep a record of the latest step

        self._opCacheProgress = KDEOpProgress(
            self.window_main.progressbar_cache, self.window_main.progress_text)
        self._acquireProgress = KDEAcquireProgressAdapter(self)
        self._cdromProgress = KDECdromProgressAdapter(self)

        self._installProgress = KDEInstallProgressAdapter(self)

        # reasonable fault handler
        sys.excepthook = self._handleException

        self.window_main.showTerminalButton.setEnabled(False)
        self.window_main.showTerminalButton.clicked.connect(self.showTerminal)

        # init gettext
        gettext.bindtextdomain("ubuntu-release-upgrader", localedir)
        gettext.textdomain("ubuntu-release-upgrader")
        self.translate_widget_children()
        name = _OSRelease().result["PRETTY_NAME"]
        if not name or name == "Ubuntu":
            name = "Kubuntu"
        self.window_main.label_title.setText(
            self.window_main.label_title.text().replace("Ubuntu", name))

        # setup terminal text in hidden by default spot
        self.window_main.konsole_frame.hide()
        self.konsole_frame_layout = QHBoxLayout(self.window_main.konsole_frame)
        self.window_main.konsole_frame.setMinimumSize(600, 400)
        self.terminal_text = DumbTerminal(self._installProgress,
                                          self.window_main.konsole_frame)
        self.konsole_frame_layout.addWidget(self.terminal_text)
        self.terminal_text.show()

        self.inhibitScreenlock()
        atexit.register(self.uninhibitScreenlock)

        # for some reason we need to start the main loop to get everything displayed
        # this app mostly works with processEvents but run main loop briefly to keep it happily displaying all widgets
        QTimer.singleShot(10, self.exitMainLoopMidFlight)
        self.app.exec_()

    def exitMainLoopMidFlight(self):
        # This is run shortly after startup. Do not add actual exit logic here!
        print("exitMainLoopMidFlight")
        self.app.exit()

    def inhibitScreenlock(self):
        if not QDBusConnection.sessionBus().isConnected():
            sys.stderr.write("Cannot connect to the D-Bus session bus.\n"
                             "To start it, run:\n"
                             "\teval `dbus-launch --auto-syntax`\n")
            return

        iface = QDBusInterface('org.kde.screensaver', '/ScreenSaver', '',
                               QDBusConnection.sessionBus())

        if iface.isValid():
            msg = iface.call('Inhibit', 'DisUpgradeViewKDE',
                             'Upgrading base OS')
            reply = QDBusReply(msg)
            self.screenLockCookie = reply.value()

    def uninhibitScreenlock(self):
        if not QDBusConnection.sessionBus().isConnected():
            sys.stderr.write("Cannot connect to the D-Bus session bus.\n"
                             "To start it, run:\n"
                             "\teval `dbus-launch --auto-syntax`\n")
            return

        iface = QDBusInterface('org.kde.screensaver', '/ScreenSaver', '',
                               QDBusConnection.sessionBus())

        if iface.isValid():
            iface.call('UnInhibit', self.screenLockCookie)

    def translate_widget_children(self, parentWidget=None):
        if parentWidget == None:
            parentWidget = self.window_main
        if isinstance(parentWidget, QDialog) or isinstance(
                parentWidget, QWidget):
            if str(parentWidget.windowTitle()) == "Error":
                parentWidget.setWindowTitle(
                    gettext.dgettext("kdelibs", "Error"))
            else:
                parentWidget.setWindowTitle(_(str(parentWidget.windowTitle())))

        if parentWidget.children() != None:
            for widget in parentWidget.children():
                self.translate_widget(widget)
                self.translate_widget_children(widget)

    def translate_widget(self, widget):
        if isinstance(widget, QLabel) or isinstance(widget, QPushButton):
            if str(widget.text()) == "&Cancel":
                kdelibs = gettext.translation("kdelibs",
                                              gettext.textdomain("kdelibs"),
                                              fallback=True)
                widget.setText(unicode_gettext(kdelibs, "&Cancel"))
            elif str(widget.text()) == "&Close":
                kdelibs = gettext.translation("kdelibs",
                                              gettext.textdomain("kdelibs"),
                                              fallback=True)
                widget.setText(unicode_gettext(kdelibs, "&Close"))
            elif str(widget.text()) != "":
                widget.setText(_(str(widget.text())).replace("_", "&"))

    def _handleException(self, exctype, excvalue, exctb):
        """Crash handler."""

        if (issubclass(exctype, KeyboardInterrupt)
                or issubclass(exctype, SystemExit)):
            return

        # we handle the exception here, hand it to apport and run the
        # apport gui manually after it because we kill u-m during the upgrade
        # to prevent it from popping up for reboot notifications or FF restart
        # notifications or somesuch
        lines = traceback.format_exception(exctype, excvalue, exctb)
        logging.error("not handled exception in KDE frontend:\n%s" %
                      "\n".join(lines))
        # we can't be sure that apport will run in the middle of a upgrade
        # so we still show a error message here
        apport_crash(exctype, excvalue, exctb)
        if not run_apport():
            tbtext = ''.join(
                traceback.format_exception(exctype, excvalue, exctb))
            dialog = QDialog(self.window_main)
            loadUi("dialog_error.ui", dialog)
            self.translate_widget_children(self.dialog)
            dialog.crash_detail.setText(tbtext)
            # Make sure we have a suitable size depending on whether or not the view is shown
            dialog.adjustSize()
            dialog.exec_()
        sys.exit(1)

    def showTerminal(self):
        if self.window_main.konsole_frame.isVisible():
            self.window_main.konsole_frame.hide()
            self.window_main.showTerminalButton.setText(_("Show Terminal >>>"))
        else:
            self.window_main.konsole_frame.show()
            self.window_main.showTerminalButton.setText(_("<<< Hide Terminal"))
        self.window_main.adjustSize()

    def getAcquireProgress(self):
        return self._acquireProgress

    def getInstallProgress(self, cache):
        self._installProgress._cache = cache
        return self._installProgress

    def getOpCacheProgress(self):
        return self._opCacheProgress

    def getCdromProgress(self):
        return self._cdromProgress

    def update_status(self, msg):
        self.window_main.label_status.setText(msg)

    def hideStep(self, step):
        image = getattr(self.window_main, "image_step%i" % step.value)
        label = getattr(self.window_main, "label_step%i" % step.value)
        image.hide()
        label.hide()

    def abort(self):
        step = self.prev_step
        if step:
            image = getattr(self.window_main, "image_step%i" % step.value)
            cancelIcon = _icon(
                "dialog-cancel",
                fallbacks=[
                    "/usr/share/icons/oxygen/16x16/actions/dialog-cancel.png",
                    "/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-cancel.png",
                    "/usr/share/icons/crystalsvg/16x16/actions/cancel.png"
                ])
            image.setPixmap(cancelIcon.pixmap(16, 16))
            image.show()

    def setStep(self, step):
        super(DistUpgradeViewKDE, self).setStep(step)
        okIcon = _icon(
            "dialog-ok",
            fallbacks=[
                "/usr/share/icons/oxygen/16x16/actions/dialog-ok.png",
                "/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-ok.png",
                "/usr/share/icons/crystalsvg/16x16/actions/ok.png"
            ])
        arrowIcon = _icon(
            "arrow-right",
            fallbacks=[
                "/usr/share/icons/oxygen/16x16/actions/arrow-right.png",
                "/usr/lib/kde4/share/icons/oxygen/16x16/actions/arrow-right.png",
                "/usr/share/icons/crystalsvg/16x16/actions/1rightarrow.png"
            ])

        if self.prev_step:
            image = getattr(self.window_main,
                            "image_step%i" % self.prev_step.value)
            label = getattr(self.window_main,
                            "label_step%i" % self.prev_step.value)
            image.setPixmap(okIcon.pixmap(16, 16))
            image.show()
            ##arrow.hide()
        self.prev_step = step
        # show the an arrow for the current step and make the label bold
        image = getattr(self.window_main, "image_step%i" % step.value)
        label = getattr(self.window_main, "label_step%i" % step.value)
        image.setPixmap(arrowIcon.pixmap(16, 16))
        image.show()
        label.setText("<b>" + label.text() + "</b>")

    def information(self, summary, msg, extended_msg=None):
        msg = "<big><b>%s</b></big><br />%s" % (summary, msg)

        dialogue = QDialog(self.window_main)
        loadUi("dialog_error.ui", dialogue)
        self.translate_widget_children(dialogue)
        dialogue.label_error.setText(msg)
        if extended_msg != None:
            dialogue.textview_error.setText(extended_msg)
            dialogue.textview_error.show()
        else:
            dialogue.textview_error.hide()
        dialogue.setWindowTitle(_("Information"))

        messageIcon = _icon(
            "dialog-information",
            fallbacks=[
                "/usr/share/icons/oxygen/48x48/status/dialog-information.png",
                "/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-information.png",
                "/usr/share/icons/crystalsvg/32x32/actions/messagebox_info.png"
            ])
        dialogue.image.setPixmap(messageIcon.pixmap(48, 48))
        # Make sure we have a suitable size depending on whether or not the view is shown
        dialogue.adjustSize()
        dialogue.exec_()

    def error(self, summary, msg, extended_msg=None):
        msg = "<big><b>%s</b></big><br />%s" % (summary, msg)

        dialogue = QDialog(self.window_main)
        loadUi("dialog_error.ui", dialogue)
        self.translate_widget_children(dialogue)
        dialogue.label_error.setText(msg)
        if extended_msg != None:
            dialogue.textview_error.setText(extended_msg)
            dialogue.textview_error.show()
        else:
            dialogue.textview_error.hide()

        messageIcon = _icon(
            "dialog-error",
            fallbacks=[
                "/usr/share/icons/oxygen/48x48/status/dialog-error.png",
                "/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-error.png",
                "/usr/share/icons/crystalsvg/32x32/actions/messagebox_critical.png"
            ])
        dialogue.image.setPixmap(messageIcon.pixmap(48, 48))
        # Make sure we have a suitable size depending on whether or not the view is shown
        dialogue.adjustSize()
        dialogue.exec_()

        return False

    def confirmChanges(self,
                       summary,
                       changes,
                       demotions,
                       downloadSize,
                       actions=None,
                       removal_bold=True):
        """show the changes dialogue"""
        # FIXME: add a whitelist here for packages that we expect to be
        # removed (how to calc this automatically?)
        DistUpgradeView.confirmChanges(self, summary, changes, demotions,
                                       downloadSize)
        self.changesDialogue = QDialog(self.window_main)
        loadUi("dialog_changes.ui", self.changesDialogue)

        self.changesDialogue.treeview_details.hide()
        self.changesDialogue.buttonBox.helpRequested.connect(
            self.showChangesDialogueDetails)
        self.translate_widget_children(self.changesDialogue)
        self.changesDialogue.buttonBox.button(QDialogButtonBox.Ok).setText(
            _("&Start Upgrade"))
        self.changesDialogue.buttonBox.button(QDialogButtonBox.Help).setIcon(
            QIcon())
        self.changesDialogue.buttonBox.button(
            QDialogButtonBox.Help).setText(_("Details") + " >>>")

        messageIcon = _icon(
            "dialog-warning",
            fallbacks=[
                "/usr/share/icons/oxygen/48x48/status/dialog-warning.png",
                "/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-warning.png",
                "/usr/share/icons/crystalsvg/32x32/actions/messagebox_warning.png"
            ])
        self.changesDialogue.question_pixmap.setPixmap(
            messageIcon.pixmap(48, 48))

        if actions != None:
            cancel = actions[0].replace("_", "")
            self.changesDialogue.buttonBox.button(
                QDialogButtonBox.Cancel).setText(cancel)
            confirm = actions[1].replace("_", "")
            self.changesDialogue.buttonBox.button(
                QDialogButtonBox.Ok).setText(confirm)

        summaryText = "<big><b>%s</b></big>" % summary
        self.changesDialogue.label_summary.setText(summaryText)
        self.changesDialogue.label_changes.setText(self.confirmChangesMessage)
        # fill in the details
        self.changesDialogue.treeview_details.clear()
        self.changesDialogue.treeview_details.setHeaderLabels(["Packages"])
        self.changesDialogue.treeview_details.header().hide()
        for demoted in self.demotions:
            self.changesDialogue.treeview_details.insertTopLevelItem(
                0,
                QTreeWidgetItem(self.changesDialogue.treeview_details,
                                [_("No longer supported %s") % demoted.name]))
        for rm in self.toRemove:
            self.changesDialogue.treeview_details.insertTopLevelItem(
                0,
                QTreeWidgetItem(self.changesDialogue.treeview_details,
                                [_("Remove %s") % rm.name]))
        for rm in self.toRemoveAuto:
            self.changesDialogue.treeview_details.insertTopLevelItem(
                0,
                QTreeWidgetItem(
                    self.changesDialogue.treeview_details,
                    [_("Remove (was auto installed) %s") % rm.name]))
        for inst in self.toInstall:
            self.changesDialogue.treeview_details.insertTopLevelItem(
                0,
                QTreeWidgetItem(self.changesDialogue.treeview_details,
                                [_("Install %s") % inst.name]))
        for up in self.toUpgrade:
            self.changesDialogue.treeview_details.insertTopLevelItem(
                0,
                QTreeWidgetItem(self.changesDialogue.treeview_details,
                                [_("Upgrade %s") % up.name]))

        # Use a suitable size for the window given the current content.
        self.changesDialogue.adjustSize()

        #FIXME resize label, stop it being shrinkable
        res = self.changesDialogue.exec_()
        if res == QDialog.Accepted:
            return True
        return False

    def showChangesDialogueDetails(self):
        if self.changesDialogue.treeview_details.isVisible():
            self.changesDialogue.treeview_details.hide()
            self.changesDialogue.buttonBox.button(
                QDialogButtonBox.Help).setText(_("Details") + " >>>")
        else:
            self.changesDialogue.treeview_details.show()
            self.changesDialogue.buttonBox.button(
                QDialogButtonBox.Help).setText("<<< " + _("Details"))
        self.changesDialogue.adjustSize()

    def askYesNoQuestion(self, summary, msg, default='No'):
        answer = QMessageBox.question(self.window_main, summary,
                                      "<font>" + msg,
                                      QMessageBox.Yes | QMessageBox.No,
                                      QMessageBox.No)
        if answer == QMessageBox.Yes:
            return True
        return False

    def confirmRestart(self):
        messageBox = QMessageBox(
            QMessageBox.Question, _("Restart required"),
            _("<b><big>Restart the system to complete the upgrade</big></b>"),
            QMessageBox.NoButton, self.window_main)
        yesButton = messageBox.addButton(QMessageBox.Yes)
        noButton = messageBox.addButton(QMessageBox.No)
        yesButton.setText(_("_Restart Now").replace("_", "&"))
        noButton.setText(gettext.dgettext("kdelibs", "&Close"))
        answer = messageBox.exec_()
        if answer == QMessageBox.Yes:
            return True
        return False

    def processEvents(self):
        QApplication.processEvents()

    def pulseProgress(self, finished=False):
        # FIXME: currently we do nothing here because this is
        # run in a different python thread and QT explodes if the UI is
        # touched from a non QThread
        pass

    def on_window_main_delete_event(self):
        #FIXME make this user friendly
        text = _("""<b><big>Cancel the running upgrade?</big></b>

The system could be in an unusable state if you cancel the upgrade. You are strongly advised to resume the upgrade."""
                 )
        text = text.replace("\n", "<br />")
        cancel = QMessageBox.warning(self.window_main, _("Cancel Upgrade?"),
                                     text, QMessageBox.Yes, QMessageBox.No)
        if cancel == QMessageBox.Yes:
            return True
        return False
Example #46
0
 def setLanguage(self, language):
     if not self.translator.isEmpty():
         QApplication.removeTranslator(self.translator)
     self.translator.load(f':/l10n/about_{language.value}.qm')
     QApplication.installTranslator(self.translator)
     self.retranslateUi(self)
Example #47
0
def main():
    filename = None
    debug = 0
    kodos_dir = os.path.join(sys.prefix, "kodos")
    locale = None

    args = sys.argv[1:]
    try:
        (opts, getopts) = getopt.getopt(args, 'd:f:k:l:?h',
                                        ["file=", "debug=", "help", "locale="])
    except:
        print("\nInvalid command line option detected.")
        usage()

    for opt, arg in opts:
        if opt in ('-h', '-?', '--help'):
            usage()
        if opt == '-k':
            kodos_dir = arg
        if opt in ('-d', '--debug'):
            try:
                debug = int(arg)
            except:
                print("debug value must be an integer")
                usage()
        if opt in ('-f', '--file'):
            filename = arg
        if opt in ('-l', '--locale'):
            locale = arg

    os.environ['KODOS_DIR'] = kodos_dir

    qApp = QApplication(sys.argv)
    qApp.setOrganizationName("kodos")
    qApp.setApplicationName("kodos")
    qApp.setOrganizationDomain("kodos.sourceforge.net")

    if locale not in (None, 'en'):
        localefile = "kodos_%s.qm" % (locale or QTextCodec.locale())
        localepath = findFile(os.path.join("translations", localefile))
        if debug:
            print(("locale changed to:", locale))
            print(localefile)
            print(localepath)

        translator = QTranslator(qApp)
        translator.load(localepath)

        qApp.installTranslator(translator)

    kodos = Kodos(filename, debug)

    #Find the current window where the mouse is just in case we are in a multi
    #monitor setup. And then move to its center.
    frameGm = kodos.frameGeometry()
    screen = QApplication.desktop().screenNumber(
        QApplication.desktop().cursor().pos())
    centerPoint = QApplication.desktop().availableGeometry(screen).center()
    frameGm.moveCenter(centerPoint)
    kodos.move(frameGm.topLeft())

    kodos.show()

    sys.exit(qApp.exec_())
Example #48
0
if __name__ == '__main__':
    # 添加oracle client驱动环境变量(添加到首位,避免与已存在client冲突)
    os.environ['PATH'] = os.path.join(
        os.path.dirname(os.path.realpath(sys.argv[0])),
        'instantclient_19_3\\') + ';'
    if os.getenv('TNS_ADMIN'):
        del os.environ['TNS_ADMIN']
    os.environ[
        'NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.AL32UTF8'  # client使用utf-8编码

    # 高DPI
    QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling,
                                        True)  # enable highdpi scaling
    QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps,
                                        True)  # use highdpi icons

    app = QApplication(sys.argv)

    # 加载QT 官方翻译
    translator = QtCore.QTranslator()
    translator.load("res/qt_zh_CN.qm")
    QApplication.installTranslator(translator)

    ui = mainUI.Ui_MainWindow()

    # 可以理解成将创建的 ui 绑定到新建的 mainWnd 上
    display = Display(ui)
    display.show()

    sys.exit(app.exec_())
Example #49
0
        cerrar.exec_()

        if cerrar.clickedButton() == botonSalir:
            event.accept()
        else:
            event.ignore()


# ===============================================================

if __name__ == "__main__":

    import sys

    aplicacion = QApplication(sys.argv)

    traductor = QTranslator(aplicacion)
    lugar = QLocale.system().name()
    path = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
    traductor.load("qtbase_%s" % lugar, path)
    aplicacion.installTranslator(traductor)

    fuente = QFont()
    fuente.setPointSize(10)
    aplicacion.setFont(fuente)

    ventana = Siacle()
    ventana.showMaximized()

    sys.exit(aplicacion.exec_())
Example #50
0
if __name__ == '__main__':
    import sys

    if getattr(sys, 'frozen', False):
        # we are running in a bundle
        frozen = 'ever so'
        bundle_dir = sys._MEIPASS
    else:
        # we are running in a normal Python environment
        bundle_dir = os.path.dirname(os.path.abspath(__file__))

    os.chdir(bundle_dir)

    app = QApplication(sys.argv)

    QFontDatabase.addApplicationFont("font/FiraSans-Regular.otf")
    QFontDatabase.addApplicationFont("font/FiraSans-Medium.otf")
    QFontDatabase.addApplicationFont("font/FiraSans-SemiBold.otf")

    translator = QTranslator()
    translator.load(QLocale.system(), "", "", "lang")
    app.installTranslator(translator)

    app.setWindowIcon(QIcon('icon.ico'))

    player = Player()
    player.show()

    sys.exit(app.exec_())
Example #51
0
        self._loading = True
        self.spin_voltage_min.setValue(min_voltage)
        self.spin_voltage_max.setValue(max_voltage)
        self.spin_voltage_min.setMaximum(max_voltage)
        self.spin_voltage_max.setMinimum(min_voltage)
        self._loading = False
        self.plot.set_voltage_range(lower_value=self.spin_voltage_min.value(),
                                    upper_value=self.spin_voltage_max.value())


if __name__ == '__main__':
    app = QApplication(sys.argv)

    qt_translator = QTranslator()
    qt_translator.load("qt_" + QLocale.system().bcp47Name(),
                       QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qt_translator)
    qtbase_translator = QTranslator()
    qtbase_translator.load(
        "qtbase_" + QLocale.system().bcp47Name(),
        QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qtbase_translator)
    my_translator = QTranslator()
    my_translator.load(QLocale.system().bcp47Name(),
                       backend.resource_path('translations'))
    app.installTranslator(my_translator)

    window = App()
    window.show()
    app.exec_()
Example #52
0
def main():
    app = QApplication(sys.argv)
    config = ConfigReader.get_instance()
    if config.getValue('loglevel', 'info') == 'debug':
        logging.getLogger().setLevel(logging.DEBUG)
    qt_translator = QTranslator()
    qt_translator.load("qt_" + QLocale.system().name(),
                       QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qt_translator)

    qtbase_translator = QTranslator()
    qt_translator.load("qtbase_" + QLocale.system().name(),
                       QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qtbase_translator)

    try:
        mokey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                               'SOFTWARE\\WOW6432Node\\INDAMED')
        is64_bits = sys.maxsize > 2**32
        if is64_bits:
            defaultClientLib = os.sep.join([
                winreg.QueryValueEx(mokey, 'DataPath')[0], '..', 'Firebird',
                'bin', 'fbclient.dll'
            ])
        else:
            defaultClientLib = os.sep.join(
                [winreg.QueryValueEx(mokey, 'LocalPath')[0], 'gds32.dll'])
    except OSError as e:
        displayErrorMessage(
            "Failed to open Medical Office registry key: {}".format(e))
        sys.exit()

    conffile2 = os.path.dirname(
        os.path.realpath(__file__)) + os.sep + "Patientenakte.cnf"

    try:
        rstservini = configparser.ConfigParser()
        rstservini.read(os.sep.join([os.environ["SYSTEMROOT"], 'rstserv.ini']))
        defaultHost = rstservini["SYSTEM"]["Computername"]
        defaultDb = os.sep.join(
            [rstservini["MED95"]["DataPath"], "MEDOFF.GDB"])
        defaultArcDb = os.sep.join(
            [rstservini["MED95"]["DataPath"], "MEDOFFARC.GDB"])
    except Exception as e:
        displayErrorMessage("Failed to open rstserv.ini: {}".format(e))
        sys.exit()

    defaultDbUser = "******"
    defaultDbPassword = "******"
    try:
        sokey = winreg.OpenKey(
            winreg.HKEY_LOCAL_MACHINE,
            'SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\App Paths\\soffice.exe'
        )
        defaultLibrePath = winreg.QueryValueEx(sokey, '')[0]
        LOGGER.debug(
            "LibreOffice soffice.exe found in '{}'".format(defaultLibrePath))
    except OSError as e:
        LOGGER.debug('Failed to open soffice.exe-Key: {}'.format(e))
        defaultLibrePath = None

    gimppath = None
    try:
        try:
            gimpkey = winreg.OpenKey(
                winreg.HKEY_LOCAL_MACHINE,
                'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\GIMP-2_is1',
                0, winreg.KEY_READ | winreg.KEY_WOW64_32KEY)
        except OSError as e:
            gimpkey = winreg.OpenKey(
                winreg.HKEY_LOCAL_MACHINE,
                'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\GIMP-2_is1',
                0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
        gimppath = winreg.QueryValueEx(gimpkey, 'DisplayIcon')[0]
        LOGGER.debug("GIMP executable found in '{}'".format(gimppath))
    except OSError as e:
        LOGGER.debug('Failed to open GIMP-Key: {}'.format(e))
        gimppath = None

    gspath = None
    try:
        try:
            gskey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                   'SOFTWARE\\Artifex\\GPL Ghostscript', 0,
                                   winreg.KEY_READ | winreg.KEY_WOW64_32KEY)
        except OSError as e:
            gskey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                   'SOFTWARE\\Artifex\\GPL Ghostscript', 0,
                                   winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
        try:
            gsverkey = winreg.OpenKey(gskey, winreg.EnumKey(gskey, 0))
            gsbasepath = os.path.join(
                winreg.QueryValueEx(gsverkey, '')[0], 'bin')
            gspath = os.path.join(gsbasepath, 'gswin64c.exe')
            if not os.path.exists(gspath):
                gspath = os.path.join(gsbasepath, 'gswin32c.exe')
                if not os.path.exists(gspath):
                    raise Exception(
                        "No suitable ghostscript executable found in {}".
                        format(gsbasepath))

            LOGGER.debug("Ghostscript version {} found in '{}'".format(
                winreg.EnumKey(gskey, 0), gspath))
        except Exception as e:
            LOGGER.debug(
                "No usable ghostscript installation found. Continuing without shrink option: {}"
                .format(e))
    except OSError as e:
        LOGGER.debug('Failed to open ghostscript key: {}'.format(e))

    for cfg in [conffile2]:
        try:
            LOGGER.debug("Attempting config %s" % (cfg))
            with open(cfg, 'r') as f:
                conf = json.load(f)
                if "dbuser" in conf:
                    defaultDbUser = conf["dbuser"]
                if "dbpassword" in conf:
                    defaultDbPassword = conf["dbpassword"]
                if "libreoffice" in conf:
                    defaultLibrePath = conf["libreoffice"]
                if "clientlib" in conf:
                    defaultClientLib = conf["clientlib"]
                if "gimppath" in conf:
                    gimppath = conf["gimppath"]
                if "ghostscript" in conf:
                    gspath = conf["ghostscript"]
            break
        except Exception as e:
            LOGGER.info("Failed to load config: %s." % (e))

    LOGGER.debug("Client lib is %s" % (defaultClientLib))
    LOGGER.debug("DB Path is %s on %s" % (defaultDb, defaultHost))
    try:
        LOGGER.debug("Connecting db '{}' at '{}', port 2013 as user {}".format(
            defaultDb, defaultHost, defaultDbUser))
        con = fdb.connect(host=defaultHost,
                          database=defaultDb,
                          port=2013,
                          user=defaultDbUser,
                          password=defaultDbPassword,
                          fb_library_name=defaultClientLib)
        LOGGER.debug("Connection established.")
    except Exception as e:
        displayErrorMessage(
            'Fehler beim Verbinden mit der Datenbank: {}. Pfad zur DLL-Datei: {}'
            .format(e, defaultClientLib))
        sys.exit()

    try:
        LOGGER.debug(
            "Connecting archive db '{}' at '{}', port 2013 as user {}".format(
                defaultArcDb, defaultHost, defaultDbUser))
        arccon = fdb.connect(host=defaultHost,
                             database=defaultArcDb,
                             port=2013,
                             user=defaultDbUser,
                             password=defaultDbPassword,
                             fb_library_name=defaultClientLib)
        LOGGER.debug("Connection established.")
    except Exception as e:
        displayErrorMessage(
            'Fehler beim Verbinden mit der Archivdatenbank: {}. Dieser Fehler kann bedenkenlos ignoriert werden, falls keine Archivdatenbank verfügbar ist (z.B. auf Mobilsystemen).'
            .format(e))
        arccon = None
    try:
        cur = con.cursor()
        stm = "SELECT FVARVALUE FROM MED95INI WHERE FCLIENTNAME=? AND FVARNAME='PatexportDatei'"
        cur.execute(stm, (os.environ["COMPUTERNAME"], ))
        res = cur.fetchone()
        if res is None:
            raise Exception(
                "Keine Konfiguration für den Namen '{}' hinterlegt!".format(
                    os.environ["COMPUTERNAME"]))

        gdtfile = res[0][:-1].decode('windows-1252')
        del cur
        if not os.path.isfile(gdtfile):
            raise Exception(
                "Ungültiger Pfad: '{}'. Bitte korrekten Pfad für Patientenexportdatei im Datenpflegesystem konfigurieren. \
                Es muss in Medical Office anschließend mindestens ein Patient aufgerufen werden, um die Datei zu initialisieren."
                .format(gdtfile))
    except Exception as e:
        displayErrorMessage(
            "Fehler beim Feststellen des Exportpfades: {}".format(e))
        sys.exit()

    with tempdir() as myTemp:
        av = ArchivViewer(con)
        tm = ArchivTableModel(con, arccon, myTemp, defaultLibrePath, av, app,
                              gimppath, gspath)
        av.documentView.doubleClicked.connect(
            lambda: tableDoubleClicked(av.documentView, tm))
        av.documentView.setModel(tm)
        av.actionStayOnTop.setChecked(config.getValue('stayontop', False))
        av.actionShowPDFAfterExport.setChecked(
            config.getValue('showPDFAfterExport', False))
        av.actionShowRemovedItems.setChecked(
            config.getValue("showRemovedItems", False))
        av.actionUseImg2pdf.setChecked(config.getValue('useImg2pdf', True))
        av.actionOptimizeExport.setEnabled(gspath is not None)
        if av.actionOptimizeExport.isEnabled():
            av.actionOptimizeExport.setChecked(
                config.getValue('shrinkPDF', True))
        av.actionUseGimpForTiff.setEnabled(gimppath is not None)
        av.actionFitToA4.setChecked(config.getValue('fitToA4', False))
        if av.actionUseGimpForTiff.isEnabled():
            av.actionUseGimpForTiff.setChecked(
                config.getValue('useGimpForTiff', False))
        if config.getValue('stayontop', False):
            av.setWindowFlags(av.windowFlags() | Qt.WindowStaysOnTopHint)
        av.exportPdf.clicked.connect(
            lambda: exportSelectionAsPdf(av.documentView, tm))
        event_handler = FileChangeHandler(gdtfile, tm)
        av.action_quit.triggered.connect(lambda: app.quit())
        av.action_about.triggered.connect(lambda: QMessageBox.about(
            av, "Über Archiv Viewer",
            """<p><b>Archiv Viewer {}</b> ist eine zur Verwendung mit Medical Office der Fa. Indamed entwickelte
             Software, die synchron zur Medical Office-Anwendung die gespeicherten Dokumente eines Patienten im Archiv
             anzeigen kann. Zusätzlich können ausgewählte Dokumente auch als PDF-Datei exportiert werden.</p>
             <p><a href=\"https://github.com/crispinus2/archivviewer\">https://github.com/crispinus2/archivviewer</a></p>
             <p>(c) 2020 Julian Hartig - Lizensiert unter den Bedingungen der GPLv3</p>"""
            .format(AVVERSION)))

        observer = Observer()
        observer.schedule(event_handler,
                          path=os.path.dirname(gdtfile),
                          recursive=False)
        observer.start()

        try:
            infos = readGDT(gdtfile)
            tm.activePatientChanged.emit(infos)
        except Exception as e:
            displayErrorMessage("While loading GDT file: %s" % (e))

        av.show()
        ret = app.exec_()
        observer.stop()
        observer.join()
    sys.exit(ret)
Example #53
0
		s = f.read()
		f.close()
		self.Edit.setText(s)
		self.filename = fn
		
	def runCode(self):
		self.msg('run')
		
			
	def msg(self, m):
		self.msgwin.setText(self.tr(m))
		

if __name__ == '__main__':
	app = QApplication(sys.argv)

	# translation stuff
	lang=QLocale.system().name()
	t=QTranslator()
	t.load("lang/"+lang, os.path.dirname(__file__))
	app.installTranslator(t)
	t1=QTranslator()
	t1.load("qt_"+lang,
	        QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(t1)

	mw = Expt()
	mw.show()
	sys.exit(app.exec_())
	
Example #54
0
def prepare(tests=False):
    app = QApplication(sys.argv)
    app.setOrganizationName("manuskript" + ("_tests" if tests else ""))
    app.setOrganizationDomain("www.theologeek.ch")
    app.setApplicationName("manuskript" + ("_tests" if tests else ""))
    app.setApplicationVersion(getVersion())

    print("Running manuskript version {}.".format(getVersion()))
    icon = QIcon()
    for i in [16, 32, 64, 128, 256, 512]:
        icon.addFile(appPath("icons/Manuskript/icon-{}px.png".format(i)))
    qApp.setWindowIcon(icon)

    app.setStyle("Fusion")

    # Load style from QSettings
    settings = QSettings(app.organizationName(), app.applicationName())
    if settings.contains("applicationStyle"):
        style = settings.value("applicationStyle")
        app.setStyle(style)

    # Translation process
    locale = QLocale.system().name()

    appTranslator = QTranslator()
    # By default: locale
    translation = appPath(
        os.path.join("i18n", "manuskript_{}.qm".format(locale)))

    # Load translation from settings
    if settings.contains("applicationTranslation"):
        translation = appPath(
            os.path.join("i18n", settings.value("applicationTranslation")))
        print("Found translation in settings:", translation)

    if appTranslator.load(translation):
        app.installTranslator(appTranslator)
        print(app.tr("Loaded translation: {}.").format(translation))

    else:
        print(
            app.tr("Note: No translator found or loaded for locale {}.").
            format(locale))

    QIcon.setThemeSearchPaths(QIcon.themeSearchPaths() + [appPath("icons")])
    QIcon.setThemeName("NumixMsk")

    # Font siue
    if settings.contains("appFontSize"):
        f = qApp.font()
        f.setPointSize(settings.value("appFontSize", type=int))
        app.setFont(f)

    # Main window
    from manuskript.mainWindow import MainWindow

    MW = MainWindow()
    # We store the system default cursor flash time to be able to restore it
    # later if necessary
    MW._defaultCursorFlashTime = qApp.cursorFlashTime()

    # Command line project
    if len(sys.argv) > 1 and sys.argv[1][-4:] == ".msk":
        if os.path.exists(sys.argv[1]):
            path = os.path.abspath(sys.argv[1])
            MW._autoLoadProject = path

    return app, MW
Example #55
0
    except:
        pass

    if fieldtemp[0] != "English":
        transfile = ""
        if fieldtemp[0] == "Japanese":
            transfile = "rgg_py_ja"
        if fieldtemp[0] == "Dutch":
            transfile = "rgg_py_nl"
        if fieldtemp[0] == "German":
            transfile = "rgg_py_de"

        trans = QTranslator()
        if not trans.load(transfile):
            print(transfile + " not found")
        application.installTranslator(trans)

    QApplication.processEvents()

    qgf = QGLFormat.defaultFormat()
    qgf.setSampleBuffers(True)
    QGLFormat.setDefaultFormat(qgf)

    QApplication.processEvents()

    main = injectMain()

    QApplication.processEvents()

    from libraries.rggLoadMain import loadMain, APPLICATION, MAIN, CLIENT, PROGRESS
Example #56
0
                continue
            ret = widget.slot_about_close(True)
            save_all = ret == QMessageBox.SaveAll


if __name__ == '__main__':
    import sys
    import cgitb
    import logging

    cgitb.enable(format='text')
    logging.basicConfig(level=logging.INFO)

    app = QApplication(sys.argv)
    app.setStyleSheet("""
    PMBaseEditor {
        qproperty-theme: "Material-Dark";
    }
    """)

    app.trans_qt = QTranslator()
    app.trans_qt.load('../../../../translations/qt_{0}.qm'.format(QLocale.system().name()))
    app.installTranslator(app.trans_qt)

    w = PMCodeEditTabWidget()
    w.show()
    w.setup_ui()
    w.currentWidget().load_file(__file__)

    sys.exit(app.exec_())
Example #57
0
class Application(QObject):
    """Class to implement a Qt Application."""

    instance = None

    QmlApplication_CLS = QmlApplication

    _logger = _module_logger.getChild('Application')

    ##############################################

    # Fixme: Singleton

    @classmethod
    def create(cls, *args, **kwargs):

        if cls.instance is not None:
            raise NameError('Instance exists')

        cls.instance = cls(*args, **kwargs)
        return cls.instance

    ##############################################

    def __init__(self):

        self._logger.info('Ctor')

        super().__init__()

        QtCore.qInstallMessageHandler(self._message_handler)

        self._parse_arguments()

        # For Qt Labs Platform native widgets
        # self._application = QGuiApplication(sys.argv)
        # use QCoreApplication::instance() to get instance
        self._application = QApplication(sys.argv)
        self._application.main = self
        self._init_application()

        self._engine = QQmlApplicationEngine()
        self._qml_application = self.QmlApplication_CLS(self)
        self._application.qml_main = self._qml_application

        self._platform = QtPlatform()
        # self._logger.info('\n' + str(self._platform))

        #! self._load_translation()
        self.register_qml_types()
        self._set_context_properties()
        self._load_qml_main()

        # self._run_before_event_loop()

        self._application.aboutToQuit.connect(self.aboutToQuit)

        QTimer.singleShot(0, self.post_init)

    ##############################################

    @property
    def parser(self):
        return self._parser

    @property
    def args(self):
        return self._args

    @property
    def platform(self):
        return self._platform

    @property
    def settings(self):
        return self._settings

    @property
    def qml_application(self):
        return self._qml_application

    ##############################################

    def _print_critical_message(self, message):
        # print('\nCritical Error on {}'.format(datetime.datetime.now()))
        # print('-'*80)
        # print(message)
        self._logger.critical(message)

    ##############################################

    def _message_handler(self, msg_type, context, msg):

        if msg_type == QtCore.QtDebugMsg:
            method = self._logger.debug
        elif msg_type == QtCore.QtInfoMsg:
            method = self._logger.info
        elif msg_type == QtCore.QtWarningMsg:
            method = self._logger.warning
        elif msg_type in (QtCore.QtCriticalMsg, QtCore.QtFatalMsg):
            method = self._logger.critical
            # method = None

        # local_msg = msg.toLocal8Bit()
        # localMsg.constData()
        context_file = context.file
        if context_file is not None:
            file_path = Path(context_file).name
        else:
            file_path = ''
        message = '{1} {3} — {0}'.format(msg, file_path, context.line,
                                         context.function)
        if method is not None:
            method(message)
        else:
            self._print_critical_message(message)

    ##############################################

    def _on_critical_exception(self, exception):
        message = str(exception) + '\n' + traceback.format_exc()
        self._print_critical_message(message)
        self._qml_application.notify_error(exception)
        # sys.exit(1)

    ##############################################

    def _init_application(self):

        self._application.setOrganizationName(
            ApplicationMetadata.organisation_name)
        self._application.setOrganizationDomain(
            ApplicationMetadata.organisation_domain)

        self._application.setApplicationName(ApplicationMetadata.name)
        self._application.setApplicationDisplayName(
            ApplicationMetadata.display_name)
        self._application.setApplicationVersion(ApplicationMetadata.version)

        logo_path = ':/icons/logo/logo-256.png'
        self._application.setWindowIcon(QIcon(logo_path))

        QIcon.setThemeName('material')

        self._settings = ApplicationSettings()

    ##############################################

    @classmethod
    def setup_gui_application(self):

        QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
        # QQuickStyle.setStyle('Material')

    ##############################################

    def _parse_arguments(self):

        self._parser = argparse.ArgumentParser(description='CodeReview', )

        self.parse_arguments()

        self._args = self._parser.parse_args()

    ##############################################

    def parse_arguments(self):

        # self.parser.add_argument(
        #     '--version',
        #     action='store_true', default=False,
        #     help="show version and exit",
        # )

        self.parser.add_argument(
            '--dont-translate',
            action='store_true',
            default=False,
            help="Don't translate application",
        )

        self.parser.add_argument(
            '--user-script',
            action=PathAction,
            default=None,
            help='user script to execute',
        )

        self.parser.add_argument(
            '--user-script-args',
            default='',
            help="user script args (don't forget to quote)",
        )

    ##############################################

    def _load_translation(self):

        if self._args.dont_translate:
            return

        # Fixme: ConfigInstall
        # directory = ':/translations'
        directory = str(Path(__file__).parent.joinpath('rcc', 'translations'))

        locale = QtCore.QLocale()
        self._translator = QtCore.QTranslator()
        if self._translator.load(locale, 'code-review', '.', directory, '.qm'):
            self._application.installTranslator(self._translator)
        else:
            raise NameError('No translator for locale {}'.format(
                locale.name()))

    ##############################################

    def register_qml_types(self):

        qmlRegisterType(KeySequenceEditor, 'CodeReview', 1, 0,
                        'KeySequenceEditor')

        qmlRegisterUncreatableType(Shortcut, 'CodeReview', 1, 0, 'Shortcut',
                                   'Cannot create Shortcut')
        qmlRegisterUncreatableType(ApplicationSettings, 'CodeReview', 1, 0,
                                   'ApplicationSettings',
                                   'Cannot create ApplicationSettings')
        qmlRegisterUncreatableType(self.QmlApplication_CLS, 'CodeReview', 1, 0,
                                   'QmlApplication',
                                   'Cannot create QmlApplication')

    ##############################################

    def _set_context_properties(self):
        context = self._engine.rootContext()
        context.setContextProperty('application', self._qml_application)
        context.setContextProperty('application_settings', self._settings)

    ##############################################

    def _load_qml_main(self):

        self._logger.info('Load QML...')

        qml_path = Path(__file__).parent.joinpath('qml')
        # qml_path = 'qrc:///qml'
        self._engine.addImportPath(str(qml_path))

        main_qml_path = qml_path.joinpath('main.qml')
        self._qml_url = QUrl.fromLocalFile(str(main_qml_path))
        # QUrl('qrc:/qml/main.qml')
        self._engine.objectCreated.connect(self._check_qml_is_loaded)
        self._engine.load(self._qml_url)

        self._logger.info('QML loaded')

    ##############################################

    def _check_qml_is_loaded(self, obj, url):
        # See https://bugreports.qt.io/browse/QTBUG-39469
        if (obj is None and url == self._qml_url):
            sys.exit(-1)

    ##############################################

    def exec_(self):
        self._logger.info('Start event loop')
        rc = self._application.exec_()
        self._logger.info('Event loop done {}'.format(rc))
        del self._engine  # solve quit issue ?
        sys.exit(rc)

    ##############################################

    def aboutToQuit(self):
        self._logger.info('')

    ##############################################

    def post_init(self):

        # Fixme: ui refresh ???

        self._logger.info('post Init...')

        if self._args.user_script is not None:
            self.execute_user_script(self._args.user_script)

        self._logger.info('Post Init Done')

    ##############################################

    def execute_user_script(self, script_path):
        """Execute an user script provided by file *script_path* in a context where is defined a
        variable *application* that is a reference to the application instance.

        """

        script_path = Path(script_path).absolute()
        self._logger.info('Execute user script:\n  {}'.format(script_path))
        try:
            source = open(script_path).read()
        except FileNotFoundError:
            self._logger.info('File {} not found'.format(script_path))
            sys.exit(1)
        try:
            bytecode = compile(source, script_path, 'exec')
        except SyntaxError as exception:
            self._on_critical_exception(exception)
        try:
            exec(bytecode, {'application': self})
        except Exception as exception:
            self._on_critical_exception(exception)
        self._logger.info('User script done')