Esempio n. 1
0
def run(torrent_client):
    """
    Start the UI
    """
    app = QApplication(sys.argv)

    app.setOrganizationName("example")
    app.setOrganizationDomain("example.com")

    engine = QQmlApplicationEngine()

    context = engine.rootContext()

    ctx_manager = ContextManager(torrent_client)

    ctx_props = ctx_manager.context_props
    for prop_name in ctx_props:
        context.setContextProperty(prop_name, ctx_props[prop_name])

    qml_file = os.path.join(os.path.dirname(__file__), "views/window.qml")
    engine.load(QUrl.fromLocalFile(os.path.abspath(qml_file)))

    if not engine.rootObjects():
        sys.exit(-1)

    window = engine.rootObjects()[0]
    ctx_manager.set_window(window)

    ret = app.exec_()

    ctx_manager.clean_up()
    sys.exit(ret)
Esempio n. 2
0
    def __init__(self, opts, args):
        QGuiApplication.__init__(self, args)
        translator = QTranslator()
        translator.load(QLocale.system().name(), "po")
        self.installTranslator(translator)
        qmlRegisterUncreatableType(
            ReleaseDownload, 'LiveUSB', 1, 0, 'Download',
            'Not creatable directly, use the liveUSBData instance instead')
        qmlRegisterUncreatableType(
            ReleaseWriter, 'LiveUSB', 1, 0, 'Writer',
            'Not creatable directly, use the liveUSBData instance instead')
        qmlRegisterUncreatableType(
            ReleaseListModel, 'LiveUSB', 1, 0, 'ReleaseModel',
            'Not creatable directly, use the liveUSBData instance instead')
        qmlRegisterUncreatableType(
            Release, 'LiveUSB', 1, 0, 'Release',
            'Not creatable directly, use the liveUSBData instance instead')
        qmlRegisterUncreatableType(
            USBDrive, 'LiveUSB', 1, 0, 'Drive',
            'Not creatable directly, use the liveUSBData instance instead')
        qmlRegisterUncreatableType(LiveUSBData, 'LiveUSB', 1, 0, 'Data',
                                   'Use the liveUSBData root instance')

        engine = QQmlApplicationEngine()
        self.data = LiveUSBData(opts)
        engine.rootContext().setContextProperty('liveUSBData', self.data)
        if (opts.directqml):
            engine.load(QUrl('liveusb/liveusb.qml'))
        else:
            engine.load(QUrl('qrc:/liveusb.qml'))
        engine.rootObjects()[0].show()

        self.exec_()
Esempio n. 3
0
def run():
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()

    engine.load('ui.qml')
    win = engine.rootObjects()[0]

    # testButton = engine.findChild(QObject, "myButton")
    # testButton.messageSend.connect(myfunction)
    # testButton.clicked.connect(myfunction)

    # testitem = engine.findChild(QObject, "butest")
    # testitem.clicked.connect(myfunction)

    buttoning = win.findChild(QObject, "firsttabbutton")
    buttoning.clicked.connect(myfunction)

    # button_text = win.findChild(QObject, "first_tab_border")
    # button_text.opacity = 0

    # testingitem = engine.findChild(QObject, "butesting")
    # testingitem.clicked.connect(myfunction)
    # testingitem.clicked.connect(myfunction)

    if not engine.rootObjects():
        return -1

    return app.exec_()
Esempio n. 4
0
def main():
    # Set the QtQuick Style
    # Acceptable values: Default, Fusion, Imagine, Material, Universal.
    os.environ['QT_QUICK_CONTROLS_STYLE'] = sys.argv[1] if len(sys.argv) > 1 else "Imagine"

    # Create an instance of the application
    # QApplication MUST be declared in global scope to avoid segmentation fault
    app = QApplication(sys.argv)

    # Create QML engine
    engine = QQmlApplicationEngine()

    # Load the qml file into the engine
    engine.load(QUrl('qrc:/pyqt5_qtquick2_example/qml/main.qml'))

    # Qml file error handling
    if not engine.rootObjects():
        sys.exit(-1)

    # Send QT_QUICK_CONTROLS_STYLE to main qml (only for demonstration)
    # For more details and other methods to communicate between Qml and Python:
    #   http://doc.qt.io/archives/qt-4.8/qtbinding.html
    qtquick2Themes = engine.rootObjects()[0].findChild(QObject, 'qtquick2Themes')
    qtquick2Themes.setProperty('text', os.environ['QT_QUICK_CONTROLS_STYLE'])

    # engine.quit.connect(app.quit)
    # Unnecessary,
    # since QQmlEngine.quit has already connect to QCoreApplication.quit

    res = app.exec_()
    # Deleting the view before it goes out of scope is required to make sure all
    # child QML instances are destroyed in the correct order or a segmentation
    # error would occur.
    del engine
    sys.exit(res)
Esempio n. 5
0
def runQML():
    #view = QQuickView()
    #ui.setupUi(this)
    #container = QWidget.createWindowContainer(view, this)
    #container.setMinimumSize(200, 200)
    #container.setMaximumSize(200, 200)
    app =QApplication(sys.argv)
    engine = QQmlApplicationEngine()
#    app.setWindowIcon(QIcon("icon.png"))
    root = engine.rootContext()
    engine.load('dice/main.qml')
    #ui.verticalLayout.addWidget(container)
    child = engine.rootObjects()[0].findChild(QtCore.QObject, "foo_object")
    #print(str(child))
    child.setProperty("text", "Blödsinn")
    #root.setContextProperty("guisettings", guisettings)



    print(str(len(engine.rootObjects())))
    for w in engine.rootObjects():
        #print(str(type(w.contentItem().childItems()).__name__))
        for v in w.contentItem().childItems():
            print(str(v.setOpacity(0.9)))
            for i,x in enumerate(v.childItems()):
                print(str(x.setOpacity(0.9)))
                x.stackAfter(v.childItems()[-i])




    if not engine.rootObjects():
        return -1

    return app.exec_()
Esempio n. 6
0
def main():
    print("start")
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    engine.load(QUrl("main.qml"))

    engine.rootObjects()[0].show()

    sys.exit(app.exec_())
Esempio n. 7
0
def main():
    """application entry point"""
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    engine.quit.connect(app.quit)
    engine.load('main.qml')

    backend = BackendLogic()
    engine.rootObjects()[0].setProperty('backend', backend)
    backend.update_time()
    sys.exit(app.exec())
Esempio n. 8
0
def run():
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()
    engine.load('qt_gui/main_window.qml')
    if not engine.rootObjects():
        return -1

    win = engine.rootObjects()[0]

    okButton = win.findChild(QObject, "okButton")
    okButton.clicked.connect(action)

    return app.exec_()
Esempio n. 9
0
def main():
    import sys

    QGuiApplication.setApplicationName("Gallery")
    QGuiApplication.setOrganizationName("QtProject")
    QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling)

    app = QGuiApplication(sys.argv)

    QIcon.setThemeName("gallery")

    settings = QSettings()

    style = Fakequickcontrols2.name()
    if style:
        settings.setValue("style", style)
    else:
        Fakequickcontrols2.setStyle(settings.value("style"))

    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty(
        "availableStyles", Fakequickcontrols2.availableStyles())
    engine.load(QUrl("qrc:/gallery.qml"))
    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())
Esempio n. 10
0
class MainWindow(QObject):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.log = logging.getLogger(__name__)
        self._read_settings()

        self.client = Client(self)

        if self.remember:
            self._autologin()

        self.model = MainWindowViewModel(self)
        self.loginModel = LoginViewModel(self.client, self.user, self.password, self.remember, self)
        self.loginModel.panel_visible = not self.remember
        self.gamesModel = GamesViewModel(self)

        self.engine = QQmlApplicationEngine(self)
        self.engine.rootContext().setContextProperty('windowModel', self.model)
        self.engine.rootContext().setContextProperty('loginModel', self.loginModel)
        self.engine.rootContext().setContextProperty('contentModel', self.gamesModel)
        self.engine.quit.connect(parent.quit)
        self.engine.load(QUrl.fromLocalFile('ui/Chrome.qml'))

        self.window = self.engine.rootObjects()[0]

        # wire up logging console
        self.console = self.window.findChild(QQuickItem, 'console')
        parent.log_changed.connect(self._log)

    def show(self):
        self.window.show()

    def _read_settings(self):
        stored = settings.get()
        stored.beginGroup('login')

        self.user = stored.value('user')
        self.password = stored.value('password')
        self.remember = stored.value('remember') == 'true'

        stored.endGroup()

    @async_slot
    def _autologin(self):
        try:
            self.log.info('logging in (auto)...')
            self.loginModel.logged_in = yield from self.client.login(self.user, self.password)
            self.log.debug('autologin result: {}'.format(self.loginModel.logged_in))
        except Exception as e:
            self.log.error('autologin failed. {}'.format(e))

    @pyqtSlot(str)
    def _log(self, msg):
        # replace with collections.deque binding(ish)?
        if self.console.property('lineCount') == LOG_BUFFER_SIZE:
            line_end = self.console.property('text').find('\n') + 1
            self.console.remove(0, line_end)

        self.console.append(msg)
Esempio n. 11
0
def main():
    if os.getuid() != 0:
        print('root permissions needed to launch keylogger')
        return
    no_func_keys = '--no-func-keys' in sys.argv
    if no_func_keys:
        ignored_keys = []
    else:
        ignored_keys = ['<Enter>', '<LShft>', '<#+8>', '<#+18>']

    app = QGuiApplication(sys.argv[:1])

    keypressprovider = KeyPressProvider(ignore_keys=ignored_keys,
                                        no_func_keys=no_func_keys)

    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty("text_provider", keypressprovider)
    engine.load(os.path.join(os.path.dirname(__file__), "main.qml"))
    window = engine.rootObjects()[0]
    if not window:
        sys.exit(-1)

    k = keypressprovider.keysPressedChanged

    k.connect(window.setText)
    sys.exit(app.exec_())
Esempio n. 12
0
class MainWindow(QObject):

    def __init__(self, parent=None):
        super().__init__(parent)

        self.model = MainWindowViewModel(self)
        self.loginModel = LoginViewModel(self)

        self.engine = QQmlApplicationEngine(self)
        self.engine.rootContext().setContextProperty('model', self.model)
        self.engine.rootContext().setContextProperty('loginModel', self.loginModel)
        self.engine.quit.connect(parent.quit)
        self.engine.load(QUrl.fromLocalFile('ui/Chrome.qml'))

        self.window = self.engine.rootObjects()[0]

        # wire up logging console
        self.log = self.window.findChild(QQuickItem, 'log')
        parent.log_changed.connect(self._log)

    def show(self):
        self.window.show()

    def _log(self, msg):
        # replace with collections.deque binding(ish)?
        if self.log.property('lineCount') == LOG_BUFFER_SIZE:
            line_end = self.log.property('text').find('\n') + 1
            self.log.remove(0, line_end)

        self.log.append(msg)
def main():
    argv = sys.argv
    
    # Trick to set the style / not found how to do it in pythonic way
    argv.extend(["-style", "universal"])
    app = QGuiApplication(argv)

    qmlRegisterType(FigureCanvasQTAggToolbar, "Backend", 1, 0, "FigureToolbar")    
    imgProvider = MatplotlibIconProvider()
    
    # !! You must specified the QApplication as parent of QQmlApplicationEngine
    # otherwise a segmentation fault is raised when exiting the app
    engine = QQmlApplicationEngine(parent=app)
    engine.addImageProvider("mplIcons", imgProvider)
    
    context = engine.rootContext()
    data_model = DataSeriesModel()
    context.setContextProperty("dataModel", data_model)
    mainApp = Form(data=data_model)
    context.setContextProperty("draw_mpl", mainApp)
    
    engine.load(QUrl('main.qml'))
    
    win = engine.rootObjects()[0]
    mainApp.figure = win.findChild(QObject, "figure").getFigure()
    
    rc = app.exec_()
    # There is some trouble arising when deleting all the objects here
    # but I have not figure out how to solve the error message.
    # It looks like 'app' is destroyed before some QObject
    sys.exit(rc)
Esempio n. 14
0
class SciHubAddSciHubURL(QObject):
    showWindowAddSciHubURL = pyqtSignal()

    def __init__(self, conf, parent):
        super(SciHubAddSciHubURL, self).__init__()

        self._conf = conf
        self._parent = parent

        self._engine = QQmlApplicationEngine()
        self._engine.load('qrc:/ui/SciHubEVAAddSciHubURL.qml')
        self._window = self._engine.rootObjects()[0]
        self._connect()

    def _connect(self):
        # Connect QML signals to PyQt slots
        self._window.addSciHubURL.connect(self.addSciHubURL)

        # Connect PyQt signals to QML slots
        self.showWindowAddSciHubURL.connect(
            self._window.showWindowAddSciHubURL)

    @pyqtSlot(str)
    def addSciHubURL(self, url):
        scihub_available_urls = json.loads(
            self._conf.get('network', 'scihub_available_urls'))

        if not url in scihub_available_urls:
            scihub_available_urls.append(url)

        self._conf.set('network', 'scihub_available_urls',
                       json.dumps(scihub_available_urls))
        self._parent.loadFromConf()
Esempio n. 15
0
    def __init__(self, argv):
        app = QGuiApplication(argv)
        engine = QQmlApplicationEngine()
        context = engine.rootContext()
        context.setContextProperty('mainWindow',
                                   engine)  # the string can be anything

        engine.load('/Users/hebingchang/QtCreator/sniffer/sniffer.qml')
        self.root = engine.rootObjects()[0]
        self.root.setDevModel(pcap.findalldevs())
        self.dev = pcap.findalldevs()[0]
        self.sniffer_status = False

        # self.root.appendPacketModel({'source': '10.162.31.142', 'destination': '151.101.74.49', 'length': 52, 'id': 1})

        self.packetModel = self.root.findChild(QObject, "packetModel")

        btnStart = self.root.findChild(QObject, "btnStart")
        btnStart.clicked.connect(self.myFunction)  # works too

        self.comboDev = self.root.findChild(QObject, "comboDevice")
        self.comboDev.activated.connect(self.getDev)

        engine.quit.connect(app.quit)
        sys.exit(app.exec_())
