Example #1
0
def main(latus_appdata_folder):

    latus.logger.log.info("latus_app_data: %s" % latus_appdata_folder)

    # check if we should run the setup wizard first
    if latus.preferences.preferences_db_exists(latus_appdata_folder):
        pref = latus.preferences.Preferences(latus_appdata_folder)
    else:
        pref = None

    app = QApplication(sys.argv)  # need this even for the GUIWizard

    if not pref or (pref and not pref.folders_are_set()):
        latus.logger.log.info('not all preferences are set - starting WizardGUI')
        app_gui_wizard = latus.gui_wizard.GUIWizard(latus_appdata_folder)
        app_gui_wizard.exec_()
        pref = latus.preferences.Preferences(latus_appdata_folder)

    if pref and pref.folders_are_set():
        app.setQuitOnLastWindowClosed(False)  # so popup dialogs don't close the system tray icon
        system_tray = LatusSystemTrayIcon(app, latus_appdata_folder)
        system_tray.start_latus()
        system_tray.show()
        app.exec_()
    else:
        msg = 'Incomplete configuration.\n\nPlease re-run Latus and complete the Latus Setup Wizard.\n\nExiting ...'
        mb = message_box(msg)
        mb.exec()
        latus.logger.log.warn(msg.replace('\n', ' '))  # don't put newlines in the log
        sys.exit(1)
def run(manager, testing=False):
    logger.info("Creating trayicon...")
    # print(QIcon.themeSearchPaths())

    app = QApplication(sys.argv)

    # Without this, Ctrl+C will have no effect
    signal.signal(signal.SIGINT, exit)
    # Ensure cleanup happens on SIGTERM
    signal.signal(signal.SIGTERM, exit)

    timer = QtCore.QTimer()
    timer.start(100)  # You may change this if you wish.
    timer.timeout.connect(lambda: None)  # Let the interpreter run each 500 ms.

    if not QSystemTrayIcon.isSystemTrayAvailable():
        QMessageBox.critical(None, "Systray", "I couldn't detect any system tray on this system. Either get one or run the ActivityWatch modules from the console.")
        sys.exit(1)

    widget = QWidget()

    icon = QIcon(":/logo.png")
    trayIcon = TrayIcon(manager, icon, widget, testing=testing)
    trayIcon.show()

    trayIcon.showMessage("ActivityWatch", "ActivityWatch is starting up...")

    QApplication.setQuitOnLastWindowClosed(False)

    # Run the application, blocks until quit
    return app.exec_()
Example #3
0
def start_qt_app(config):
    import sys
    from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMessageBox
    from quamash import QEventLoop
    from ui.main import Window
    from ui.qt_gui_connection import qSignal
    app = QApplication(sys.argv)
    
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    
    if not QSystemTrayIcon.isSystemTrayAvailable():
        QMessageBox.critical(None, "Systray",
                             "I couldn't detect any system tray on this system.")
        sys.exit(1)

    QApplication.setQuitOnLastWindowClosed(False)
    
    gui_connection = qSignal()
    window = Window(gui_connection)
    
    def closeApp():
        print("Close app signal")
        for task in asyncio.Task.all_tasks():
            print(task)
            task.cancel()
        loop.stop()
    gui_connection.closeApp.connect(closeApp)
    
    with loop:
        #asyncio.run_coroutine_threadsafe(timer(loop, config, gui_connection), loop)
        try:
            loop.run_until_complete(timer(loop, config, gui_connection))
        except asyncio.CancelledError:
            pass
Example #4
0
def gui_main():

    args = get_arguments()

    try:
        # todo: today we're redirecting api.abel.co so for this we need to go direct.  In the future have everything on AWS including DNS.
        sentry_dsn = requests.get('http://l3wp7vlxe8.execute-api.us-west-2.amazonaws.com/dev/apps/propmtime/sentrydsn').text
        if not (sentry_dsn.startswith('http') and '@sentry.io' in sentry_dsn):
            sentry_dsn = None
    except ConnectionError:
        sentry_dsn = None

    balsa = Balsa( __application_name__, __author__, gui=True, use_sentry=sentry_dsn is not None, sentry_dsn=sentry_dsn)
    balsa.init_logger_from_args(args)

    app_data_folder = appdirs.user_config_dir(appname=__application_name__, appauthor=__author__)
    init_preferences_db(app_data_folder)

    init_exit_control_event()

    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)  # so popup dialogs don't close the system tray icon
    system_tray = PropMTimeSystemTray(app, app_data_folder, balsa.log_path)
    system_tray.show()
    app.exec_()