Esempio n. 16
0
def main_gui(args: argparse.Namespace):
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    # Check environment first
    from PyQt5.QtWidgets import QMessageBox, QSystemTrayIcon
    def dialog(message: str) -> None:
        QMessageBox.critical(None, "VirtScreen", message)
    if not QSystemTrayIcon.isSystemTrayAvailable():
        dialog("Cannot detect system tray on this system.")
        sys.exit(1)
    check_env(args, dialog)

    app.setApplicationName("VirtScreen")
    app.setWindowIcon(QIcon(ICON_PATH))
    os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material"

    # Register the Python type.  Its URI is 'People', it's v1.0 and the type
    # will be called 'Person' in QML.
    qmlRegisterType(DisplayProperty, 'VirtScreen.DisplayProperty', 1, 0, 'DisplayProperty')
    qmlRegisterType(Backend, 'VirtScreen.Backend', 1, 0, 'Backend')
    qmlRegisterType(Cursor, 'VirtScreen.Cursor', 1, 0, 'Cursor')
    qmlRegisterType(Network, 'VirtScreen.Network', 1, 0, 'Network')

    # Create a component factory and load the QML script.
    engine = QQmlApplicationEngine()
    engine.load(QUrl(MAIN_QML_PATH))
    if not engine.rootObjects():
        dialog("Failed to load QML")
        sys.exit(1)
    sys.exit(app.exec_())
    with loop:
        loop.run_forever()
Esempio n. 17
0
class SciHubCaptcha(QObject):
    showWindowCaptcha = pyqtSignal(str)

    def __init__(self, parent, log=None):
        super(SciHubCaptcha, self).__init__()

        self._parent = parent
        self.log = log

        self._engine = QQmlApplicationEngine()
        self._engine.load('qrc:/ui/SciHubEVACaptcha.qml')
        self._window = self._engine.rootObjects()[0]
        self._connect()

    def _connect(self):
        # Connect QML signals to PyQt slots
        self._window.killCaptcha.connect(self.killCaptcha)

        # Connect PyQt signals to QML slots
        self.showWindowCaptcha.connect(self._window.showWindowCaptcha)

    @pyqtSlot(bool, str)
    def killCaptcha(self, kill, captcha):
        if kill:
            self._parent.rampageWithCaptchar(captcha)
        else:
            self.log(self.tr('Battle canceled, rampage again?'), 'ERROR')
            self._parent.afterRampage.emit()
Esempio n. 18
0
class QmlAusgabe(object):
    def __init__(self, pathToQmlFile="guiTest.qml"):

        #QML-Engine
        self.__appEngine = QQmlApplicationEngine()
        self.__appEngine.load(pathToQmlFile)

        self.__appWindow = self.__appEngine.rootObjects()[0]

        self.__rectangle1 = self.__appWindow.findChild(QObject, "Rectangle1")
        self.__rectangle2 = self.__appWindow.findChild(QObject, "Rectangle2")

        self.__colorState = False

    def changeColor(self):
        if self.__colorState:
            self.__rectangle1.setProperty("color", "red")
            self.__rectangle2.setProperty("color", "green")
        else:
            self.__rectangle1.setProperty("color", "yellow")
            self.__rectangle2.setProperty("color", "blue")
        self.__colorState = not self.__colorState

    def show(self):
        self.__appWindow.show()
Esempio n. 19
0
class PDFxGui:
    QML_FILE = "qml/MainWindow.qml"
    window = None
    threads = []
    pdf_windows = []

    def __init__(self):
        self.threads = []

        # Create and setup window
        self.engine = QQmlApplicationEngine()
        self.engine.load(self.QML_FILE)
        self.window = self.engine.rootObjects()[0]

        # Connect signals
        self.window.signalOpenPdfs.connect(self.open_pdf)
        self.window.signalShowAboutWindow.connect(show_about_window)

    def open_pdf(self, urls):
        num_pdfs = urls.property("length").toInt()
        pdf_urls = [
            urls.property(index).toString() for index in range(num_pdfs)
        ]
        if len(pdf_urls) == 0:
            return

        def signal_item_start(uri):
            print("started:", uri)
            self.window.setStatusText("Opening %s..." %
                                      (os.path.basename(uri)))

        def signal_item_finished(uri):
            print("finished:", uri)
            win = PdfDetailWindow(uri)
            win.window.show()
            self.pdf_windows.append(win)

        def signal_item_error(uri, error):
            print("error:", uri, error)

        def signal_item_extract_page(uri, curpage):
            print("page:", curpage)
            self.window.setStatusText("Reading page %s of %s..." %
                                      (curpage, os.path.basename(uri)))

        def signal_finished():
            print("all finished")
            self.window.setState("")
            self.window.setStatusText("")

        self.window.setState("busy")
        open_thread = OpenPdfQThread(pdf_urls)
        open_thread.signal_item_start.connect(signal_item_start)
        open_thread.signal_item_extract_page.connect(signal_item_extract_page)
        open_thread.signal_item_finished.connect(signal_item_finished)
        open_thread.signal_item_error.connect(signal_item_error)
        open_thread.signal_finished.connect(signal_finished)
        open_thread.start()
        self.threads.append(open_thread)
Esempio n. 20
0
class AboutWindow:
    QML_FILE = "qml/AboutWindow.qml"

    def __init__(self):
        # Create window from QML via QQmlApplicationEngine
        self.engine = QQmlApplicationEngine()
        self.engine.load(self.QML_FILE)
        self.window = self.engine.rootObjects()[0]
Esempio n. 21
0
def run():
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()
    engine.load('main.qml')

    if not engine.rootObjects():
        return -1
    return app.exec_()
Esempio n. 22
0
class AboutWindow:
    QML_FILE = "qml/AboutWindow.qml"

    def __init__(self):
        # Create window from QML via QQmlApplicationEngine
        self.engine = QQmlApplicationEngine()
        self.engine.load(self.QML_FILE)
        self.window = self.engine.rootObjects()[0]
Esempio n. 23
0
def runQML():
    app =QApplication(sys.argv)
    engine = QQmlApplicationEngine()
    app.setWindowIcon(QIcon("icon.png"))
    engine.load('main.qml')

    if not engine.rootObjects():
        return -1
    return app.exec_()
Esempio n. 24
0
def main():
    app = QGuiApplication(sys.argv)

    current_path = os.path.abspath(os.path.dirname(__file__))
    qml_file = os.path.join(current_path, 'qml/dashboard.qml')

    engine = QQmlApplicationEngine()
    engine.load(QUrl.fromLocalFile(qml_file))

    ctx = engine.rootContext()
    win = engine.rootObjects()[0]
    py_mainapp = MainApp(ctx, win)

    engine.rootContext().setContextProperty("py_mainapp", py_mainapp)

    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())
Esempio n. 25
0
    def launch(self):
        global w_SimX
        global currentWindow

        while self.__running.isSet():
            self.__flag.wait(
            )  # returns immediately when false, blocking until the internal identity bit is true to return

            app = QApplication(sys.argv)  #creating an application object
            engine = QQmlApplicationEngine()  #creating an engine object
            currentWindow = guiWindow(
            )  #creating object of guiWindow class and initialize constructor
            engine.rootContext().setContextProperty(
                "guiWindow", currentWindow)  #connection between qml and python
            engine.load('mainMenu.qml')  #loading qml
            w_SimX = engine.rootObjects()[0]  #w_SimX object for qml
            if not engine.rootObjects():
                sys.exit(-1)
            sys.exit(app.exec_())  #to exit window
Esempio n. 26
0
class App():
    def __init__(self, qapp):

        self.engine = QQmlApplicationEngine()
        self.engine.load('main.qml')
        try:
            qmlroot = self.engine.rootObjects()[0]
        except:
            print('Failed to load QML')
            sys.exit()
Esempio n. 27
0
def run():
	app = QApplication(sys.argv)
	engine = QQmlApplicationEngine()
	engine.load('49_QtQuick.qml')
	app.setWindowIcon(QIcon('./icon/icon.png'))

	if not engine.rootObjects():
		return -1

	return app.exec_()
Esempio n. 28
0
def main():
    import sys

    app = QApplication(sys.argv)

    QQuickWindow.setDefaultAlphaBuffer(True)

    QCoreApplication.setApplicationName("Photosurface")
    QCoreApplication.setOrganizationName("QtProject")
    QCoreApplication.setApplicationVersion(QT_VERSION_STR)
    parser = QCommandLineParser()
    parser.setApplicationDescription("Qt Quick Demo - Photo Surface")
    parser.addHelpOption()
    parser.addVersionOption()
    parser.addPositionalArgument("directory",
                                 "The image directory or URL to show.")
    parser.process(app)

    initialUrl = QUrl()
    if parser.positionalArguments():
        initialUrl = QUrl.fromUserInput(parser.positionalArguments()[0],
                                        QDir.currentPath(),
                                        QUrl.AssumeLocalFile)
        if not initialUrl.isValid():
            print(
                'Invalid argument: "',
                parser.positionalArguments()[0],
                '": ',
                initialUrl.errorString(),
            )
            sys.exit(1)

    nameFilters = imageNameFilters()

    engine = QQmlApplicationEngine()
    context: QQmlContext = engine.rootContext()

    picturesLocationUrl = QUrl.fromLocalFile(QDir.homePath())
    picturesLocations = QStandardPaths.standardLocations(
        QStandardPaths.PicturesLocation)
    if picturesLocations:
        picturesLocationUrl = QUrl.fromLocalFile(picturesLocations[0])
        if not initialUrl and QDir(picturesLocations[0]).entryInfoList(
                nameFilters, QDir.Files):
            initialUrl = picturesLocationUrl

    context.setContextProperty("contextPicturesLocation", picturesLocationUrl)
    context.setContextProperty("contextInitialUrl", initialUrl)
    context.setContextProperty("contextImageNameFilters", nameFilters)

    engine.load(QUrl("qrc:///photosurface.qml"))
    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())
Esempio n. 29
0
class PDFxGui:
    QML_FILE = "qml/MainWindow.qml"
    window = None
    threads = []
    pdf_windows = []

    def __init__(self):
        self.threads = []
        
        # Create and setup window
        self.engine = QQmlApplicationEngine()
        self.engine.load(self.QML_FILE)
        self.window = self.engine.rootObjects()[0]

        # Connect signals
        self.window.signalOpenPdfs.connect(self.open_pdf)
        self.window.signalShowAboutWindow.connect(show_about_window)

    def open_pdf(self, urls):
        num_pdfs = urls.property("length").toInt()
        pdf_urls = [urls.property(index).toString() for index in range(num_pdfs)]
        if len(pdf_urls) == 0:
            return

        def signal_item_start(uri):
            print("started:", uri)
            self.window.setStatusText("Opening %s..." % (os.path.basename(uri)))

        def signal_item_finished(uri):
            print("finished:", uri)
            win = PdfDetailWindow(uri)
            win.window.show()
            self.pdf_windows.append(win)

        def signal_item_error(uri, error):
            print("error:", uri, error)

        def signal_item_extract_page(uri, curpage):
            print("page:", curpage)
            self.window.setStatusText("Reading page %s of %s..." % (curpage, os.path.basename(uri)))

        def signal_finished():
            print("all finished")
            self.window.setState("")
            self.window.setStatusText("")

        self.window.setState("busy")
        open_thread = OpenPdfQThread(pdf_urls)
        open_thread.signal_item_start.connect(signal_item_start)
        open_thread.signal_item_extract_page.connect(signal_item_extract_page)
        open_thread.signal_item_finished.connect(signal_item_finished)
        open_thread.signal_item_error.connect(signal_item_error)
        open_thread.signal_finished.connect(signal_finished)
        open_thread.start()
        self.threads.append(open_thread)
Esempio n. 30
0
 def start_default_calendar(self):
     self.prepare_calendar()
     engine = QQmlApplicationEngine()
     ctx = engine.rootContext()
     ctx.setContextProperty("controller", self)
     ctx.setContextProperty("calendarData", self.calendar_data)
     engine.load(QUrl('ViewStuff/default_calendar/default_calendar.qml'))
     win = engine.rootObjects()[0]
     btn = win.findChild(QObject, 'createEvent')
     btn.clicked.connect(self.add_event)  # works too
     return engine
Esempio n. 31
0
File: main.py Progetto: ihrwein/yarg
def main():
    app = QGuiApplication(sys.argv)
    qmlRegisterType(MainController, 'MainController', 1, 0, 'MainController')
    qmlRegisterType(ProfileViewModel, 'ProfileViewModel', 1, 0, 'ProfileViewModel')
    engine = QQmlApplicationEngine()
    main_controller = MainController()
    main_controller.profile_selection_changed(0)
    engine.rootContext().setContextProperty('mainController', main_controller)
    engine.load(QUrl.fromLocalFile('yarg/resource/main.qml'))
    window = engine.rootObjects()[0]
    sys.exit(app.exec_())
Esempio n. 32
0
File: main.py Progetto: ihrwein/yarg
def main():
    app = QGuiApplication(sys.argv)
    qmlRegisterType(MainController, 'MainController', 1, 0, 'MainController')
    qmlRegisterType(ProfileViewModel, 'ProfileViewModel', 1, 0,
                    'ProfileViewModel')
    engine = QQmlApplicationEngine()
    main_controller = MainController()
    main_controller.profile_selection_changed(0)
    engine.rootContext().setContextProperty('mainController', main_controller)
    engine.load(QUrl.fromLocalFile('yarg/resource/main.qml'))
    window = engine.rootObjects()[0]
    sys.exit(app.exec_())
Esempio n. 33
0
class PixelWall(QApplication):

    def __init__(self, *args, **kwargs):
        super(PixelWall, self).__init__(*args, **kwargs)
        self.engine = QQmlApplicationEngine(self)
        self.servers = ServerModel(self.engine)
        self.settings = QSettings('OpenServices', 'PixelWall')
        url = self.settings.value('server/url')
        self.engine.setNetworkAccessManagerFactory(NetworkAccessManagerFactory('hetzner.fladi.at', 3128))
        ctxt = self.engine.rootContext()
        ctxt.setContextProperty('app', self)
        ctxt.setContextProperty('url', 'about:blank')
        self.engine.load(QUrl('states.qml'))
        discoverer = Avahi(self.engine, '_pixelwall._tcp')
        discoverer.initialized.connect(self.serverState)
        discoverer.added.connect(self.servers.addService)
        ctxt.setContextProperty('serverModel', self.servers)
        discoverer.run()
        if url:
            self.setUrl(url)
            self.setState('Web')

    def setState(self, state):
        for root in self.engine.rootObjects():
            node = root.findChild(QObject, 'main')
            if node:
                logger.info('Setting state: {}'.format(state))
                node.setProperty('state', state)

    def setUrl(self, url):
        logger.info('Connecting WebView to {}'.format(url))
        ctxt = self.engine.rootContext()
        ctxt.setContextProperty('url', 'https://www.heise.de/')

    @pyqtSlot()
    def reset(self):
        self.settings.remove('server/url')
        self.setState('Servers')

    @pyqtSlot(int)
    def serverSelected(self, index):
        server = self.servers.getIndex(index)
        logger.info('Server selected {}'.format(server))
        url = 'https://{server.host}:{server.port}/'.format(server=server)
        self.settings.setValue('server/url', url)
        self.setUrl(url)
        self.setState('Web')

    @pyqtSlot()
    def serverState(self):
        self.setState('Servers')