Example #5
0
def start():
    # Start logging all events
    if '--drop' in sys.argv:
        drop_db()

    utils.start_app_logging()
    if sys.platform == 'win32':
        from server import SingleInstance
        single_app = SingleInstance()

        if single_app.already_running():
            running_warning()

    app = QApplication(sys.argv)

    if not QSystemTrayIcon.isSystemTrayAvailable():
        QMessageBox.critical(
            None,
            "Systray",
            "Could not detect a system tray on this system"
        )
        sys.exit(1)

    QApplication.setQuitOnLastWindowClosed(False)

    osf = OSFApp()

    osf.start()

    osf.hide()
    sys.exit(app.exec_())
Example #6
0
def main():
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)
    app.setOrganizationName('sansimera-qt')
    app.setOrganizationDomain('sansimera-qt')
    app.setApplicationName('sansimera-qt')
    prog = Sansimera()
    app.exec_()
def main():
    atexit.register(Cleanup)
    QApplication.setStyle('Fusion')
    app = QApplication(sys.argv)
    app.setApplicationName("OCR Translator")
    app.setQuitOnLastWindowClosed(True)
    ocrtranslator = OCRTranslator()
    ocrtranslator.show()
    sys.exit(app.exec_())
Example #8
0
def main():
    app = QApplication(sys.argv)
    app.setApplicationName("xyplayer")
    app.setQuitOnLastWindowClosed(True)
    
    from xyplayer.player import Player
    Player = Player()
    Player.show()
    sys.exit(app.exec_())
Example #9
0
File: app.py Project: zhsj/qwechat
def runApp():
    if config.DEBUG:
        sys.argv.append("--remote-debugging-port=" + str(config.DEBUG_PORT))
    app = QApplication(sys.argv)
    app.setApplicationName(config.APP_NAME)
    QApplication.setQuitOnLastWindowClosed(False)
    window = Window()
    window.showMaximized()
    app.exec_()
Example #10
0
def main():
    parse_args(sys.argv)

    q_app = QApplication(sys.argv)
    q_app.setQuitOnLastWindowClosed(True)
    q_app.setApplicationName('FeelUOwn')

    app_event_loop = QEventLoop(q_app)
    asyncio.set_event_loop(app_event_loop)
    app = App()
    app.show()

    app_event_loop.run_forever()
    sys.exit(0)
Example #11
0
def main():
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)
    app.setOrganizationName('meteo-qt')
    app.setOrganizationDomain('meteo-qt')
    app.setApplicationName('meteo-qt')
    app.setWindowIcon(QIcon(':/logo'))
    filePath = os.path.dirname(os.path.realpath(__file__))
    settings = QSettings()
    locale = settings.value('Language')
    if locale is None or locale == '':
        locale = QLocale.system().name()
    appTranslator = QTranslator()
    if os.path.exists(filePath + '/translations/'):
        appTranslator.load(filePath + "/translations/meteo-qt_" + locale)
    else:
        appTranslator.load("/usr/share/meteo_qt/translations/meteo-qt_" +
                           locale)
    app.installTranslator(appTranslator)
    qtTranslator = QTranslator()
    qtTranslator.load("qt_" + locale,
                      QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qtTranslator)

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

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

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

    m = SystemTrayIcon()
    app.exec_()
def gui_mode():
    """
    Start NEFI2 GUI
    """
    extloader = ExtensionLoader()
    pipeline = Pipeline(extloader.cats_container, True)

    app = QApplication(sys.argv)

    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
    app.setQuitOnLastWindowClosed(True)
    wnd = MainView(pipeline)
    wnd.load_dark_theme(app)
    wnd.show()

    sys.exit(app.exec_())
Example #13
0
def main():
    app = QApplication(sys.argv)
    if sys.platform == "win32":
        app.setFont(QFont("Tahoma", 9))
    app.setOrganizationName("Besteam")
    app.setOrganizationDomain("besteam.im")
    app.setApplicationName("QuickPanel")
    app.setQuitOnLastWindowClosed(False)
    app.setWindowIcon(QIcon(":/images/angelfish.png"))
    #app.setStyle(QStyleFactory.create("qtcurve"))
    platform = Platform()
    platform.start()
    try:
        getattr(app, "exec")()
    except AttributeError:
        getattr(app, "exec_")()