Esempio n. 34
0
def main():
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()
    width = 15
    height = 15
    gameManager = GameManager(width, height, 50)
    engine.rootContext().setContextProperty("gameManager", gameManager)
    engine.load('Views/Window.qml')
    window = engine.rootObjects()[0]
    window.setProperty("title", "Sapper")
    window.setProperty("width", width * 50 + 90)
    window.setProperty("height", height * 50 + 140)
    window.show()
    sys.exit(app.exec_())
Esempio n. 35
0
def main():
    import sys

    QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QGuiApplication(sys.argv)

    QFontDatabase.addApplicationFont(":/fonts/fontello.ttf")

    engine = QQmlApplicationEngine()
    engine.load(QUrl("qrc:/swipetoremove.qml"))
    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())
Esempio n. 36
0
def main():
    qmlRegisterType(PokerGamePanel, 'PokerGamePanel', 1, 0, 'PokerGamePanel')

    QtCore.qInstallMessageHandler(qt_message_handler)
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine(app)

    qml = os.path.join(os.path.dirname(__file__), 'qml/RootWindow.qml')
    engine.load(qml)
    if len(engine.rootObjects()) == 0:
        print("Loading QML Error.")
        return

    app.exec_()
Esempio n. 37
0
    def run(self):
        url = QUrl.fromLocalFile(self.get_resource("main.qml"))
        engine = QQmlApplicationEngine()

        qmlRegisterType(QActionType, "ActionType", 1, 0, "ActionType")

        engine.rootContext().setContextProperty("config", self.config)
        engine.rootContext().setContextProperty("library", self.library)
        engine.rootContext().setContextProperty("importer", self.importer)
        engine.load(url)

        if not engine.rootObjects():
            return -1

        return self.app.exec_()
Esempio n. 38
0
 def create(self, qmlUrl):
   # assert isinstance(qmlUrl, QUrl)
   engine = QQmlApplicationEngine(qmlUrl)
 
   try:
     qmlRoot = engine.rootObjects()[0]
   except:
     qWarning("Failed to read or parse qml.")
     raise
   
   print(qmlRoot)
   #assert isinstance(qmlRoot, QQuickWindow)
   return qmlRoot
 
   #super().__init__(qmlRoot)
   '''
Esempio n. 39
0
class MyApp(QObject):
    def __init__(self, qml, set_context=None):
        super().__init__()
        self.app = QApplication(sys.argv)

        self.engine = QQmlApplicationEngine(self)
        self.root_context = self.engine.rootContext()

        if set_context:
            set_context(self.root_context)

        self.engine.load(QUrl(qml))
        self.root_view = self.engine.rootObjects()[0]

    @staticmethod
    def run(my_app):
        my_app.root_view.show()
        return my_app.app.exec_()
Esempio n. 40
0
def main(argv):
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    qapp = QGuiApplication([])

    engine = QQmlApplicationEngine()

    data_list = []
    for entry in os.scandir(argv[1]):
        url = "file://" + urllib.parse.quote(os.path.abspath(entry.path))
        digest = hashlib.md5(os.fsencode(url)).hexdigest()
        result = os.path.join(xdg.BaseDirectory.xdg_cache_home, "thumbnails", "normal", digest + ".png")
        data_list.append(Foo(entry.name, result, "2018-01-11T19:20"))

    engine.load(QUrl('main.qml'))

    ctxt = engine.rootContext()
    ctxt.setContextProperty("menu2", QVariant(data_list))

    win = engine.rootObjects()[0]
    win.show()

    sys.exit(qapp.exec())
 
 appEngine = QQmlApplicationEngine()
 
 context = appEngine.rootContext()
 appEngine.addImageProvider('viewerprovider', CvImageProvider()) # Hack to make qml believe provider is valid before its creation
 appEngine.addImageProvider('trackerprovider', CvImageProvider()) # Hack to make qml believe provider is valid before its creation
 appEngine.addImageProvider('recorderprovider', CvImageProvider()) # Hack to make qml believe provider is valid before its creation
 appEngine.addImageProvider('calibrationprovider', CvImageProvider()) # Hack to make qml believe provider is valid before its creation
 
 analysisImageProvider = PyplotImageProvider(fig=None)
 appEngine.addImageProvider("analysisprovider", analysisImageProvider)
 analysisImageProvider2 = PyplotImageProvider(fig=None)
 appEngine.addImageProvider("analysisprovider2", analysisImageProvider2)
 appEngine.load(QUrl('./qml/MouseTracker.qml'))
 
 win = appEngine.rootObjects()[0]
 
 if not DEBUG:
     logger = Logger(context, win, "log")
     sys.stdout = logger
 
 # REGISTER PYTHON CLASSES WITH QML
 params = ParamsIface(app, context, win)
 viewer = ViewerIface(app, context, win, params, "preview", "viewerprovider")
 tracker = TrackerIface(app, context, win, params, "trackerDisplay", "trackerprovider", analysisImageProvider, analysisImageProvider2)
 recorder = RecorderIface(app, context, win, params, "recording", "recorderprovider", analysisImageProvider, analysisImageProvider2)
 calibrater = CalibrationIface(app, context, win, params, "calibrationDisplay", "calibrationprovider")
 
 context.setContextProperty('py_iface', params)
 context.setContextProperty('py_viewer', viewer)
 context.setContextProperty('py_tracker', tracker)
Esempio n. 42
0
class AppController(QObject):
    """The main controller of this application."""
    def __init__(self):
        super(AppController, self).__init__()
        ServiceAdaptor(self)

        self.contexts = []
        self._osdVisible = False
        self._initQuitTimer()

    def _initQuitTimer(self):
        self._quitTimer = QTimer()
        self._quitTimer.setInterval(10 * 1000)
        self._quitTimer.setSingleShot(True)
        self._quitTimer.timeout.connect(self._checkContexts)

    def _checkContexts(self):
        if (self.contexts) or self._osdVisible:
            self._quitTimer.start()
        else:
            qApp.quit()

    def _contextNeedSound(self):
        soundEffectInterface.play()

    def _contextFinished(self):
        sender = self.sender()
        if sender in self.contexts:
            # TODO: the remove _doesn't_ get the sender object
            # garbage collected, there must be some reference cycles.
            self.contexts.remove(sender)
        self._checkContexts()

    def _contextNeedOSD(self, area):
        def _osdClosed():
            self._osdVisible = False

        self._osdVisible = True
        self._qmlEngine = QQmlApplicationEngine()
        self._qmlEngine.load(QUrl(OSD_QML))
        osd = self._qmlEngine.rootObjects()[0]
        osd.setX(area.x() + (area.width() - osd.width()) / 2)
        osd.setY(area.y() + (area.height() - osd.height()) / 2)
        osd.showTips()
        osd.closed.connect(_osdClosed)

    def _createContextSettings(self):
        settings = ScreenshotSettings()
        settings.tmpImageFile = "%s.png" % tempfile.mktemp()
        settings.tmpBlurFile = "%s-blur.png" % tempfile.mktemp()
        settings.tmpMosaiceFile = "%s-mosaic.png" % tempfile.mktemp()
        settings.tmpSaveFile = "%s-save.png" % tempfile.mktemp()

        return settings


    def runWithArguments(self, arguments):
        for _context in self.contexts:
            if _context.isActive():
                return 1

        argValues = processArguments(arguments)
        delay = argValues["delay"]

        savePathValue = argValues["savePath"]

        context = AppContext(argValues)
        if savePathValue != "":
            pic_name = os.path.basename(savePathValue)
            if pic_name == "":
                return 1
            else :
                if not os.path.exists(os.path.dirname(savePathValue)):
                    return 1

        context.settings = self._createContextSettings()
        context.finished.connect(self._contextFinished)
        context.needSound.connect(self._contextNeedSound)
        context.needOSD.connect(self._contextNeedOSD)
        self.contexts.append(context)

        if delay > 0:
            notificationsInterface.notify(_("Deepin Screenshot"),
            _("Deepin Screenshot will start after %s seconds.") % delay)
            '''If run the program frequently, the QTimer sometimes do not invoke the event, so replace QTimer with SafeTimer'''
            SafeTimer.singleShot(delay, context.main)
        else:
            context.main()

        return 0
Esempio n. 43
0
class Application(QApplication):
    """Main Nuxeo Drive application controlled by a system tray icon + menu"""

    icon = QIcon(str(find_icon("app_icon.svg")))
    icons: Dict[str, QIcon] = {}
    icon_state = None
    use_light_icons = None
    filters_dlg: Optional[FiltersDialog] = None
    _delegator: Optional["NotificationDelegator"] = None
    tray_icon: DriveSystrayIcon

    def __init__(self, manager: "Manager", *args: Any) -> None:
        super().__init__(list(*args))
        self.manager = manager

        self.osi = self.manager.osi
        self.setWindowIcon(self.icon)
        self.setApplicationName(APP_NAME)
        self._init_translator()
        self.setQuitOnLastWindowClosed(False)

        self.ask_for_metrics_approval()

        self._conflicts_modals: Dict[str, bool] = dict()
        self.current_notification: Optional[Notification] = None
        self.default_tooltip = APP_NAME

        font = QFont("Helvetica, Arial, sans-serif", 12)
        self.setFont(font)
        self.ratio = sqrt(QFontMetricsF(font).height() / 12)

        self.init_gui()

        self.manager.dropEngine.connect(self.dropped_engine)

        self.setup_systray()
        self.manager.reloadIconsSet.connect(self.load_icons_set)

        # Direct Edit
        self.manager.direct_edit.directEditConflict.connect(self._direct_edit_conflict)
        self.manager.direct_edit.directEditError.connect(self._direct_edit_error)

        # Check if actions is required, separate method so it can be overridden
        self.init_checks()

        # Setup notification center for macOS
        if MAC:
            self._setup_notification_center()

        # Application update
        self.manager.updater.appUpdated.connect(self.quit)
        self.manager.updater.serverIncompatible.connect(self._server_incompatible)
        self.manager.updater.wrongChannel.connect(self._wrong_channel)

        # Display release notes on new version
        if self.manager.old_version != self.manager.version:
            self.show_release_notes(self.manager.version)

        # Listen for nxdrive:// sent by a new instance
        self.init_nxdrive_listener()

        # Connect this slot last so the other slots connected
        # to self.aboutToQuit can run beforehand.
        self.aboutToQuit.connect(self.manager.stop)

    @if_frozen
    def add_qml_import_path(self, view: QQuickView) -> None:
        """
        Manually set the path to the QML folder to fix errors with unicode paths.
        This is needed only on Windows when packaged with Nuitka.
        """
        if Options.freezer != "nuitka":
            return

        qml_dir = Options.res_dir.parent / "PyQt5" / "Qt" / "qml"
        log.debug(f"Setting QML import path for {view} to {qml_dir!r}")
        view.engine().addImportPath(str(qml_dir))

    def init_gui(self) -> None:

        self.api = QMLDriveApi(self)
        self.conflicts_model = FileModel()
        self.errors_model = FileModel()
        self.engine_model = EngineModel(self)
        self.action_model = ActionModel()
        self.file_model = FileModel()
        self.ignoreds_model = FileModel()
        self.language_model = LanguageModel()

        self.add_engines(list(self.manager._engines.values()))
        self.engine_model.statusChanged.connect(self.update_status)
        self.language_model.addLanguages(Translator.languages())

        flags = Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint

        if WINDOWS:
            self.conflicts_window = QQuickView()
            self.add_qml_import_path(self.conflicts_window)
            self.conflicts_window.setMinimumWidth(550)
            self.conflicts_window.setMinimumHeight(600)
            self.settings_window = QQuickView()
            self.add_qml_import_path(self.settings_window)
            self.settings_window.setMinimumWidth(640)
            self.settings_window.setMinimumHeight(520)
            self.systray_window = SystrayWindow()
            self.add_qml_import_path(self.systray_window)

            self._fill_qml_context(self.conflicts_window.rootContext())
            self._fill_qml_context(self.settings_window.rootContext())
            self._fill_qml_context(self.systray_window.rootContext())
            self.systray_window.rootContext().setContextProperty(
                "systrayWindow", self.systray_window
            )

            self.conflicts_window.setSource(
                QUrl.fromLocalFile(str(find_resource("qml", "Conflicts.qml")))
            )
            self.settings_window.setSource(
                QUrl.fromLocalFile(str(find_resource("qml", "Settings.qml")))
            )
            self.systray_window.setSource(
                QUrl.fromLocalFile(str(find_resource("qml", "Systray.qml")))
            )
            flags |= Qt.Popup
        else:
            self.app_engine = QQmlApplicationEngine()
            self._fill_qml_context(self.app_engine.rootContext())
            self.app_engine.load(
                QUrl.fromLocalFile(str(find_resource("qml", "Main.qml")))
            )
            root = self.app_engine.rootObjects()[0]
            self.conflicts_window = root.findChild(QQuickWindow, "conflictsWindow")
            self.settings_window = root.findChild(QQuickWindow, "settingsWindow")
            self.systray_window = root.findChild(SystrayWindow, "systrayWindow")
            if LINUX:
                flags |= Qt.Drawer

        self.systray_window.setFlags(flags)

        self.manager.newEngine.connect(self.add_engines)
        self.manager.initEngine.connect(self.add_engines)
        self.manager.dropEngine.connect(self.remove_engine)
        self._window_root(self.conflicts_window).changed.connect(self.refresh_conflicts)
        self._window_root(self.systray_window).appUpdate.connect(self.api.app_update)
        self._window_root(self.systray_window).getLastFiles.connect(self.get_last_files)
        self.api.setMessage.connect(self._window_root(self.settings_window).setMessage)

        if self.manager.get_engines():
            current_uid = self.engine_model.engines_uid[0]
            self.get_last_files(current_uid)
            self.update_status(self.manager._engines[current_uid])

        self.manager.updater.updateAvailable.connect(
            self._window_root(self.systray_window).updateAvailable
        )
        self.manager.updater.updateProgress.connect(
            self._window_root(self.systray_window).updateProgress
        )

    @pyqtSlot(Action)
    def action_started(self, action: Action) -> None:
        self.refresh_actions()

    @pyqtSlot(Action)
    def action_progressing(self, action: Action) -> None:
        self.action_model.set_progress(action.export())

    @pyqtSlot(Action)
    def action_done(self, action: Action) -> None:
        self.refresh_actions()

    def add_engines(self, engines: Union[Engine, List[Engine]]) -> None:
        if not engines:
            return

        engines = engines if isinstance(engines, list) else [engines]
        for engine in engines:
            self.engine_model.addEngine(engine.uid)

    def remove_engine(self, uid: str) -> None:
        self.engine_model.removeEngine(uid)

    def _fill_qml_context(self, context: QQmlContext) -> None:
        """ Fill the context of a QML element with the necessary resources. """
        context.setContextProperty("ConflictsModel", self.conflicts_model)
        context.setContextProperty("ErrorsModel", self.errors_model)
        context.setContextProperty("EngineModel", self.engine_model)
        context.setContextProperty("ActionModel", self.action_model)
        context.setContextProperty("FileModel", self.file_model)
        context.setContextProperty("IgnoredsModel", self.ignoreds_model)
        context.setContextProperty("languageModel", self.language_model)
        context.setContextProperty("api", self.api)
        context.setContextProperty("application", self)
        context.setContextProperty("currentLanguage", self.current_language())
        context.setContextProperty("manager", self.manager)
        context.setContextProperty("osi", self.osi)
        context.setContextProperty("updater", self.manager.updater)
        context.setContextProperty("ratio", self.ratio)
        context.setContextProperty("update_check_delay", Options.update_check_delay)
        context.setContextProperty("isFrozen", Options.is_frozen)
        context.setContextProperty("WINDOWS", WINDOWS)
        context.setContextProperty("tl", Translator._singleton)
        context.setContextProperty(
            "nuxeoVersionText", f"{APP_NAME} {self.manager.version}"
        )
        metrics = self.manager.get_metrics()
        versions = (
            f'Python {metrics["python_version"]}, '
            f'Qt {metrics["qt_version"]}, '
            f'SIP {metrics["sip_version"]}'
        )
        if Options.system_wide:
            versions += " [admin]"
        context.setContextProperty("modulesVersionText", versions)

        colors = {
            "darkBlue": "#1F28BF",
            "nuxeoBlue": "#0066FF",
            "lightBlue": "#00ADED",
            "teal": "#73D2CF",
            "purple": "#8400FF",
            "red": "#C02828",
            "orange": "#FF9E00",
            "darkGray": "#495055",
            "mediumGray": "#7F8284",
            "lightGray": "#BCBFBF",
            "lighterGray": "#F5F5F5",
        }

        for name, value in colors.items():
            context.setContextProperty(name, value)

    def _window_root(self, window):
        if WINDOWS:
            return window.rootObject()
        return window

    def translate(self, message: str, values: List[Any] = None) -> str:
        return Translator.get(message, values)

    def _show_window(self, window: QWindow) -> None:
        window.show()
        window.raise_()
        window.requestActivate()

    def _init_translator(self) -> None:
        locale = Options.force_locale or Options.locale
        Translator(find_resource("i18n"), self.manager.get_config("locale", locale))
        # Make sure that a language change changes external values like
        # the text in the contextual menu
        Translator.on_change(self._handle_language_change)
        # Trigger it now
        self.osi.register_contextual_menu()
        self.installTranslator(Translator._singleton)

    @pyqtSlot(str, Path, str)
    def _direct_edit_conflict(self, filename: str, ref: Path, digest: str) -> None:
        log.debug(f"Entering _direct_edit_conflict for {filename!r} / {ref!r}")
        try:
            if filename in self._conflicts_modals:
                log.debug(f"Filename already in _conflicts_modals: {filename!r}")
                return
            log.debug(f"Putting filename in _conflicts_modals: {filename!r}")
            self._conflicts_modals[filename] = True

            msg = QMessageBox()
            msg.setInformativeText(
                Translator.get("DIRECT_EDIT_CONFLICT_MESSAGE", [short_name(filename)])
            )
            overwrite = msg.addButton(
                Translator.get("DIRECT_EDIT_CONFLICT_OVERWRITE"), QMessageBox.AcceptRole
            )
            msg.addButton(Translator.get("CANCEL"), QMessageBox.RejectRole)
            msg.setIcon(QMessageBox.Warning)
            msg.exec_()
            if msg.clickedButton() == overwrite:
                self.manager.direct_edit.force_update(ref, digest)
            del self._conflicts_modals[filename]
        except:
            log.exception(
                f"Error while displaying Direct Edit conflict modal dialog for {filename!r}"
            )

    @pyqtSlot(str, list)
    def _direct_edit_error(self, message: str, values: List[str]) -> None:
        """ Display a simple Direct Edit error message. """
        msg_text = self.translate(message, values)
        log.warning(f"DirectEdit error message: '{msg_text}', values={values}")
        msg = QMessageBox()
        msg.setWindowTitle(f"Direct Edit - {APP_NAME}")
        msg.setWindowIcon(self.icon)
        msg.setIcon(QMessageBox.Warning)
        msg.setTextFormat(Qt.RichText)
        msg.setText(msg_text)
        msg.exec_()

    @pyqtSlot()
    def _root_deleted(self) -> None:
        engine = self.sender()
        log.info(f"Root has been deleted for engine: {engine.uid}")

        msg = QMessageBox()
        msg.setIcon(QMessageBox.Critical)
        msg.setWindowIcon(self.icon)
        msg.setText(Translator.get("DRIVE_ROOT_DELETED", [engine.local_folder]))
        recreate = msg.addButton(
            Translator.get("DRIVE_ROOT_RECREATE"), QMessageBox.AcceptRole
        )
        disconnect = msg.addButton(
            Translator.get("DRIVE_ROOT_DISCONNECT"), QMessageBox.RejectRole
        )

        msg.exec_()
        res = msg.clickedButton()
        if res == disconnect:
            self.manager.unbind_engine(engine.uid)
        elif res == recreate:
            engine.reinit()
            engine.start()

    @pyqtSlot()
    def _no_space_left(self) -> None:
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Warning)
        msg.setWindowIcon(self.icon)
        msg.setText(Translator.get("NO_SPACE_LEFT_ON_DEVICE"))
        msg.addButton(Translator.get("OK"), QMessageBox.AcceptRole)
        msg.exec_()

    @pyqtSlot(Path)
    def _root_moved(self, new_path: Path) -> None:
        engine = self.sender()
        log.info(f"Root has been moved for engine: {engine.uid} to {new_path!r}")
        info = [engine.local_folder, str(new_path)]

        msg = QMessageBox()
        msg.setIcon(QMessageBox.Critical)
        msg.setWindowIcon(self.icon)
        msg.setText(Translator.get("DRIVE_ROOT_MOVED", info))
        move = msg.addButton(
            Translator.get("DRIVE_ROOT_UPDATE"), QMessageBox.AcceptRole
        )
        recreate = msg.addButton(
            Translator.get("DRIVE_ROOT_RECREATE"), QMessageBox.AcceptRole
        )
        disconnect = msg.addButton(
            Translator.get("DRIVE_ROOT_DISCONNECT"), QMessageBox.RejectRole
        )
        msg.exec_()
        res = msg.clickedButton()

        if res == disconnect:
            self.manager.unbind_engine(engine.uid)
        elif res == recreate:
            engine.reinit()
            engine.start()
        elif res == move:
            engine.set_local_folder(new_path)
            engine.start()

    def confirm_deletion(self, path: Path) -> DelAction:
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Question)
        msg.setWindowIcon(self.icon)

        cb = QCheckBox(Translator.get("DONT_ASK_AGAIN"))
        msg.setCheckBox(cb)

        mode = self.manager.get_deletion_behavior()
        unsync = None
        if mode is DelAction.DEL_SERVER:
            descr = "DELETION_BEHAVIOR_CONFIRM_DELETE"
            confirm_text = "DELETE_FOR_EVERYONE"
            unsync = msg.addButton(
                Translator.get("JUST_UNSYNC"), QMessageBox.RejectRole
            )
        elif mode is DelAction.UNSYNC:
            descr = "DELETION_BEHAVIOR_CONFIRM_UNSYNC"
            confirm_text = "UNSYNC"

        msg.setText(
            Translator.get(descr, [str(path), Translator.get("SELECT_SYNC_FOLDERS")])
        )
        msg.addButton(Translator.get("CANCEL"), QMessageBox.RejectRole)
        confirm = msg.addButton(Translator.get(confirm_text), QMessageBox.AcceptRole)
        msg.exec_()

        res = msg.clickedButton()
        if cb.isChecked():
            self.manager._dao.store_bool("show_deletion_prompt", False)

        if res == confirm:
            return mode
        if res == unsync:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Question)
            msg.setWindowIcon(self.icon)
            msg.setText(Translator.get("DELETION_BEHAVIOR_SWITCH"))
            msg.addButton(Translator.get("NO"), QMessageBox.RejectRole)
            confirm = msg.addButton(Translator.get("YES"), QMessageBox.AcceptRole)
            msg.exec_()
            res = msg.clickedButton()
            if res == confirm:
                self.manager.set_deletion_behavior(DelAction.UNSYNC)
            return DelAction.UNSYNC
        return DelAction.ROLLBACK

    @pyqtSlot(Path)
    def _doc_deleted(self, path: Path) -> None:
        engine: Engine = self.sender()
        mode = self.confirm_deletion(path)

        if mode is DelAction.ROLLBACK:
            # Re-sync the document
            engine.rollback_delete(path)
        else:
            # Delete or filter out the document
            engine.delete_doc(path, mode)

    @pyqtSlot(Path, Path)
    def _file_already_exists(self, oldpath: Path, newpath: Path) -> None:
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Critical)
        msg.setWindowIcon(self.icon)
        msg.setText(Translator.get("FILE_ALREADY_EXISTS", values=[str(oldpath)]))
        replace = msg.addButton(Translator.get("REPLACE"), QMessageBox.AcceptRole)
        msg.addButton(Translator.get("CANCEL"), QMessageBox.RejectRole)
        msg.exec_()
        if msg.clickedButton() == replace:
            oldpath.unlink()
            normalize_event_filename(newpath)
        else:
            newpath.unlink()

    @pyqtSlot(object)
    def dropped_engine(self, engine: "Engine") -> None:
        # Update icon in case the engine dropped was syncing
        self.change_systray_icon()

    @pyqtSlot()
    def change_systray_icon(self) -> None:
        # Update status has the precedence over other ones
        if self.manager.updater.status not in (
            UPDATE_STATUS_UNAVAILABLE_SITE,
            UPDATE_STATUS_UP_TO_DATE,
        ):
            self.set_icon_state("update")
            return

        syncing = conflict = False
        engines = self.manager.get_engines()
        invalid_credentials = paused = offline = True

        for engine in engines.values():
            syncing |= engine.is_syncing()
            invalid_credentials &= engine.has_invalid_credentials()
            paused &= engine.is_paused()
            offline &= engine.is_offline()
            conflict |= bool(engine.get_conflicts())

        if offline:
            new_state = "error"
            Action(Translator.get("OFFLINE"))
        elif invalid_credentials:
            new_state = "error"
            Action(Translator.get("AUTH_EXPIRED"))
        elif not engines:
            new_state = "disabled"
            Action.finish_action()
        elif paused:
            new_state = "paused"
            Action.finish_action()
        elif syncing:
            new_state = "syncing"
        elif conflict:
            new_state = "conflict"
        else:
            new_state = "idle"
            Action.finish_action()

        self.set_icon_state(new_state)

    def refresh_conflicts(self, uid: str) -> None:
        """ Update the content of the conflicts/errors window. """
        self.conflicts_model.empty()
        self.errors_model.empty()
        self.ignoreds_model.empty()

        self.conflicts_model.addFiles(self.api.get_conflicts(uid))
        self.errors_model.addFiles(self.api.get_errors(uid))
        self.ignoreds_model.addFiles(self.api.get_unsynchronizeds(uid))

    @pyqtSlot()
    def show_conflicts_resolution(self, engine: "Engine") -> None:
        """ Display the conflicts/errors window. """
        self.refresh_conflicts(engine.uid)
        self._window_root(self.conflicts_window).setEngine.emit(engine.uid)
        self.conflicts_window.show()
        self.conflicts_window.requestActivate()

    @pyqtSlot()
    def show_settings(self, section: str = "General") -> None:
        sections = {"General": 0, "Accounts": 1, "About": 2}
        self._window_root(self.settings_window).setSection.emit(sections[section])
        self.settings_window.show()
        self.settings_window.requestActivate()

    @pyqtSlot()
    def show_systray(self) -> None:
        icon = self.tray_icon.geometry()

        if not icon or icon.isEmpty():
            # On Ubuntu it's likely we can't retrieve the geometry.
            # We're simply displaying the systray in the top right corner.
            screen = self.desktop().screenGeometry()
            pos_x = screen.right() - self.systray_window.width() - 20
            pos_y = 30
        else:
            dpi_ratio = self.primaryScreen().devicePixelRatio() if WINDOWS else 1
            pos_x = max(
                0, (icon.x() + icon.width()) / dpi_ratio - self.systray_window.width()
            )
            pos_y = icon.y() / dpi_ratio - self.systray_window.height()
            if pos_y < 0:
                pos_y = (icon.y() + icon.height()) / dpi_ratio

        self.systray_window.setX(pos_x)
        self.systray_window.setY(pos_y)

        self.systray_window.show()
        self.systray_window.raise_()

    @pyqtSlot()
    def hide_systray(self):
        self.systray_window.hide()

    @pyqtSlot()
    def open_help(self) -> None:
        self.manager.open_help()

    @pyqtSlot()
    def destroyed_filters_dialog(self) -> None:
        self.filters_dlg = None

    @pyqtSlot()
    def show_filters(self, engine: "Engine") -> None:
        if self.filters_dlg:
            self.filters_dlg.close()
            self.filters_dlg = None

        self.filters_dlg = FiltersDialog(self, engine)
        self.filters_dlg.destroyed.connect(self.destroyed_filters_dialog)

        # Close the settings window at the same time of the filters one
        if hasattr(self, "close_settings_too"):
            self.filters_dlg.destroyed.connect(self.settings_window.close)
            delattr(self, "close_settings_too")

        self.filters_dlg.show()
        self._show_window(self.settings_window)

    @pyqtSlot(str, object)
    def _open_authentication_dialog(
        self, url: str, callback_params: Dict[str, str]
    ) -> None:
        self.api._callback_params = callback_params
        if Options.is_frozen:
            """
            Authenticate through the browser.

            This authentication requires the server's Nuxeo Drive addon to include
            NXP-25519. Instead of opening the server's login page in a WebKit view
            through the app, it opens in the browser and retrieves the login token
            by opening an nxdrive:// URL.
            """
            self.manager.open_local_file(url)
        else:
            self._web_auth_not_frozen(url)

    def _web_auth_not_frozen(self, url: str) -> None:
        """
        Open a dialog box to fill the credentials.
        Then a request will be done using the Python client to
        get a token.

        This is used when the application is not frozen as there is no custom
        protocol handler in this case.
        """

        from PyQt5.QtWidgets import QLineEdit
        from nuxeo.client import Nuxeo

        dialog = QDialog()
        dialog.setWindowTitle(self.translate("WEB_AUTHENTICATION_WINDOW_TITLE"))
        dialog.setWindowIcon(self.icon)
        dialog.resize(250, 100)

        layout = QVBoxLayout()

        username = QLineEdit("Administrator", parent=dialog)
        password = QLineEdit("Administrator", parent=dialog)
        password.setEchoMode(QLineEdit.Password)
        layout.addWidget(username)
        layout.addWidget(password)

        def auth() -> None:
            """Retrieve a token and create the account."""
            user = str(username.text())
            pwd = str(password.text())
            nuxeo = Nuxeo(
                host=url,
                auth=(user, pwd),
                proxies=self.manager.proxy.settings(url=url),
                verify=Options.ca_bundle or not Options.ssl_no_verify,
            )
            try:
                token = nuxeo.client.request_auth_token(
                    device_id=self.manager.device_id,
                    app_name=APP_NAME,
                    permission=TOKEN_PERMISSION,
                    device=get_device(),
                )
            except Exception as exc:
                log.error(f"Connection error: {exc}")
                token = ""
            finally:
                del nuxeo

            # Check we have a token and not a HTML response
            if "\n" in token:
                token = ""

            self.api.handle_token(token, user)
            dialog.close()

        buttons = QDialogButtonBox()
        buttons.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
        buttons.accepted.connect(auth)
        buttons.rejected.connect(dialog.close)
        layout.addWidget(buttons)

        dialog.setLayout(layout)
        dialog.exec_()

    @pyqtSlot(object)
    def _connect_engine(self, engine: "Engine") -> None:
        engine.syncStarted.connect(self.change_systray_icon)
        engine.syncCompleted.connect(self.change_systray_icon)
        engine.invalidAuthentication.connect(self.change_systray_icon)
        engine.syncSuspended.connect(self.change_systray_icon)
        engine.syncResumed.connect(self.change_systray_icon)
        engine.offline.connect(self.change_systray_icon)
        engine.online.connect(self.change_systray_icon)
        engine.rootDeleted.connect(self._root_deleted)
        engine.rootMoved.connect(self._root_moved)
        engine.docDeleted.connect(self._doc_deleted)
        engine.fileAlreadyExists.connect(self._file_already_exists)
        engine.noSpaceLeftOnDevice.connect(self._no_space_left)
        self.change_systray_icon()

    def init_checks(self) -> None:
        for engine in self.manager.get_engines().values():
            self._connect_engine(engine)

        self.manager.newEngine.connect(self._connect_engine)
        self.manager.notification_service.newNotification.connect(
            self._new_notification
        )
        self.manager.notification_service.triggerNotification.connect(
            self._handle_notification_action
        )
        self.manager.updater.updateAvailable.connect(self._update_notification)
        self.manager.updater.noSpaceLeftOnDevice.connect(self._no_space_left)

        if not self.manager.get_engines():
            self.show_settings()
        else:
            for engine in self.manager.get_engines().values():
                # Prompt for settings if needed
                if engine.has_invalid_credentials():
                    self.show_settings("Accounts")  # f"Account_{engine.uid}"
                    break

        self.manager.start()

    @pyqtSlot()
    @if_frozen
    def _update_notification(self) -> None:
        self.change_systray_icon()

        # Display a notification
        status, version = self.manager.updater.status, self.manager.updater.version

        msg = ("AUTOUPDATE_UPGRADE", "AUTOUPDATE_DOWNGRADE")[
            status == UPDATE_STATUS_INCOMPATIBLE_SERVER
        ]
        description = Translator.get(msg, [version])
        flags = Notification.FLAG_BUBBLE | Notification.FLAG_UNIQUE
        if LINUX:
            description += " " + Translator.get("AUTOUPDATE_MANUAL")
            flags |= Notification.FLAG_SYSTRAY

        log.warning(description)
        notification = Notification(
            uuid="AutoUpdate",
            flags=flags,
            title=Translator.get("NOTIF_UPDATE_TITLE", [version]),
            description=description,
        )
        self.manager.notification_service.send_notification(notification)

    @pyqtSlot()
    def _server_incompatible(self) -> None:
        version = self.manager.version
        downgrade_version = self.manager.updater.version or ""
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Warning)
        msg.setWindowIcon(self.icon)
        msg.setText(Translator.get("SERVER_INCOMPATIBLE", [version, downgrade_version]))
        if downgrade_version:
            msg.addButton(
                Translator.get("CONTINUE_USING", [version]), QMessageBox.RejectRole
            )
            downgrade = msg.addButton(
                Translator.get("DOWNGRADE_TO", [downgrade_version]),
                QMessageBox.AcceptRole,
            )
        else:
            msg.addButton(Translator.get("CONTINUE"), QMessageBox.RejectRole)
        msg.exec_()

        res = msg.clickedButton()
        if downgrade_version and res == downgrade:
            self.manager.updater.update(downgrade_version)

    @pyqtSlot()
    def _wrong_channel(self) -> None:
        if self.manager.prompted_wrong_channel:
            log.debug(
                "Not prompting for wrong channel, already showed it since startup"
            )
            return
        self.manager.prompted_wrong_channel = True

        version = self.manager.version
        downgrade_version = self.manager.updater.version or ""
        version_channel = self.manager.updater.get_version_channel(version)
        current_channel = self.manager.get_update_channel()
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Warning)
        msg.setWindowIcon(self.icon)
        msg.setText(
            Translator.get("WRONG_CHANNEL", [version, version_channel, current_channel])
        )
        switch_channel = msg.addButton(
            Translator.get("USE_CHANNEL", [version_channel]), QMessageBox.AcceptRole
        )
        downgrade = msg.addButton(
            Translator.get("DOWNGRADE_TO", [downgrade_version]), QMessageBox.AcceptRole
        )
        msg.exec_()

        res = msg.clickedButton()
        if downgrade_version and res == downgrade:
            self.manager.updater.update(downgrade_version)
        elif res == switch_channel:
            self.manager.set_update_channel(version_channel)

    @pyqtSlot()
    def message_clicked(self) -> None:
        if self.current_notification:
            self.manager.notification_service.trigger_notification(
                self.current_notification.uid
            )

    def _setup_notification_center(self) -> None:
        if not self._delegator:
            self._delegator = NotificationDelegator.alloc().init()
            if self._delegator:
                self._delegator._manager = self.manager
        setup_delegator(self._delegator)

    @pyqtSlot(object)
    def _new_notification(self, notif: Notification) -> None:
        if not notif.is_bubble():
            return

        if self._delegator is not None:
            # Use notification center
            from ..osi.darwin.pyNotificationCenter import notify

            user_info = {"uuid": notif.uid} if notif.uid else None

            return notify(notif.title, "", notif.description, user_info=user_info)

        icon = QSystemTrayIcon.Information
        if notif.level == Notification.LEVEL_WARNING:
            icon = QSystemTrayIcon.Warning
        elif notif.level == Notification.LEVEL_ERROR:
            icon = QSystemTrayIcon.Critical

        self.current_notification = notif
        self.tray_icon.showMessage(notif.title, notif.description, icon, 10000)

    @pyqtSlot(str, str)
    def _handle_notification_action(self, action: str, engine_uid: str) -> None:
        func = getattr(self.api, action, None)
        if not func:
            log.error(f"Action {action}() is not defined in {self.api}")
            return
        func(engine_uid)

    def set_icon_state(self, state: str, force: bool = False) -> bool:
        """
        Execute systray icon change operations triggered by state change.

        The synchronization thread can update the state info but cannot
        directly call QtGui widget methods. This should be executed by the main
        thread event loop, hence the delegation to this method that is
        triggered by a signal to allow for message passing between the 2
        threads.

        Return True of the icon has changed state or if force is True.
        """

        if not force and self.icon_state == state:
            # Nothing to update
            return False

        self.tray_icon.setToolTip(self.get_tooltip())
        self.tray_icon.setIcon(self.icons[state])
        self.icon_state = state
        return True

    def get_tooltip(self) -> str:
        actions = Action.get_actions()
        if not actions:
            return self.default_tooltip

        # Display only the first action for now
        for action in actions.values():
            if action and action.type and not action.type.startswith("_"):
                break
        else:
            return self.default_tooltip

        return f"{self.default_tooltip} - {action!r}"

    @if_frozen
    def show_release_notes(self, version: str) -> None:
        """ Display release notes of a given version. """

        channel = self.manager.get_update_channel()
        log.info(f"Showing release notes, version={version!r} channel={channel}")

        # For now, we do care about beta only
        if channel != "beta":
            return

        url = (
            "https://api.github.com/repos/nuxeo/nuxeo-drive"
            f"/releases/tags/release-{version}"
        )

        if channel != "release":
            version += f" {channel}"

        try:
            # No need for the `verify` kwarg here as GitHub will never use a bad certificate.
            with requests.get(url) as resp:
                data = resp.json()
                html = markdown(data["body"])
        except Exception:
            log.warning(f"[{version}] Release notes retrieval error")
            return

        dialog = QDialog()
        dialog.setWindowTitle(f"{APP_NAME} {version} - Release notes")
        dialog.setWindowIcon(self.icon)

        dialog.resize(600, 400)

        notes = QTextEdit()
        notes.setStyleSheet("background-color: #eee; border: none;")
        notes.setReadOnly(True)
        notes.setHtml(html)

        buttons = QDialogButtonBox()
        buttons.setStandardButtons(QDialogButtonBox.Ok)
        buttons.clicked.connect(dialog.accept)

        layout = QVBoxLayout()
        layout.addWidget(notes)
        layout.addWidget(buttons)
        dialog.setLayout(layout)
        dialog.exec_()

    def accept_unofficial_ssl_cert(self, hostname: str) -> bool:
        """Ask the user to bypass the SSL certificate verification."""
        from ..utils import get_certificate_details

        def signature(sig: str) -> str:
            """
            Format the certificate signature.

                >>> signature("0F4019D1E6C52EF9A3A929B6D5613816")
                0f:40:19:d1:e6:c5:2e:f9:a3:a9:29:b6:d5:61:38:16

            """
            from textwrap import wrap

            return str.lower(":".join(wrap(sig, 2)))

        cert = get_certificate_details(hostname=hostname)
        if not cert:
            return False

        subject = [
            f"<li>{details[0][0]}: {details[0][1]}</li>"
            for details in sorted(cert["subject"])
        ]
        issuer = [
            f"<li>{details[0][0]}: {details[0][1]}</li>"
            for details in sorted(cert["issuer"])
        ]
        urls = [
            f"<li><a href='{details}'>{details}</a></li>"
            for details in cert["caIssuers"]
        ]
        sig = f"<code><small>{signature(cert['serialNumber'])}</small></code>"
        message = f"""
<h2>{Translator.get("SSL_CANNOT_CONNECT", [hostname])}</h2>
<p style="color:red">{Translator.get("SSL_HOSTNAME_ERROR")}</p>

<h2>{Translator.get("SSL_CERTIFICATE")}</h2>
<ul>
    {"".join(subject)}
    <li style="margin-top: 10px;">{Translator.get("SSL_SERIAL_NUMBER")} {sig}</li>
    <li style="margin-top: 10px;">{Translator.get("SSL_DATE_FROM")} {cert["notBefore"]}</li>
    <li>{Translator.get("SSL_DATE_EXPIRATION")} {cert["notAfter"]}</li>
</ul>

<h2>{Translator.get("SSL_ISSUER")}</h2>
<ul style="list-style-type:square;">{"".join(issuer)}</ul>

<h2>{Translator.get("URL")}</h2>
<ul>{"".join(urls)}</ul>
"""

        dialog = QDialog()
        dialog.setWindowTitle(Translator.get("SSL_UNTRUSTED_CERT_TITLE"))
        dialog.setWindowIcon(self.icon)
        dialog.resize(600, 650)

        notes = QTextEdit()
        notes.setReadOnly(True)
        notes.setHtml(message)

        continue_with_bad_ssl_cert = False

        def accept() -> None:
            nonlocal continue_with_bad_ssl_cert
            continue_with_bad_ssl_cert = True
            dialog.accept()

        buttons = QDialogButtonBox()
        buttons.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttons.button(QDialogButtonBox.Ok).setEnabled(False)
        buttons.accepted.connect(accept)
        buttons.rejected.connect(dialog.close)

        def bypass_triggered(state: int) -> None:
            """Enable the OK button only when the checkbox is checked."""
            buttons.button(QDialogButtonBox.Ok).setEnabled(bool(state))

        bypass = QCheckBox(Translator.get("SSL_TRUST_ANYWAY"))
        bypass.stateChanged.connect(bypass_triggered)

        layout = QVBoxLayout()
        layout.addWidget(notes)
        layout.addWidget(bypass)
        layout.addWidget(buttons)
        dialog.setLayout(layout)
        dialog.exec_()

        return continue_with_bad_ssl_cert

    def show_metadata(self, path: Path) -> None:
        self.manager.ctx_edit_metadata(path)

    @pyqtSlot(bool)
    def load_icons_set(self, use_light_icons: bool = False) -> None:
        """Load a given icons set (either the default one "dark", or the light one)."""
        if self.use_light_icons is use_light_icons:
            return

        suffix = ("", "_light")[use_light_icons]
        mask = str(find_icon("active.svg"))  # Icon mask for macOS
        for state in {
            "conflict",
            "disabled",
            "error",
            "idle",
            "notification",
            "paused",
            "syncing",
            "update",
        }:
            icon = QIcon()
            icon.addFile(str(find_icon(f"{state}{suffix}.svg")))
            if MAC:
                icon.addFile(mask, mode=QIcon.Selected)
            self.icons[state] = icon

        self.use_light_icons = use_light_icons
        self.manager.set_config("light_icons", use_light_icons)

        # Reload the current showed icon
        if self.icon_state:
            self.set_icon_state(self.icon_state, force=True)

    def initial_icons_set(self) -> bool:
        """
        Try to guess the most appropriate icons set at start.
        The user will still have the possibility to change that in Settings.
        """
        use_light_icons = self.manager.get_config("light_icons", default=None)

        if use_light_icons is None:
            # Default value for GNU/Linux, macOS ans Windows 7
            use_light_icons = False

            if WINDOWS:
                win_ver = sys.getwindowsversion()
                version = (win_ver.major, win_ver.minor)
                if version > (6, 1):  # Windows 7
                    # Windows 8+ has a dark them by default
                    use_light_icons = True
        else:
            # The value stored in DTB as a string '0' or '1', convert to boolean
            use_light_icons = bool(int(use_light_icons))

        return use_light_icons

    def setup_systray(self) -> None:
        """Setup the icon system tray and its associated menu."""
        self.load_icons_set(use_light_icons=self.initial_icons_set())

        self.tray_icon = DriveSystrayIcon(self)
        if not self.tray_icon.isSystemTrayAvailable():
            log.critical("There is no system tray available!")
        else:
            self.tray_icon.setToolTip(APP_NAME)
            self.set_icon_state("disabled")
            self.tray_icon.show()

    def _handle_language_change(self) -> None:
        self.manager.set_config("locale", Translator.locale())
        if not MAC:
            self.tray_icon.setContextMenu(self.tray_icon.get_context_menu())
        self.osi.register_contextual_menu()

    def event(self, event: QEvent) -> bool:
        """ Handle URL scheme events under macOS. """
        url = getattr(event, "url", None)
        if not url:
            # This is not an event for us!
            return super().event(event)

        final_url = unquote(event.url().toString())
        try:
            return self._handle_nxdrive_url(final_url)
        except:
            log.exception(f"Error handling URL event {final_url!r}")
            return False

    def _show_msgbox_restart_needed(self) -> None:
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setText(Translator.get("RESTART_NEEDED_MSG", values=[APP_NAME]))
        msg.setWindowTitle(APP_NAME)
        msg.addButton(Translator.get("OK"), QMessageBox.AcceptRole)
        msg.exec_()

    def _handle_nxdrive_url(self, url: str) -> bool:
        """ Handle an nxdrive protocol URL. """

        info = parse_protocol_url(url)
        if not info:
            return False

        cmd = info["command"]
        path = normalized_path(info.get("filepath", ""))
        manager = self.manager

        log.info(f"Event URL={url}, info={info!r}")

        # Event fired by a context menu item
        func = {
            "access-online": manager.ctx_access_online,
            "copy-share-link": manager.ctx_copy_share_link,
            "edit-metadata": manager.ctx_edit_metadata,
        }.get(cmd, None)
        if func:
            func(path)
        elif "edit" in cmd:
            if self.manager.restart_needed:
                self._show_msgbox_restart_needed()
                return False

            manager.direct_edit.edit(
                info["server_url"],
                info["doc_id"],
                user=info["user"],
                download_url=info["download_url"],
            )
        elif cmd == "token":
            self.api.handle_token(info["token"], info["username"])
        else:
            log.warning(f"Unknown event URL={url}, info={info!r}")
            return False
        return True

    def init_nxdrive_listener(self) -> None:
        """
        Set up a QLocalServer to listen to nxdrive protocol calls.

        On Windows, when an nxdrive:// URL is opened, it creates a new
        instance of Nuxeo Drive. As we want the already running instance to
        receive this call (particularly during the login process), we set
        up a QLocalServer in that instance to listen to the new ones who will
        send their data.
        The Qt implementation of QLocalSocket on Windows makes use of named
        pipes. We just need to connect a handler to the newConnection signal
        to process the URLs.
        """
        named_pipe = f"{BUNDLE_IDENTIFIER}.protocol.{os.getpid()}"
        server = QLocalServer()
        server.setSocketOptions(QLocalServer.WorldAccessOption)
        server.newConnection.connect(self._handle_connection)
        try:
            server.listen(named_pipe)
            log.info(f"Listening for nxdrive:// calls on {server.fullServerName()}")
        except:
            log.info(
                f"Unable to start local server on {named_pipe}: {server.errorString()}"
            )

        self._nxdrive_listener = server
        self.aboutToQuit.connect(self._nxdrive_listener.close)

    def _handle_connection(self) -> None:
        """ Retrieve the connection with other instances and handle the incoming data. """

        con: QLocalSocket = None
        try:
            con = self._nxdrive_listener.nextPendingConnection()
            log.info("Receiving socket connection for nxdrive protocol handling")
            if not con or not con.waitForConnected():
                log.error(f"Unable to open server socket: {con.errorString()}")
                return

            if con.waitForReadyRead():
                payload = con.readAll()
                url = force_decode(payload.data())
                self._handle_nxdrive_url(url)

            con.disconnectFromServer()
            if con.state() == QLocalSocket.ConnectedState:
                con.waitForDisconnected()
        finally:
            del con
        log.info("Successfully closed server socket")

    def update_status(self, engine: "Engine") -> None:
        """
        Update the systray status for synchronization,
        conflicts/errors and software updates.
        """
        sync_state = error_state = update_state = ""

        update_state = self.manager.updater.status
        self.refresh_conflicts(engine.uid)

        # Check synchronization state
        if self.manager.restart_needed:
            sync_state = "restart"
        elif engine.is_paused():
            sync_state = "suspended"
        elif engine.is_syncing():
            sync_state = "syncing"

        # Check error state
        if engine.has_invalid_credentials():
            error_state = "auth_expired"
        elif self.conflicts_model.count:
            error_state = "conflicted"
        elif self.errors_model.count:
            error_state = "error"

        self._window_root(self.systray_window).setStatus.emit(
            sync_state, error_state, update_state
        )

    @pyqtSlot()
    def refresh_actions(self) -> None:
        actions = self.api.get_actions()
        if actions != self.action_model.actions:
            self.action_model.set_actions(actions)
        self.action_model.fileChanged.emit()

    @pyqtSlot(str)
    def get_last_files(self, uid: str) -> None:
        files = self.api.get_last_files(uid, 10, "")
        if files != self.file_model.files:
            self.file_model.empty()
            self.file_model.addFiles(files)
        self.file_model.fileChanged.emit()

    def current_language(self) -> Optional[str]:
        lang = Translator.locale()
        for tag, name in self.language_model.languages:
            if tag == lang:
                return name
        return None

    def show_metrics_acceptance(self) -> None:
        """ Display a "friendly" dialog box to ask user for metrics approval. """

        tr = Translator.get

        dialog = QDialog()
        dialog.setWindowTitle(tr("SHARE_METRICS_TITLE", [APP_NAME]))
        dialog.setWindowIcon(self.icon)
        dialog.setStyleSheet("background-color: #ffffff;")
        layout = QVBoxLayout()

        info = QLabel(tr("SHARE_METRICS_MSG", [COMPANY]))
        info.setTextFormat(Qt.RichText)
        info.setWordWrap(True)
        layout.addWidget(info)

        def analytics_choice(state) -> None:
            Options.use_analytics = bool(state)

        def errors_choice(state) -> None:
            Options.use_sentry = bool(state)

        # Checkboxes
        em_analytics = QCheckBox(tr("SHARE_METRICS_ERROR_REPORTING"))
        em_analytics.setChecked(True)
        em_analytics.stateChanged.connect(errors_choice)
        layout.addWidget(em_analytics)

        cb_analytics = QCheckBox(tr("SHARE_METRICS_ANALYTICS"))
        cb_analytics.stateChanged.connect(analytics_choice)
        layout.addWidget(cb_analytics)

        # Buttons
        buttons = QDialogButtonBox()
        buttons.setStandardButtons(QDialogButtonBox.Apply)
        buttons.clicked.connect(dialog.close)
        layout.addWidget(buttons)
        dialog.setLayout(layout)
        dialog.resize(400, 200)
        dialog.show()
        dialog.exec_()

        states = []
        if Options.use_analytics:
            states.append("analytics")
        if Options.use_sentry:
            states.append("sentry")

        (Options.nxdrive_home / "metrics.state").write_text("\n".join(states))

    def ask_for_metrics_approval(self) -> None:
        """Should we setup and use Sentry and/or Google Analytics?"""

        # Check the user choice first
        Options.nxdrive_home.mkdir(parents=True, exist_ok=True)

        STATE_FILE = Options.nxdrive_home / "metrics.state"
        if STATE_FILE.is_file():
            lines = STATE_FILE.read_text().splitlines()
            Options.use_sentry = "sentry" in lines
            Options.use_analytics = "analytics" in lines
            # Abort now, the user already decided to use Sentry or not
            return

        # The user did not choose yet, display a message box
        self.show_metrics_acceptance()
Esempio n. 44
0
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtCore import QUrl
from PyQt5.QtQml import qmlRegisterType
from PyQt5.QtWidgets import QApplication
from mvc_control.controller import Controller
import sys, signal
from mvc_view.FFDScene import FFDScene
from util.util import filter_for_speed

__author__ = 'ac'

# logging.basicConfig(level=logging.DEBUG)
app = QApplication(sys.argv)

signal.signal(signal.SIGINT, signal.SIG_DFL)


qmlRegisterType(FFDScene, 'FFD', 1, 0, "FFDScene")
# controller = Controller()

engine = QQmlApplicationEngine()
engine.load(QUrl(filter_for_speed(file_name='res/ui/main.qml')))
scene = engine.rootObjects()[0].findChild(FFDScene, 'scene')

controller = scene.controller  # type: Controller
engine.rootContext().setContextProperty('controller', controller)

# print('main thread:', threading.current_thread().ident)
# app.exec()
sys.exit(app.exec())
Esempio n. 45
0
class QtApplication(QApplication, Application):
    pluginsLoaded = Signal()
    applicationRunning = Signal()
    
    def __init__(self, tray_icon_name: str = None, **kwargs) -> None:
        plugin_path = ""
        if sys.platform == "win32":
            if hasattr(sys, "frozen"):
                plugin_path = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "PyQt5", "plugins")
                Logger.log("i", "Adding QT5 plugin path: %s", plugin_path)
                QCoreApplication.addLibraryPath(plugin_path)
            else:
                import site
                for sitepackage_dir in site.getsitepackages():
                    QCoreApplication.addLibraryPath(os.path.join(sitepackage_dir, "PyQt5", "plugins"))
        elif sys.platform == "darwin":
            plugin_path = os.path.join(self.getInstallPrefix(), "Resources", "plugins")

        if plugin_path:
            Logger.log("i", "Adding QT5 plugin path: %s", plugin_path)
            QCoreApplication.addLibraryPath(plugin_path)

        # use Qt Quick Scene Graph "basic" render loop
        os.environ["QSG_RENDER_LOOP"] = "basic"

        super().__init__(sys.argv, **kwargs) # type: ignore

        self._qml_import_paths = [] #type: List[str]
        self._main_qml = "main.qml" #type: str
        self._qml_engine = None #type: Optional[QQmlApplicationEngine]
        self._main_window = None #type: Optional[MainWindow]
        self._tray_icon_name = tray_icon_name #type: Optional[str]
        self._tray_icon = None #type: Optional[str]
        self._tray_icon_widget = None #type: Optional[QSystemTrayIcon]
        self._theme = None #type: Optional[Theme]
        self._renderer = None #type: Optional[QtRenderer]

        self._job_queue = None #type: Optional[JobQueue]
        self._version_upgrade_manager = None #type: Optional[VersionUpgradeManager]

        self._is_shutting_down = False #type: bool

        self._recent_files = [] #type: List[QUrl]

        self._configuration_error_message = None #type: Optional[ConfigurationErrorMessage]

    def addCommandLineOptions(self) -> None:
        super().addCommandLineOptions()
        # This flag is used by QApplication. We don't process it.
        self._cli_parser.add_argument("-qmljsdebugger",
                                      help = "For Qt's QML debugger compatibility")

    def initialize(self) -> None:
        super().initialize()
        # Initialize the package manager to remove and install scheduled packages.
        self._package_manager = self._package_manager_class(self, parent = self)

        self._mesh_file_handler = MeshFileHandler(self) #type: MeshFileHandler
        self._workspace_file_handler = WorkspaceFileHandler(self) #type: WorkspaceFileHandler

        # Remove this and you will get Windows 95 style for all widgets if you are using Qt 5.10+
        self.setStyle("fusion")

        self.setAttribute(Qt.AA_UseDesktopOpenGL)
        major_version, minor_version, profile = OpenGLContext.detectBestOpenGLVersion()

        if major_version is None and minor_version is None and profile is None and not self.getIsHeadLess():
            Logger.log("e", "Startup failed because OpenGL version probing has failed: tried to create a 2.0 and 4.1 context. Exiting")
            QMessageBox.critical(None, "Failed to probe OpenGL",
                                 "Could not probe OpenGL. This program requires OpenGL 2.0 or higher. Please check your video card drivers.")
            sys.exit(1)
        else:
            opengl_version_str = OpenGLContext.versionAsText(major_version, minor_version, profile)
            Logger.log("d", "Detected most suitable OpenGL context version: %s", opengl_version_str)
        if not self.getIsHeadLess():
            OpenGLContext.setDefaultFormat(major_version, minor_version, profile = profile)

        self._qml_import_paths.append(os.path.join(os.path.dirname(sys.executable), "qml"))
        self._qml_import_paths.append(os.path.join(self.getInstallPrefix(), "Resources", "qml"))

        Logger.log("i", "Initializing job queue ...")
        self._job_queue = JobQueue()
        self._job_queue.jobFinished.connect(self._onJobFinished)

        Logger.log("i", "Initializing version upgrade manager ...")
        self._version_upgrade_manager = VersionUpgradeManager(self)

    def startSplashWindowPhase(self) -> None:
        super().startSplashWindowPhase()

        self._package_manager.initialize()

        # Read preferences here (upgrade won't work) to get the language in use, so the splash window can be shown in
        # the correct language.
        try:
            preferences_filename = Resources.getPath(Resources.Preferences, self._app_name + ".cfg")
            self._preferences.readFromFile(preferences_filename)
        except FileNotFoundError:
            Logger.log("i", "Preferences file not found, ignore and use default language '%s'", self._default_language)

        signal.signal(signal.SIGINT, signal.SIG_DFL)
        # This is done here as a lot of plugins require a correct gl context. If you want to change the framework,
        # these checks need to be done in your <framework>Application.py class __init__().

        i18n_catalog = i18nCatalog("uranium")

        self._configuration_error_message = ConfigurationErrorMessage(self,
              i18n_catalog.i18nc("@info:status", "Your configuration seems to be corrupt."),
              lifetime = 0,
              title = i18n_catalog.i18nc("@info:title", "Configuration errors")
              )
        # Remove, install, and then loading plugins
        self.showSplashMessage(i18n_catalog.i18nc("@info:progress", "Loading plugins..."))
        # Remove and install the plugins that have been scheduled
        self._plugin_registry.initializeBeforePluginsAreLoaded()
        self._loadPlugins()
        self._plugin_registry.checkRequiredPlugins(self.getRequiredPlugins())
        self.pluginsLoaded.emit()

        self.showSplashMessage(i18n_catalog.i18nc("@info:progress", "Updating configuration..."))
        with self._container_registry.lockFile():
            VersionUpgradeManager.getInstance().upgrade()

        # Load preferences again because before we have loaded the plugins, we don't have the upgrade routine for
        # the preferences file. Now that we have, load the preferences file again so it can be upgraded and loaded.
        try:
            preferences_filename = Resources.getPath(Resources.Preferences, self._app_name + ".cfg")
            with open(preferences_filename, "r", encoding = "utf-8") as f:
                serialized = f.read()
            # This performs the upgrade for Preferences
            self._preferences.deserialize(serialized)
            self._preferences.setValue("general/plugins_to_remove", "")
            self._preferences.writeToFile(preferences_filename)
        except FileNotFoundError:
            Logger.log("i", "The preferences file cannot be found, will use default values")

        # Force the configuration file to be written again since the list of plugins to remove maybe changed
        self.showSplashMessage(i18n_catalog.i18nc("@info:progress", "Loading preferences..."))
        try:
            self._preferences_filename = Resources.getPath(Resources.Preferences, self._app_name + ".cfg")
            self._preferences.readFromFile(self._preferences_filename)
        except FileNotFoundError:
            Logger.log("i", "The preferences file '%s' cannot be found, will use default values",
                       self._preferences_filename)
            self._preferences_filename = Resources.getStoragePath(Resources.Preferences, self._app_name + ".cfg")

        # FIXME: This is done here because we now use "plugins.json" to manage plugins instead of the Preferences file,
        # but the PluginRegistry will still import data from the Preferences files if present, such as disabled plugins,
        # so we need to reset those values AFTER the Preferences file is loaded.
        self._plugin_registry.initializeAfterPluginsAreLoaded()

        # Check if we have just updated from an older version
        self._preferences.addPreference("general/last_run_version", "")
        last_run_version_str = self._preferences.getValue("general/last_run_version")
        if not last_run_version_str:
            last_run_version_str = self._version
        last_run_version = Version(last_run_version_str)
        current_version = Version(self._version)
        if last_run_version < current_version:
            self._just_updated_from_old_version = True
        self._preferences.setValue("general/last_run_version", str(current_version))
        self._preferences.writeToFile(self._preferences_filename)

        # Preferences: recent files
        self._preferences.addPreference("%s/recent_files" % self._app_name, "")
        file_names = self._preferences.getValue("%s/recent_files" % self._app_name).split(";")
        for file_name in file_names:
            if not os.path.isfile(file_name):
                continue
            self._recent_files.append(QUrl.fromLocalFile(file_name))

        if not self.getIsHeadLess():
            # Initialize System tray icon and make it invisible because it is used only to show pop up messages
            self._tray_icon = None
            if self._tray_icon_name:
                self._tray_icon = QIcon(Resources.getPath(Resources.Images, self._tray_icon_name))
                self._tray_icon_widget = QSystemTrayIcon(self._tray_icon)
                self._tray_icon_widget.setVisible(False)

    def initializeEngine(self) -> None:
        # TODO: Document native/qml import trickery
        self._qml_engine = QQmlApplicationEngine(self)
        self._qml_engine.setOutputWarningsToStandardError(False)
        self._qml_engine.warnings.connect(self.__onQmlWarning)

        for path in self._qml_import_paths:
            self._qml_engine.addImportPath(path)

        if not hasattr(sys, "frozen"):
            self._qml_engine.addImportPath(os.path.join(os.path.dirname(__file__), "qml"))

        self._qml_engine.rootContext().setContextProperty("QT_VERSION_STR", QT_VERSION_STR)
        self._qml_engine.rootContext().setContextProperty("screenScaleFactor", self._screenScaleFactor())

        self.registerObjects(self._qml_engine)

        Bindings.register()
        self._qml_engine.load(self._main_qml)
        self.engineCreatedSignal.emit()

    recentFilesChanged = pyqtSignal()

    @pyqtProperty("QVariantList", notify=recentFilesChanged)
    def recentFiles(self) -> List[QUrl]:
        return self._recent_files

    def _onJobFinished(self, job: Job) -> None:
        if isinstance(job, WriteFileJob):
            if not job.getResult() or not job.getAddToRecentFiles():
                # For a write file job, if it failed or it doesn't need to be added to the recent files list, we do not
                # add it.
                return
        elif (not isinstance(job, ReadMeshJob) and not isinstance(job, ReadFileJob)) or not job.getResult():
            return

        if isinstance(job, (ReadMeshJob, ReadFileJob, WriteFileJob)):
            self.addFileToRecentFiles(job.getFileName())

    def addFileToRecentFiles(self, file_name: str) -> None:
        file_path = QUrl.fromLocalFile(file_name)

        if file_path in self._recent_files:
            self._recent_files.remove(file_path)

        self._recent_files.insert(0, file_path)
        if len(self._recent_files) > 10:
            del self._recent_files[10]

        pref = ""
        for path in self._recent_files:
            pref += path.toLocalFile() + ";"

        self.getPreferences().setValue("%s/recent_files" % self.getApplicationName(), pref)
        self.recentFilesChanged.emit()

    def run(self) -> None:
        super().run()

    def hideMessage(self, message: Message) -> None:
        with self._message_lock:
            if message in self._visible_messages:
                message.hide(send_signal = False)  # we're in handling hideMessageSignal so we don't want to resend it
                self._visible_messages.remove(message)
                self.visibleMessageRemoved.emit(message)

    def showMessage(self, message: Message) -> None:
        with self._message_lock:
            if message not in self._visible_messages:
                self._visible_messages.append(message)
                message.setLifetimeTimer(QTimer())
                message.setInactivityTimer(QTimer())
                self.visibleMessageAdded.emit(message)

        # also show toast message when the main window is minimized
        self.showToastMessage(self._app_name, message.getText())

    def _onMainWindowStateChanged(self, window_state: int) -> None:
        if self._tray_icon and self._tray_icon_widget:
            visible = window_state == Qt.WindowMinimized
            self._tray_icon_widget.setVisible(visible)

    # Show toast message using System tray widget.
    def showToastMessage(self, title: str, message: str) -> None:
        if self.checkWindowMinimizedState() and self._tray_icon_widget:
            # NOTE: Qt 5.8 don't support custom icon for the system tray messages, but Qt 5.9 does.
            #       We should use the custom icon when we switch to Qt 5.9
            self._tray_icon_widget.showMessage(title, message)

    def setMainQml(self, path: str) -> None:
        self._main_qml = path

    def exec_(self, *args: Any, **kwargs: Any) -> None:
        self.applicationRunning.emit()
        super().exec_(*args, **kwargs)
        
    @pyqtSlot()
    def reloadQML(self) -> None:
        # only reload when it is a release build
        if not self.getIsDebugMode():
            return
        if self._qml_engine and self._theme:
            self._qml_engine.clearComponentCache()
            self._theme.reload()
            self._qml_engine.load(self._main_qml)
            # Hide the window. For some reason we can't close it yet. This needs to be done in the onComponentCompleted.
            for obj in self._qml_engine.rootObjects():
                if obj != self._qml_engine.rootObjects()[-1]:
                    obj.hide()

    @pyqtSlot()
    def purgeWindows(self) -> None:
        # Close all root objects except the last one.
        # Should only be called by onComponentCompleted of the mainWindow.
        if self._qml_engine:
            for obj in self._qml_engine.rootObjects():
                if obj != self._qml_engine.rootObjects()[-1]:
                    obj.close()

    @pyqtSlot("QList<QQmlError>")
    def __onQmlWarning(self, warnings: List[QQmlError]) -> None:
        for warning in warnings:
            Logger.log("w", warning.toString())

    engineCreatedSignal = Signal()

    def isShuttingDown(self) -> bool:
        return self._is_shutting_down

    def registerObjects(self, engine) -> None: #type: ignore #Don't type engine, because the type depends on the platform you're running on so it always gives an error somewhere.
        engine.rootContext().setContextProperty("PluginRegistry", PluginRegistry.getInstance())

    def getRenderer(self) -> QtRenderer:
        if not self._renderer:
            self._renderer = QtRenderer()

        return cast(QtRenderer, self._renderer)

    mainWindowChanged = Signal()

    def getMainWindow(self) -> Optional[MainWindow]:
        return self._main_window

    def setMainWindow(self, window: MainWindow) -> None:
        if window != self._main_window:
            if self._main_window is not None:
                self._main_window.windowStateChanged.disconnect(self._onMainWindowStateChanged)

            self._main_window = window
            if self._main_window is not None:
                self._main_window.windowStateChanged.connect(self._onMainWindowStateChanged)

            self.mainWindowChanged.emit()

    def setVisible(self, visible: bool) -> None:
        if self._main_window is not None:
            self._main_window.visible = visible

    @property
    def isVisible(self) -> bool:
        if self._main_window is not None:
            return self._main_window.visible #type: ignore #MyPy doesn't realise that self._main_window cannot be None here.
        return False

    def getTheme(self) -> Optional[Theme]:
        if self._theme is None:
            if self._qml_engine is None:
                Logger.log("e", "The theme cannot be accessed before the engine is initialised")
                return None

            self._theme = UM.Qt.Bindings.Theme.Theme.getInstance(self._qml_engine)
        return self._theme

    #   Handle a function that should be called later.
    def functionEvent(self, event: QEvent) -> None:
        e = _QtFunctionEvent(event)
        QCoreApplication.postEvent(self, e)

    #   Handle Qt events
    def event(self, event: QEvent) -> bool:
        if event.type() == _QtFunctionEvent.QtFunctionEvent:
            event._function_event.call()
            return True

        return super().event(event)

    def windowClosed(self, save_data: bool = True) -> None:
        Logger.log("d", "Shutting down %s", self.getApplicationName())
        self._is_shutting_down = True

        # garbage collect tray icon so it gets properly closed before the application is closed
        self._tray_icon_widget = None

        if save_data:
            try:
                self.savePreferences()
            except Exception as e:
                Logger.log("e", "Exception while saving preferences: %s", repr(e))

        try:
            self.applicationShuttingDown.emit()
        except Exception as e:
            Logger.log("e", "Exception while emitting shutdown signal: %s", repr(e))

        try:
            self.getBackend().close()
        except Exception as e:
            Logger.log("e", "Exception while closing backend: %s", repr(e))

        if self._tray_icon_widget:
            self._tray_icon_widget.deleteLater()

        self.quit()

    def checkWindowMinimizedState(self) -> bool:
        if self._main_window is not None and self._main_window.windowState() == Qt.WindowMinimized:
            return True
        else:
            return False

    ##  Get the backend of the application (the program that does the heavy lifting).
    #   The backend is also a QObject, which can be used from qml.
    @pyqtSlot(result = "QObject*")
    def getBackend(self) -> Backend:
        return self._backend

    ##  Property used to expose the backend
    #   It is made static as the backend is not supposed to change during runtime.
    #   This makes the connection between backend and QML more reliable than the pyqtSlot above.
    #   \returns Backend \type{Backend}
    @pyqtProperty("QVariant", constant = True)
    def backend(self) -> Backend:
        return self.getBackend()

    ## Create a class variable so we can manage the splash in the CrashHandler dialog when the Application instance
    # is not yet created, e.g. when an error occurs during the initialization
    splash = None  # type: Optional[QSplashScreen]

    def createSplash(self) -> None:
        if not self.getIsHeadLess():
            try:
                QtApplication.splash = self._createSplashScreen()
            except FileNotFoundError:
                QtApplication.splash = None
            else:
                if QtApplication.splash:
                    QtApplication.splash.show()
                    self.processEvents()

    ##  Display text on the splash screen.
    def showSplashMessage(self, message: str) -> None:
        if not QtApplication.splash:
            self.createSplash()
        
        if QtApplication.splash:
            QtApplication.splash.showMessage(message, Qt.AlignHCenter | Qt.AlignVCenter)
            self.processEvents()
        elif self.getIsHeadLess():
            Logger.log("d", message)

    ##  Close the splash screen after the application has started.
    def closeSplash(self) -> None:
        if QtApplication.splash:
            QtApplication.splash.close()
            QtApplication.splash = None

    ## Create a QML component from a qml file.
    #  \param qml_file_path: The absolute file path to the root qml file.
    #  \param context_properties: Optional dictionary containing the properties that will be set on the context of the
    #                              qml instance before creation.
    #  \return None in case the creation failed (qml error), else it returns the qml instance.
    #  \note If the creation fails, this function will ensure any errors are logged to the logging service.
    def createQmlComponent(self, qml_file_path: str, context_properties: Dict[str, "QObject"] = None) -> Optional["QObject"]:
        if self._qml_engine is None: # Protect in case the engine was not initialized yet
            return None
        path = QUrl.fromLocalFile(qml_file_path)
        component = QQmlComponent(self._qml_engine, path)
        result_context = QQmlContext(self._qml_engine.rootContext()) #type: ignore #MyPy doens't realise that self._qml_engine can't be None here.
        if context_properties is not None:
            for name, value in context_properties.items():
                result_context.setContextProperty(name, value)
        result = component.create(result_context)
        for err in component.errors():
            Logger.log("e", str(err.toString()))
        if result is None:
            return None

        # We need to store the context with the qml object, else the context gets garbage collected and the qml objects
        # no longer function correctly/application crashes.
        result.attached_context = result_context
        return result

    ##  Delete all nodes containing mesh data in the scene.
    #   \param only_selectable. Set this to False to delete objects from all build plates
    @pyqtSlot()
    def deleteAll(self, only_selectable = True) -> None:
        Logger.log("i", "Clearing scene")
        if not self.getController().getToolsEnabled():
            return

        nodes = []
        for node in DepthFirstIterator(self.getController().getScene().getRoot()): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
            if not isinstance(node, SceneNode):
                continue
            if (not node.getMeshData() and not node.callDecoration("getLayerData")) and not node.callDecoration("isGroup"):
                continue  # Node that doesnt have a mesh and is not a group.
            if only_selectable and not node.isSelectable():
                continue
            if not node.callDecoration("isSliceable") and not node.callDecoration("getLayerData") and not node.callDecoration("isGroup"):
                continue  # Only remove nodes that are selectable.
            if node.getParent() and cast(SceneNode, node.getParent()).callDecoration("isGroup"):
                continue  # Grouped nodes don't need resetting as their parent (the group) is resetted)
            nodes.append(node)
        if nodes:
            op = GroupedOperation()

            for node in nodes:
                op.addOperation(RemoveSceneNodeOperation(node))

                # Reset the print information
                self.getController().getScene().sceneChanged.emit(node)

            op.push()
            Selection.clear()

    ##  Get the MeshFileHandler of this application.
    def getMeshFileHandler(self) -> MeshFileHandler:
        return self._mesh_file_handler

    def getWorkspaceFileHandler(self) -> WorkspaceFileHandler:
        return self._workspace_file_handler

    @pyqtSlot(result = QObject)
    def getPackageManager(self) -> PackageManager:
        return self._package_manager

    ##  Gets the instance of this application.
    #
    #   This is just to further specify the type of Application.getInstance().
    #   \return The instance of this application.
    @classmethod
    def getInstance(cls, *args, **kwargs) -> "QtApplication":
        return cast(QtApplication, super().getInstance(**kwargs))

    def _createSplashScreen(self) -> QSplashScreen:
        return QSplashScreen(QPixmap(Resources.getPath(Resources.Images, self.getApplicationName() + ".png")))

    def _screenScaleFactor(self) -> float:
        # OSX handles sizes of dialogs behind our backs, but other platforms need
        # to know about the device pixel ratio
        if sys.platform == "darwin":
            return 1.0
        else:
            # determine a device pixel ratio from font metrics, using the same logic as UM.Theme
            fontPixelRatio = QFontMetrics(QCoreApplication.instance().font()).ascent() / 11
            # round the font pixel ratio to quarters
            fontPixelRatio = int(fontPixelRatio * 4) / 4
            return fontPixelRatio
Esempio n. 46
0
class UiState(QObject):
    sigComPortOpened = pyqtSignal()
    sigComPortClosed = pyqtSignal()
    sigPowerOn = pyqtSignal()
    sigPowerOff = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.fsm = QStateMachine()
        self.qmlEngine = QQmlApplicationEngine()
        self.qmlEngine.addImportPath("qml")
        self.qmlEngine.addImportPath("lib")
        self.qmlEngine.load(QUrl('qrc:/qml/main.qml'))        
        self.rootObject = self.qmlEngine.rootObjects()[0]

        self.rootObject.comPortOpened.connect(self.sigComPortOpened)
        self.rootObject.comPortClosed.connect(self.sigComPortClosed)
        self.rootObject.powerOn.connect(self.sigPowerOn)
        self.rootObject.powerOff.connect(self.sigPowerOff)
        self.createState()
        pass

    def createState(self):
        # state defintion
        mainState = QState(self.fsm)
        finalState = QFinalState(self.fsm)
        self.fsm.setInitialState(mainState)
        
        initState = QState(mainState)
        openState = QState(mainState)
        mainState.setInitialState(initState)

        standbyState = QState(openState)
        processingState = QState(openState)
        openState.setInitialState(standbyState)

        # transition defition
        initState.addTransition(self.sigComPortOpened, openState) 
        openState.addTransition(self.sigComPortClosed, initState)

        standbyState.addTransition(self.sigPowerOn, processingState)
        processingState.addTransition(self.sigPowerOff, standbyState)

        initState.entered.connect(self.initStateEntered)
        openState.entered.connect(self.openStateEntered)
        standbyState.entered.connect(self.standbyStateEntered)
        processingState.entered.connect(self.processingStateEntered)

        # fsm start
        self.fsm.start()
        pass

    @pyqtSlot()
    def initStateEntered(self):
        print("init")
        QMetaObject.invokeMethod(self.rootObject, "setPathViewIndex", QtCore.Q_ARG("QVariant", 0))
        pass

    @pyqtSlot()   
    def openStateEntered(self):
        print("open")
        pass

    @pyqtSlot()
    def standbyStateEntered(self):
        print("standby")
        QMetaObject.invokeMethod(self.rootObject, "setPathViewIndex", QtCore.Q_ARG("QVariant", 1))
        pass

    @pyqtSlot()
    def processingStateEntered(self):
        print("processing")
        QMetaObject.invokeMethod(self.rootObject, "setPathViewIndex",QtCore.Q_ARG("QVariant", 2))
        pass 
Esempio n. 47
0
import sys
from PyQt5.QtCore import QObject, pyqtSlot
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine


class InPython(QObject):
    @pyqtSlot(str, )
    def login(self, Login):
        print(Login)
        return "a"


if __name__ == "__main__":
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()
    context = engine.rootContext()
    context.setContextProperty("main", engine)
    engine.load('Main.qml')
    win = engine.rootObjects()[0]
    
    inPython = InPython()
    context.setContextProperty("loginManger", inPython)
    
    win.show()
    sys.exit(app.exec_())
Esempio n. 48
0
                 Card.type == CardType.MINION.value)))
    cards = cards.order_by(Card.cost).order_by(Card.type.asc()). \
                            order_by(Card.name.asc()).limit(8).all()
    model.reset()
    model.add_cards(cards)

if __name__ == "__main__":
    import pdb
    app = QApplication(sys.argv)
    # Register the Python type.  Its URI is 'People', it's v1.0 and the type
    # will be called 'Person' in QML.
    qmlRegisterType(TrackedCard, 'TrackedCards', 1, 0, 'TrackedCard')
    engine = QQmlApplicationEngine()
    ctxt = engine.rootContext()
    # Initialize the data base
    sqlengine = create_engine('sqlite:///stats.db', echo=False)
    Session = sessionmaker()
    Session.configure(bind=sqlengine)
    session = Session()


    ctxt.setContextProperty('pythonList', model)
    engine.load(QUrl('vt.qml'))
    engine.quit.connect(app.quit)
    autoComplete = engine.rootObjects()[0].findChild(QObject, 'autoComplete')
    autoComplete.textModified.connect(onTextChanged)
    # data = engine.rootObjects()[0].findChild(QObject, 'myList')
    # QMetaObject.invokeMethod(data, "append",
    #             Q_ARG('QVariant', {'name':'Josh', 'number': 90}))
    sys.exit(app.exec_())
Esempio n. 49
0
class AppController(QObject):
    """The main controller of this application."""
    def __init__(self):
        super(AppController, self).__init__()
        ServiceAdaptor(self)

        self.contexts = []
        self._osdVisible = False
        self._initQuitTimer()

    def _initQuitTimer(self):
        self._quitTimer = QTimer()
        self._quitTimer.setInterval(10 * 1000)
        self._quitTimer.setSingleShot(True)
        self._quitTimer.timeout.connect(self._checkContexts)

    def _checkContexts(self):
        if (self.contexts) or self._osdVisible:
            self._quitTimer.start()
        else:
            qApp.quit()

    def _contextNeedSound(self):
        self._sound.play()

    def _contextFinished(self):
        sender = self.sender()
        if sender in self.contexts:
            # TODO: the remove _doesn't_ get the sender object
            # garbage collected, there must be some reference cycles.
            self.contexts.remove(sender)
        self._checkContexts()

    def _contextNeedOSD(self, area):
        def _osdClosed():
            self._osdVisible = False

        self._osdVisible = True
        self._qmlEngine = QQmlApplicationEngine()
        self._qmlEngine.load(QUrl(OSD_QML))
        osd = self._qmlEngine.rootObjects()[0]
        osd.setX(area.x() + (area.width() - osd.width()) / 2)
        osd.setY(area.y() + (area.height() - osd.height()) / 2)
        osd.showTips()
        osd.closed.connect(_osdClosed)

    def _createContextSettings(self):
        settings = ScreenshotSettings()
        settings.tmpImageFile = "%s.png" % tempfile.mktemp()
        settings.tmpBlurFile = "%s-blur.png" % tempfile.mktemp()
        settings.tmpMosaiceFile = "%s-mosaic.png" % tempfile.mktemp()
        settings.tmpSaveFile = "%s-save.png" % tempfile.mktemp()

        return settings

    def runWithArguments(self, arguments):
        for _context in self.contexts:
            if _context.isActive():
                return

        argValues = processArguments(arguments)
        delay = argValues["delay"]

        self._sound = QSound(SOUND_FILE)
        self._sound.setLoops(1)

        context = AppContext(argValues)
        context.settings = self._createContextSettings()
        context.finished.connect(self._contextFinished)
        context.needSound.connect(self._contextNeedSound)
        context.needOSD.connect(self._contextNeedOSD)
        self.contexts.append(context)

        if delay > 0:
            notificationsInterface.notify(_("Deepin Screenshot"),
            _("Deepin Screenshot will start after %s seconds.") % delay)

        QTimer.singleShot(max(0, delay * 1000), context.main)
Esempio n. 50
0
class PdfDetailWindow:
    QML_FILE = "qml/PdfDetailsWindow.qml"
    window = None

    references = []
    num_references = 0

    check_links_thread = None
    dl_thread = None

    cur_download = 0
    num_downloads = 0

    def __init__(self, pdf_uri, fake=False):
        self.fake = fake

        # Create window
        self.engine = QQmlApplicationEngine()
        self.engine.load(self.QML_FILE)
        self.window = self.engine.rootObjects()[0]
        self.window.setTitle(os.path.basename(pdf_uri))

        # Connect signals
        self.window.download.connect(self.download)
        self.window.signalCheckLinks.connect(self.checkLinks)
        self.window.shutdown.connect(self.onClosing)
        self.window.signalOpenMainWindow.connect(self.openMainWindow)
        self.window.signalShowAboutWindow.connect(show_about_window)

        if self.fake:
            # self.references = REFS_TEST
            self.references = []
        else:
            # Sort references by type
            ref_set = PDFX_INSTANCES[pdf_uri].get_references()
            self.references = sorted(ref_set, key=lambda ref: ref.reftype)
        self.num_references = len(self.references)
        self.window.setStatusText("%s references" % self.num_references)

        for ref in self.references:
            self.window.addReference(ref.ref, ref.reftype)

        # This works somewhat. Simply binds the list to the listModel variable
        # but does not support layoutChanged, etc.
        # refs = [QVariant({"ref": ref.ref, "type": ref.reftype, "status": ""}) for ref in self.references]
        # self.engine.rootContext().setContextProperty('listModel', refs)

        # Now we try building a real model we can use with a SortFilterProxyModel
        # see https://wiki.python.org/moin/PyQt/Sorting%20numbers%20in%20columns

        # self.model = MyTableModel(refs*2, ["ref", "type", "status"])
        # self.window.setModel(self.model)
        #
        # self.model = QStandardItemModel()
        # for index, ref in enumerate(self.references):
        #     row = QStandardItem()
        #     row.setData(QVariant({
        #         "ref": ref.ref,
        #         "type": ref.reftype,
        #         "status": ""
        #     }))
        #     # row.setData(QVariant([ref.ref, ref.reftype, ""]))
        #     self.model.appendRow([row])
        # self.window.setModel(self.model)


        # self.model2 = SortFilterProxyModel()
        # self.model2.setSourceModel(self.model)
        # self.window.setModel(self.model2)

    def onClosing(self):
        print("XX Closing")
        # if self.check_links_thread:
        #     self.check_links_thread.quit()

    def openMainWindow(self):
        global MAINWINDOW_INSTANCE
        if not MAINWINDOW_INSTANCE:
            MAINWINDOW_INSTANCE = PDFxGui()
        MAINWINDOW_INSTANCE.window.show()
        MAINWINDOW_INSTANCE.window.raise_()
        MAINWINDOW_INSTANCE.window.requestActivate()

    def download(self, selected_item_indexes, target_folder_uri):
        """
        selected_item_indexes is a [QJSValue](http://doc.qt.io/qt-5/qjsvalue.html) Array
        """
        # Parse file:/// uri to local path
        parsed_path = urlparse(target_folder_uri)
        target_folder = os.path.abspath(parsed_path.path)
        print("targetfolder:", target_folder)

        # Get selected item indexes
        num_items_selected = selected_item_indexes.property("length").toInt()
        item_indexes = [selected_item_indexes.property(index).toInt() for index in range(num_items_selected)]

        # Extract only PDF references
        refs = []
        for item_index in item_indexes:
            if self.references[item_index].reftype in ["pdf"]:
                refs.append(self.references[item_index])

        if not refs:
            self.window.setStatusText("No pdf documents selected")
            self.window.downloadFinished()
            return

        # Filter out only "url" and "pdf" references
        self.num_downloads = len(refs)
        self.cur_downloaded = 0
        self.num_downloads_errors = 0

        def signal_download_item_finished(ref, status):
            index = self.references.index(ref)
            self.cur_downloaded += 1
            if status != "200":
                self.num_downloads_errors += 1
            print("done:", self.cur_downloaded, status)
            self.window.setStatusText("Downloaded %s of %s..." % (self.cur_downloaded, self.num_downloads))
            self.window.setStatusProgress(float(self.cur_downloaded) / float(self.num_downloads))
            self.window.checkLinksStatusCodeReceived(index, status)

        def signal_download_finished():
            self.window.setStatusText("Downloaded %s pdf documents (%s errors)" % (self.num_downloads, self.num_downloads_errors))
            self.window.downloadFinished()

        self.window.setStatusText("Downloading %s pdf documents..." % self.num_downloads)
        self.window.setStatusProgress(0)

        self.dl_thread = DownloadQThread(refs, target_folder)
        self.dl_thread.download_item_finished.connect(signal_download_item_finished)
        self.dl_thread.download_finished.connect(signal_download_finished)
        self.dl_thread.start()

    def checkLinks(self):
        print("start checking links...")

        # Filter out only "url" and "pdf" references
        refs = [ref for ref in self.references if ref.reftype in ["url", "pdf"]]
        self.num_checks_total = len(refs)
        self.num_checks_current = 0
        self.num_checks_errors = 0

        def signal_checking_links_item_finished(ref, status_code):
            self.num_checks_current += 1
            if status_code != "200":
                self.num_checks_errors += 1
            print("checked %s/%s. [%s] %s" % (self.num_checks_current, self.num_checks_total, status_code, ref))
            self.window.setStatusText("Checked link %s of %s..." % (self.num_checks_current, self.num_checks_total))
            self.window.setStatusProgress(float(self.num_checks_current) / float(self.num_checks_total))

            index = self.references.index(ref)
            self.window.checkLinksStatusCodeReceived(index, status_code)

        def signal_checking_links_finished():
            text = "Checked %s links (%s errors)" % (self.num_checks_total, self.num_checks_errors)
            self.window.setStatusText(text)
            self.window.checkLinksFinished()

        self.window.setStatusText("Checking links...")
        self.window.setStatusProgress(0)

        self.check_links_thread = CheckLinksQThread(refs)
        self.check_links_thread.checking_links_item_finished.connect(signal_checking_links_item_finished)
        self.check_links_thread.checking_links_finished.connect(signal_checking_links_finished)
        self.check_links_thread.start()
Esempio n. 51
0
            window = engine.rootObjects()[0]
            myObject = window.findChild(QObject, "myObject")
            #loop.call_soon(myObject.funcRetClicked())
            #myObject.funcRetClicked()
            loop.run_in_executor(exec, myObject.funcRetClicked)
        '''