Example #14
0
def start():
    start_logging()

    # will end application if an instance is already running
    singleton = SingleInstance(callback=running_warning)

    min_version = None
    # Then, if the current version is too old, close the program
    try:
        r = requests.get(settings.MIN_VERSION_URL, timeout=10)
    except requests.exceptions.ConnectionError:
        logger.warning('Check for minimum version requirements for OSF-Sync failed '
                       'because you have no Internet connection')
    else:
        try:
            min_version = r.json()['min-version']
        except KeyError as e:
            logger.exception(e)

    if min_version:
        if StrictVersion(settings.VERSION) < StrictVersion(min_version):
            # User error message
            running_warning(message='You must update to a newer version. '
                                    'You can find newest version at {}'
                            .format(settings.OFFLINE_PROJECT_ON_OSF),
                            critical=True)
            sys.exit(1)

    # Start logging all events
    if '--drop' in sys.argv:
        drop_db()

    app = QApplication(sys.argv)

    # connect QT to handle system shutdown signal from os correctly
    app.aboutToQuit.connect(exit_gracefully)

    if not QSystemTrayIcon.isSystemTrayAvailable():
        QMessageBox.critical(None, 'Systray', 'Could not detect a system tray on this system')
        sys.exit(1)

    QApplication.setQuitOnLastWindowClosed(False)

    if not OSFOfflineQT(app).start():
        return sys.exit(1)
    return sys.exit(app.exec_())
Example #15
0
    def gui_mode():
        """
        Start NEFI2 GUI
        """
        myappid = 'nefi2.0' # arbitrary string
        if sys.platform == 'win32' or sys.platform == 'win64':
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

        extloader = ExtensionLoader()
        pipeline = Pipeline(extloader.cats_container)
        app = QApplication(sys.argv)
        app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
        app.setQuitOnLastWindowClosed(True)
        app.setWindowIcon(QtGui.QIcon(os.path.join('icons', 'nefi2.ico')))
        wnd = MainView(pipeline)
        wnd.load_dark_theme(app)
        wnd.show()
        sys.exit(app.exec_())
Example #16
0
    def __init__(self):
        app = QApplication(sys.argv)
        app.setApplicationName("eKalappai")
        app.setApplicationVersion("4.0.0")
        shared = QSharedMemory("59698760-43bb-44d9-8121-181ecbb70e4d")

        if not shared.create(512, QSharedMemory.ReadWrite):
            qWarning("Cannot start more than one instance of eKalappai any time.")
            exit(0)
        splashImage = QPixmap(':intro/splash_screen')
        splashScreen = QSplashScreen(splashImage)
        splashScreen.show()
        time.sleep(2)
        splashScreen.hide()
        QApplication.setQuitOnLastWindowClosed(False)
        ekWindow = EKWindow()
        ekWindow.engine.start()
        sys.exit(app.exec_())
Example #17
0
def main():
    # Create and parse the command-line arguments
    parser = argparse.ArgumentParser(description='Linux Show Player')
    parser.add_argument('-f', '--file', default='', help="Session file path")
    parser.add_argument('-l', '--log', choices=['debug', 'info', 'warning'],
                        default='warning', help='Log level')

    args = parser.parse_args()

    # Set the logging level
    if args.log == 'debug':
        log = logging.DEBUG
    elif args.log == 'info':
        log = logging.INFO
    else:
        log = logging.WARNING

    logging.basicConfig(format='%(levelname)s:: %(message)s', level=log)

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

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

    # Create the application
    LiSP_app = Application()
    # Load modules and plugins
    modules.load_modules()
    plugins.load_plugins()
    # Start the application
    LiSP_app.start(session_file=args.file)

    # Start the application
    sys.exit(_exec(app, LiSP_app))
Example #18
0
    def __init__(self, config, use_qt_notifications):

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

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

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

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

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

        QApplication.setQuitOnLastWindowClosed(False)

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

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

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

        self._win = MainWindow(self._engine, use_qt_notifications)
Example #19
0
def start():
	app = QApplication(sys.argv)
	app.setOrganizationName(globals.ORGANIZATION_NAME)
	app.setOrganizationDomain(globals.ORGANIZATION_DOMAIN)
	app.setApplicationName(globals.APPLICATION_NAME)

	if isMacintoshComputer():
		# add /opt/local/bin to PATH to find pdflatex binary -- useful for Mac plateform using Macports
		os.environ['PATH'] = os.environ.get('PATH', '/usr/bin') + ':/opt/local/bin'
		app.setQuitOnLastWindowClosed(False)

	app_controller = ControllerFactory.createAppController()

	args = app.arguments()[1:]
	if len(args) > 0:
		for file_path in args:
			app_controller.open(file_path)
	else:
		app_controller.new()

	app.exec_()
	app_controller.quit()
Example #20
0
    def exec(self):
        """
        start the mailchecker
        """
        app = QApplication(sys.argv)

        # create new tray icon passing 6 param
        # PARAM 1: action for right click menu - on quit
        # PARAM 2: action for right click menu - check for new emails
        # PARAM 3: action for right click menu - show settings dialog
        # PARAM 4: icon for no new emails state
        # PARAM 5: icon for existance of unread/new emails
        # PARAM 6: icon for error state
        self.__tray_icon = MailChecker_UI_TrayIcon(app.quit,
                                                   self.__check_all_accounts_for_new_emails,
                                                   self. __show_settings_dialog,
                                                   self.settings.read(MailChecker_Settings_Options.icon_normal),
                                                   self.settings.read(MailChecker_Settings_Options.icon_new_email),
                                                   self.settings.read(MailChecker_Settings_Options.icon_error))
        # TODO: find a better way
        self.__tray_icon.set_onLeftClick_action(
            self.settings.read(MailChecker_Settings_Options.on_click))

        accounts_data = self.account_manager.get_all_accounts_data()

        if accounts_data:
            for account_data in accounts_data:
                # email_address: str, password: str, imap: str, mailbox: str
                self.__activate_account(account_data['nickname'],
                                        account_data['email_address'],
                                        account_data['password'],
                                        account_data['imap'],
                                        account_data['mailbox'],
                                        account_data['timeout'])

        self.__tray_icon.show()
        QApplication.setQuitOnLastWindowClosed(False)
        app.exec_()
Example #21
0
class FileViewApplication:

    def __init__(self) -> None:
        # Allow Ctrl-C killing of the Qt app, see:
        # http://stackoverflow.com/questions/4938723/
        signal.signal(signal.SIGINT, signal.SIG_DFL)

        self.cache_dir = os.path.join(xdg.BaseDirectory.xdg_cache_home, "dt-fileview")
        self.config_dir = os.path.join(xdg.BaseDirectory.xdg_config_home, "dt-fileview")
        self.config_file = os.path.join(self.config_dir, "config.ini")
        if not os.path.isdir(self.config_dir):
            os.makedirs(self.config_dir)

        self.stream_dir = os.path.join(self.cache_dir, "streams")
        if not os.path.isdir(self.stream_dir):
            os.makedirs(self.stream_dir)

        logging_config = os.path.join(self.config_dir, "logging.ini")
        if os.path.exists(logging_config):
            print("loading logger config from: {}".format(logging_config))
            try:
                logging.config.fileConfig(logging_config,
                                          defaults=None, disable_existing_loggers=False)
            except Exception as err:
                print(traceback.format_exc())

        settings.init(self.config_file)

        self.file_history = SqlHistory(os.path.join(self.config_dir, "file.sqlite"))
        self.location_history = SqlHistory(os.path.join(self.config_dir, "locations.sqlite"))
        self.bookmarks = Bookmarks(os.path.join(self.config_dir, "bookmarks.txt"))

        QPixmapCache.setCacheLimit(102400)

        self.qapp = QApplication([])
        self.qapp.setQuitOnLastWindowClosed(False)
        self.qapp.lastWindowClosed.connect(self.on_last_window_closed)

        self.stream_manager = StreamManager(self.stream_dir)
        self.vfs = VirtualFilesystem(self.cache_dir, self)
        self.executor = Executor(self)
        self.thumbnailer = Thumbnailer(self.vfs)
        self.metadata_collector = MetaDataCollector(self.vfs.get_stdio_fs())
        self.session_bus = QDBusConnection.sessionBus()
        self.dbus_thumbnail_cache = DBusThumbnailCache(self.session_bus)
        self.mime_database = MimeDatabase(self.vfs)
        self.mime_associations = XdgMimeAssociations.system()
        self.fs_operations = FilesystemOperations(self)
        self.fs = Filesystem()

        self.directory_thumbnailer = DirectoryThumbnailer(self)
        self.directory_thumbnailer.start()

        self.controllers: List[Controller] = []

        self.actions = ApplicationActions(self)
        self._preferences_dialog = PreferencesDialog()

    def on_last_window_closed(self) -> None:
        self.quit()

    def quit(self) -> None:
        self.close()
        self.qapp.quit()

    def run(self) -> int:
        return cast(int, self.qapp.exec())

    def close(self) -> None:
        self.directory_thumbnailer.close()

        self.file_history.close()
        self.location_history.close()

        settings.save()

        self.metadata_collector.close()
        self.thumbnailer.close()
        self.vfs.close()

    def close_controller(self, controller: 'Controller') -> None:
        self.controllers.remove(controller)
        controller.close()

    def new_controller(self) -> 'Controller':
        controller = Controller(self)
        controller._gui._window.show()
        self.controllers.append(controller)
        return controller

    def show_files(self, files: List[Location]) -> None:
        controller = Controller(self)
        controller.set_files(files)
        controller._gui._window.show()
        self.controllers.append(controller)

    def show_location(self, location: Location) -> None:
        self.location_history.append(location)

        controller = Controller(self)
        controller.set_location(location)
        controller._gui._window.show()
        self.controllers.append(controller)

    def set_filesystem_enabled(self, value):
        self.fs.set_enabled(value)