with loop:
    try:
        test = Test()
        service = Service(loop)

        #loop.run_forever()

        print('1')
        # rootObjects 실행전 context를 선언/추가해줍니다.
        ctx = engine.rootContext()
        ctx.setContextProperty('Service', service)

        #engine.load("main.qml")
        engine.load("qml/tytrader.qml")
        window = engine.rootObjects()[0]
        #window.setContextProperty('Service', service)

        loop.run_until_complete(test.printInterval())
        loop.run_forever()
    except:
        pass


Esempio n. 52
0
            sleeptime = 1000000 - datetime.datetime.now().microsecond
            yield from asyncio.sleep(round(sleeptime * 0.000001, 2))


with loop:

    ctx = engine.rootContext()
    engine.load("progressor.qml")
    #engine.load("progressor_multiple.qml")
    #window = engine.rootObjects()[0]
    #window = engine.rootObjects()[0].findChild("wnd1")
    #root = engine.rootObjects()[0].findChild(QObject, "rootObj")
    #root = engine.rootObjects()[0]

    #window = engine.rootObjects()[0].findChild(QObject, "wnd")
    window = engine.rootObjects()[0].findChild(QObject, "wnd_dummy")
    window1 = engine.rootObjects()[0].findChild(QObject, "wnd1")
    window2 = engine.rootObjects()[0].findChild(QObject, "wnd2")

    window.show()
    window1.show()
    window2.show()

    obj = window.findChild(QObject, "main")
    obj1 = window1.findChild(QObject, "main1")
    obj2 = window2.findChild(QObject, "main2")

    prog = Progressor(obj)
    prog1 = Progressor(obj1)
    prog2 = Progressor(obj2)