Example #22
0
def main():
    parser = setup_argparse()
    args = parser.parse_args()

    if args.version:
        print('feeluown {}, fuocore {}'.format(feeluown_version, fuocore_version))
        return

    if is_port_used(23333) or is_port_used(23334):
        print('\033[0;31m', end='')
        print('Port(23333 or 23334) is used, maybe another feeluown is running?')
        print('\033[0m', end='')
        sys.exit(1)

    debug = args.debug
    mpv_audio_device = args.mpv_audio_device
    cli_only = args.no_window
    logger_config(debug, to_file=args.log_to_file)

    load_rcfile()

    player_kwargs = dict(
        audio_device=bytes(mpv_audio_device, 'utf-8'))

    # 设置 exception hook
    sys.excepthook = excepthook

    if not cli_only:
        try:
            import PyQt5  # noqa
        except ImportError:
            logger.warning('PyQt5 is not installed,can only use CLI mode.')
            cli_only = True

    if not cli_only:
        from PyQt5.QtWidgets import QApplication
        from quamash import QEventLoop
        from feeluown.guiapp import GuiApp

        q_app = QApplication(sys.argv)
        q_app.setQuitOnLastWindowClosed(True)
        q_app.setApplicationName('FeelUOwn')

        app_event_loop = QEventLoop(q_app)
        asyncio.set_event_loop(app_event_loop)
        pubsub_gateway, pubsub_server = run_pubsub()

        app = GuiApp(pubsub_gateway, player_kwargs=player_kwargs)
        app.config = config
        # 初始化 UI 和组件间信号绑定
        app.initialize()
        # TODO: 调用 show 时,会弹出主界面,但这时界面还没开始绘制
        # 为了让提升启动速度,一些非必须的初始化操作可以在 show 之后进行
        app.show()
    else:
        from feeluown.app import CliApp

        pubsub_gateway, pubsub_server = run_pubsub()
        app = CliApp(pubsub_gateway, player_kwargs=player_kwargs)
        app.config = config
        app.initialize()

    bind_signals(app)

    event_loop = asyncio.get_event_loop()
    app.protocol.run_server()
    try:
        event_loop.run_forever()
        logger.info('Event loop stopped.')
    except KeyboardInterrupt:
        # NOTE: gracefully shutdown?
        pass
    finally:
        pubsub_server.close()
        event_loop.close()
Example #23
0
        self.browser.setUrl(QUrl(url))
        # 添加浏览器到窗口中
        self.setCentralWidget(self.browser)
    def goto(self,url):
        self.browser.setUrl(QUrl(url))

    def _downloadRequested(item):  # QWebEngineDownloadItem
        print('downloading to', item.path())
        item.accept()

if __name__ == '__main__':
    # pyqt窗口必须在QApplication方法中使用
    # 每一个PyQt5应用都必须创建一个应用对象.sys.argv参数是来自命令行的参数列表.Python脚本可以从shell里运行.这是我们如何控制我们的脚本运行的一种方法.
    app = QApplication(sys.argv)
    # 关闭所有窗口,也不关闭应用程序
    QApplication.setQuitOnLastWindowClosed(False)
    from PyQt5 import QtWidgets

    # QWidget窗口是PyQt5中所有用户界口对象的基本类.我们使用了QWidget默认的构造器.默认的构造器没有父类.一个没有父类的窗口被称为一个window.
    w = MainWindow("https://wx.qq.com/?&lang=zh")
    # show()方法将窗口显示在屏幕上.一个窗口是先在内存中被创建,然后显示在屏幕上的.
    w.show()

    # from PyQt5.QtWidgets import QSystemTrayIcon
    # from PyQt5.QtGui import QIcon
    # 在系统托盘处显示图标
    tp = QSystemTrayIcon(w)
    cur_path = os.path.dirname(os.path.realpath(__file__))
    config_path = os.path.join(cur_path, 'timg.jpeg')
    tp.setIcon(QIcon(config_path))
    # 设置系统托盘图标的菜单
Example #24
0
def ensure_data_dir():
    if not os.path.exists(FEELUOWN_PATH):
        os.mkdir(FEELUOWN_PATH)
    if not os.path.exists(CACHE_PATH):
        os.mkdir(CACHE_PATH)
    if not os.path.exists(DATA_PATH):
        os.mkdir(DATA_PATH)
    if not os.path.exists(SONGS_PATH):
        os.mkdir(SONGS_PATH)


if __name__ == "__main__":
    ensure_data_dir()

    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(True)
    app.setWindowIcon(QIcon(WINDOW_ICON))
    app.setApplicationName("FeelUOwn")
    app_event_loop = QEventLoop(app)
    asyncio.set_event_loop(app_event_loop)

    qss = QSS_PATH
    with open(qss, "r") as qssfile:
        app.setStyleSheet(qssfile.read())

    if MODE != DEBUG:
        f_handler = open(LOGFILE, 'w')
        sys.stdout = f_handler
        sys.stderr = f_handler

    w = Controller()
Example #25
0
def create_app(config):
    mode = config.MODE

    if mode & App.GuiMode:

        from PyQt5.QtCore import Qt, QDir
        from PyQt5.QtGui import QIcon, QPixmap
        from PyQt5.QtWidgets import QApplication, QWidget

        try:
            # HELP: QtWebEngineWidgets must be imported before a
            # QCoreApplication instance is created
            # TODO: add a command line option to control this import
            import PyQt5.QtWebEngineWidgets  # noqa
        except ImportError:
            logger.info('import QtWebEngineWidgets failed')

        from feeluown.utils.compat import QEventLoop

        pkg_root_dir = os.path.dirname(__file__)
        icons_dir = os.path.join(pkg_root_dir, 'icons')

        q_app = QApplication(sys.argv)
        QDir.addSearchPath('icons', icons_dir)

        q_app.setQuitOnLastWindowClosed(not config.ENABLE_TRAY)
        q_app.setApplicationName('FeelUOwn')

        app_event_loop = QEventLoop(q_app)
        asyncio.set_event_loop(app_event_loop)

        class GuiApp(QWidget):
            mode = App.GuiMode

            def __init__(self):
                super().__init__()
                self.setObjectName('app')
                QApplication.setWindowIcon(QIcon(
                    QPixmap('icons:feeluown.png')))

            def closeEvent(self, _):
                if not self.config.ENABLE_TRAY:
                    self.exit()

            def exit(self):
                self.ui.mpv_widget.close()
                event_loop = asyncio.get_event_loop()
                event_loop.stop()

            def mouseReleaseEvent(self, e):
                if not self.rect().contains(e.pos()):
                    return
                if e.button() == Qt.BackButton:
                    self.browser.back()
                elif e.button() == Qt.ForwardButton:
                    self.browser.forward()

        class FApp(App, GuiApp):
            def __init__(self, config):
                App.__init__(self, config)
                GuiApp.__init__(self)

    else:
        FApp = App

    Signal.setup_aio_support()
    Resolver.setup_aio_support()
    app = FApp(config)
    attach_attrs(app)
    Resolver.library = app.library
    return app
Example #26
0
        painter = QPainter(self)
        painter.setPen(Qt.red)
        x = int(self.width() / 2)
        y = int(self.height() / 2)
        painter.drawLine(x, 0, x, self.height())
        painter.drawLine(0, y, self.width(), y)
        if self.ismd:
            # 画坐标点
            pos = QCursor.pos()
            ret = win32gui.GetPixel(
                win32gui.GetWindowDC(win32gui.GetDesktopWindow()), pos.x(),
                pos.y())
            r, g, b = ret & 0xff, (ret >> 8) & 0xff, (ret >> 16) & 0xff
            print(r, g, b)
            painter.setPen(Qt.white)
            painter.drawText(
                self.rect(), Qt.AlignLeft | Qt.AlignBottom,
                '({}, {})\nRGB: ({}, {}, {})\n{}'.format(
                    pos.x(), pos.y(), r, g, b,
                    QColor(r, g, b).name()))


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(True)
    w = Label()
    w.show()
    sys.exit(app.exec_())
Example #27
0
def main():
	app = QApplication(sys.argv)
	QApplication.setQuitOnLastWindowClosed(False)
	ex = Onkyo()
	sys.exit(app.exec_())
Example #28
0
from PyQt5.QtWidgets import (QApplication, QWidget, QSystemTrayIcon, QMenu,
                             QAction)
from PyQt5.QtGui import QIcon
from client import client
from threading import Thread
import platform

ICON_FILE = 'keyboard-24' if platform.system() == 'Linux' else 'keyboard-16'

if __name__ == "__main__":

    app = QApplication([])
    app.setQuitOnLastWindowClosed(False)

    # Adding an icon
    icon = QIcon(ICON_FILE)

    # Adding item on the menu bar
    tray = QSystemTrayIcon()
    tray.setIcon(icon)
    tray.setVisible(True)

    # Creating the options
    menu = QMenu()

    # To quit the app
    quit = QAction("Quit")
    quit.triggered.connect(app.quit)
    menu.addAction(quit)

    # Adding options to the System Tray
Example #29
0
#!/usr/bin/python3
#-*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QApplication
import dialog

if __name__ == '__main__':
  app = QApplication(sys.argv)
  QApplication.setQuitOnLastWindowClosed(False)
  mainDialog = dialog.Dialog()
  mainDialog.show()
  sys.exit(app.exec_())
else:
  print("Useless!")
Example #30
0
 def __init__(self):
     QApplication.__init__(self, sys.argv)
     QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
     QApplication.setQuitOnLastWindowClosed(False)
Example #31
0
        window.setWindowFlags(MainWindowType | Qt.FramelessWindowHint | Qt.WindowStaysOnBottomHint)
        self.locked = True
        window.show()
        
    def dummy(self):
        print("settings.show")
        
    def closeEvent(self, event):
        SettingsSave()
        QApplication.instance().quit()
            
    def resizeEvent(self,event):
        programSettings.setValue("SizeX",window.geometry().width())
        programSettings.setValue("SizeY",window.geometry().height())
        
    def moveEvent(self,event):
        if SettingsExist() and (self.locked):
        # The following hack is for KWin 5.x because it can move even locked windows, even frameless windows. Now if you try to move locked window, it goes back.
            self.move(int(programSettings.value("PosX")),int(programSettings.value("PosY")))
            event.ignore()
        programSettings.setValue("PosX",window.x())
        programSettings.setValue("PosY",window.y())

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    QApplication.setQuitOnLastWindowClosed(True)
    window = Window()
    window.show()
    sys.exit(app.exec_())
if os.name == 'posix':
    QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads, True)

from PyQt5.QtQuick import QQuickView
from PyQt5.QtGui import (QSurfaceFormat, QColor, QImage,
    QPixmap, QCursor, QKeySequence, qRed, qGreen, qBlue)
from PyQt5.QtWidgets import QApplication, qApp, QFileDialog
from PyQt5.QtCore import (pyqtSlot, QStandardPaths, QUrl,
    QCommandLineParser, QCommandLineOption, QTimer, Qt)
from PyQt5.QtDBus import QDBusConnection, QDBusInterface
from PyQt5.QtMultimedia import QSoundEffect
app = QApplication(sys.argv)
app.setOrganizationName("Deepin")
app.setApplicationName("Deepin Screenshot")
app.setApplicationVersion("3.0")
app.setQuitOnLastWindowClosed(False)

from i18n import _
from window_info import WindowInfo
from menu_controller import MenuController
from settings import ScreenShotSettings
from dbus_services import is_service_exist, unregister_service
from dbus_interfaces import controlCenterInterface
from dbus_interfaces import notificationsInterface, socialSharingInterface
from constants import MAIN_QML, SOUND_FILE, MAIN_DIR, TMP_IMAGE_FILE

def init_cursor_shape_dict():
    global cursor_shape_dict

    file_name_except_extension = lambda x: os.path.basename(x).split(".")[0]
Example #33
0
        print("settings.show")

    def closeEvent(self, event):
        SettingsSave()
        QApplication.instance().quit()

    def resizeEvent(self, event):
        programSettings.setValue("SizeX", window.geometry().width())
        programSettings.setValue("SizeY", window.geometry().height())

    def moveEvent(self, event):
        if (self.locked):
            # The following hack is for KWin 5.x because it can move even locked windows, even frameless windows. Now if you try to move locked window, it goes back.
            if (SettingsExist()):
                self.move(int(programSettings.value("PosX")),
                          int(programSettings.value("PosY")))
            else:
                self.move(PosX, PosY)
            event.ignore()
        programSettings.setValue("PosX", window.x())
        programSettings.setValue("PosY", window.y())


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    QApplication.setQuitOnLastWindowClosed(True)
    window = Window()
    window.show()
    sys.exit(app.exec_())
Example #34
0
def main(argv):
    global server_thread
    print("Starting %s %s..." % (common.app_name, common.app_version))
    print("""         __
        /  \_
     __(     )_
   _(          \_
 _(              )_
(__________________)
""")
    app = QApplication(argv)
    
    network.setup()
    filtering.setup()
    
    # Create extension server.
    server_thread = extension_server.ExtensionServerThread(QCoreApplication.instance())
    
    # Start DBus loop
    if has_dbus:
        print("DBus available. Creating main loop...", end=" ")
        mainloop = DBusQtMainLoop(set_as_default = True)
        dbus.set_default_main_loop(mainloop)
        print("done.")
    else:
        print("DBus unavailable.")

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

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

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

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

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

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

    app.setWindowIcon(common.app_icon)

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

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

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

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

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

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

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

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

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

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

    settings.reload_extensions()
    settings.reload_userscripts()

    server_thread.setDirectory(settings.extensions_folder)

    # Start extension server.
    server_thread.start()

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

    # Load settings.
    data.loadData()

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

    common.desktop = QDesktopWidget()

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

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

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

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

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

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

    # Start app.
    print("Kon~!")
    sys.exit(app.exec_())
Example #35
0
class App:
    def __init__(self):
        print(
            f"{colors.PINK}{colors.BOLD}Welcome to Spotlightify{colors.RESET}\n\n"
        )

        self.app = QApplication([])
        self.app.setQuitOnLastWindowClosed(False)

        self.theme = default_themes["dark"]

        self.tray = None
        self.tray_menu = None
        self.action_open = None
        self.action_exit = None

        self.config = config

        self.spotlight = None
        self.spotify = None
        self.oauth = None
        self.token_info = None

        self.listener_thread = Thread(target=listener,
                                      daemon=True,
                                      args=(self.show_spotlight, ))
        self.song_queue = None
        self.image_queue = None
        self.cache_manager = None

        self.run()

    def run(self):
        print(self.config.username)
        if not self.config.is_valid():
            app = QApplication([])
            app.setQuitOnLastWindowClosed(True)
            auth = AuthUI()
            # ADD TUTORIAL WEBSITE webbrowser.open("https://alfred-spotify-mini-player.com/setup/", 2)
            while not self.config.is_valid():
                auth.show()
                app.exec_()
                if auth.isCanceled:
                    sys.exit()

        try:
            print("Starting auth process")
            self.oauth = self.config.get_oauth()
            self.token_info = self.oauth.get_access_token(as_dict=True)
            self.spotify = Spotify(auth=self.token_info["access_token"])

            self.init_tray()

            self.listener_thread.start()
            self.song_queue = SongQueue()
            self.image_queue = ImageQueue()
            self.cache_manager = CacheManager(self.spotify, self.song_queue,
                                              self.image_queue)

            self.spotlight = SpotlightUI(self.spotify, self.song_queue)

            self.show_spotlight()
            while True:
                self.app.exec_()

        except Exception as ex:
            print(ex)

    def init_tray(self):
        self.tray_menu = QMenu()

        self.action_open = QAction("Open")
        self.action_open.triggered.connect(self.show_spotlight)
        self.tray_menu.addAction(self.action_open)

        self.action_exit = QAction("Exit")
        self.action_exit.triggered.connect(App.exit)
        self.tray_menu.addAction(self.action_exit)

        self.tray = QSystemTrayIcon()
        self.tray.setIcon(QIcon(f"{ASSETS_DIR}img{sep}logo_small.png"))
        self.tray.setVisible(True)
        self.tray.setToolTip("Spotlightify")
        self.tray.setContextMenu(self.tray_menu)
        self.tray.activated.connect(
            lambda reason: self.show_spotlight(reason=reason))

    def show_spotlight(self, **kwargs):
        def focus_windows():  # Only way to focus UI on Windows
            mouse = Controller()
            # mouse position before focus
            mouse_pos_before = mouse.position
            # changing the mouse position for click
            target_pos_x = ui.pos().x() + ui.textbox.pos().x()
            target_pos_y = ui.pos().y() + ui.textbox.pos().y()
            mouse.position = (target_pos_x, target_pos_y)
            mouse.click(Button.left)
            mouse.position = mouse_pos_before

        if kwargs and kwargs["reason"] != 3:
            # if kwargs contains "reason" this has been invoked by the tray icon being clicked
            # reason = 3 means the icon has been left-clicked, so anything other than a left click
            # should open the context menu
            return

        ui = self.spotlight
        ui.show()
        ui.raise_()
        ui.activateWindow()
        ui.function_row.refresh(None)  # refreshes function row button icons
        self.token_refresh()

        if "Windows" in platform():
            focus_windows()

    def token_refresh(self):
        try:
            if self.oauth.is_token_expired(token_info=self.token_info):
                self.token_info = self.oauth.refresh_access_token(
                    self.token_info["refresh_token"])
                self.spotify.set_auth(self.token_info["access_token"])
        except:
            print("[WARNING] Could not refresh user API token")

    @staticmethod
    def exit():
        print(f"\n{colors.PINK}{colors.BOLD}Exiting{colors.RESET}")
        kill(getpid(), 3)
        exit(0)