def _initSystemTray(self, withMenu: bool = False):
        LOG.info("Initializing the system tray: available: %s, messages: %s",
                 QSystemTrayIcon.isSystemTrayAvailable(),
                 QSystemTrayIcon.supportsMessages())

        if not QSystemTrayIcon.isSystemTrayAvailable():
            return

        systemTrayIcon = QSystemTrayIcon(QIcon('assets/logo.png'), self._app)
        systemTrayIcon.setToolTip("The Deep Visualization Toolbox")
        systemTrayIcon.activated.connect(self.onSystemTrayActivated)

        if withMenu:
            contextMenu = QMenu()
            contextMenu.aboutToShow.connect(self.onSystemTrayMenuAboutToShow)

            actionTest = QAction('Test', contextMenu)
            actionTest.triggered.connect(self.onSystemTrayMenuActionTriggered)
            systemTrayIcon.setContextMenu(contextMenu)

        if QSystemTrayIcon.supportsMessages():
            systemTrayIcon.\
                messageClicked.connect(self.onSystemTrayMessageClicked)

        systemTrayIcon.show()
示例#2
0
def is_system_tray_available():
    app = QApplication.instance()
    if app is None:
        app = QApplication([])
        tray = QSystemTrayIcon()
        is_available = tray.isSystemTrayAvailable()
        app.quit()
    else:
        tray = QSystemTrayIcon()
        is_available = tray.isSystemTrayAvailable()

    return is_available
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_()
示例#4
0
 def CreateTrayIcon(self):
     if not QSystemTrayIcon.isSystemTrayAvailable():
         self.log_text = "本系统不支持托盘图标!"
         self.logger.SendMessage("W", 3, self.log_cate, self.log_text, "S")
         return
     
     QApplication.setQuitOnLastWindowClosed(False) # 点击主界面关闭按钮将不会结束程序,需要从托盘菜单退出
     
     self.tray_icon_menu = QMenu()
     self.tray_icon_menu.addAction(self.action_show)
     self.tray_icon_menu.addAction(self.action_hide)
     self.tray_icon_menu.addSeparator()
     self.tray_icon_menu.addAction(self.action_about)
     self.tray_icon_menu.addAction(self.action_exit)
     
     self.tray_icon = QSystemTrayIcon()
     self.tray_icon.setContextMenu(self.tray_icon_menu)
     
     self.tray_icon.setToolTip(define.TRAY_POP_START_TITLE)
     self.tray_icon.setIcon(QIcon(define.DEF_ICON_SYSTEM_TRAY))
     
     self.tray_icon.messageClicked.connect(self.OnTrayIconMsgClicked)
     self.tray_icon.activated.connect(self.OnTrayIconClicked)
     
     self.action_show.setEnabled(False)
     self.action_hide.setEnabled(True)
     
     self.tray_icon.show()
     
     self.is_tray_icon_loaded = True
示例#5
0
    def __init__(self, icon, controller, publisher, parent=None):
        super().__init__(icon, parent)
        self.logger = logging.getLogger(' TrayIndicator')
        try:
            if not QSystemTrayIcon.isSystemTrayAvailable():
                raise EnvironmentError('System tray not available')
        except EnvironmentError as env_error:
            self.logger.critical('Error - System tray not available')
            message_tuple = [
                _('System tray not available.'),
                _('Worksets relies on the system tray - the application will terminate.\n\nPlease enable the system tray and try again.'
                  ), '', 'Critical', True
            ]
            publisher.user_message('MESSAGE', message_tuple)

        self.controller = controller
        self.publisher = publisher
        self.publisher.register(['UPDATED', 'INSERTED', 'REMOVED'], self,
                                self.update_menu)

        self.active_mw_dialog = None
        self.active_settings_dialog = None
        self.menu = QMenu(parent)
        # Work around since tray.activated signal doesn't work on Ubuntu Unity
        self.menu.aboutToShow.connect(self.icon_activated)
        self.build_menu()
        self.setContextMenu(self.menu)
示例#6
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()
示例#7
0
def show(main_window):
    """Show a system tray icon with a small icon."""
    _fix_unity_systray()
    icon = QIcon(multiplatform.get_path("logos/icon-192.png"))
    sti = QSystemTrayIcon(icon, main_window)
    if not sti.isSystemTrayAvailable():
        logger.warning("System tray not available.")
        return

    def showhide(_):
        """Show or hide the main window."""
        if main_window.isVisible():
            main_window.hide()
        else:
            main_window.show()

    _menu = QMenu(main_window)
    _act = _menu.addAction("Mostrar/Ocultar")
    _act.triggered.connect(showhide)
    _act = _menu.addAction("Acerca de")
    _act.triggered.connect(main_window.open_about_dialog)
    _act = _menu.addAction("Salir")
    _act.triggered.connect(main_window.on_close)
    sti.setContextMenu(_menu)
    sti.show()
示例#8
0
文件: main.py 项目: Aksem/KoffeeBreak
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
示例#9
0
def gui(start, config_file):
    if start:
        import sys
        from PyQt5.QtWidgets import QSystemTrayIcon
        from PyQt5.QtWidgets import QMessageBox
        from PyQt5.QtWidgets import QApplication
        from bot.utils.common import make_config_file, default_config
        from bot.duel_links_runtime import DuelLinkRunTime
        from bot.dl_gui import DuelLinksGui
        sip.setdestroyonexit(False)
        app = QApplication(sys.argv)

        if not QSystemTrayIcon.isSystemTrayAvailable():
            QMessageBox.critical(None, "Systray",
                                 "Systray not dected on system.")
            sys.exit(1)

        QApplication.setQuitOnLastWindowClosed(False)

        uconfig = default_config()
        uconfig.read(config_file)
        dlRuntime = setup_runtime(uconfig)
        dlRuntime.main()
        window = DuelLinksGui(dlRuntime, uconfig.get('locations', 'assets'))
        window.show()
        sys.exit(app.exec_())
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_()
示例#11
0
 def closeEvent(self, event):
     if (
         not settings.get_value("global/tray_enabled")
         or not QSystemTrayIcon.isSystemTrayAvailable()
         or self.close_requested
         or self.core_config.debug
         or self.force_close
     ):
         if not self.force_close:
             result = ask_question(
                 self,
                 QCoreApplication.translate(self.__class__.__name__, "Confirmation"),
                 QCoreApplication.translate("MainWindow", "Are you sure you want to quit ?"),
             )
             if not result:
                 event.ignore()
                 self.close_requested = False
                 return
             event.accept()
         else:
             event.accept()
         if self.tray:
             self.tray.hide()
         self.stop_core()
     else:
         if self.tray and not self.tray_message_shown:
             self.tray.showMessage(
                 "Parsec", QCoreApplication.translate("MainWindow", "Parsec is still running.")
             )
             self.tray_message_shown = True
         event.ignore()
         self.hide()
示例#12
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_())
示例#13
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_())
示例#14
0
def ui_main():
    import sys
    global wsettings, wabout

    app = QApplication(sys.argv)
    systemtray_timeout = 0

    # Check if DE supports system tray
    while not QSystemTrayIcon.isSystemTrayAvailable():
        systemtray_timeout += 1
        time.sleep(20)
        if systemtray_timeout == 5:
            QMessageBox.critical(
                None, "Mail notifier",
                "I couldn't detect any system tray on this system.")
            sys.exit(1)

    QApplication.setQuitOnLastWindowClosed(False)

    import signal
    signal.signal(signal.SIGTERM, signal_term_handler)

    wabout = About()
    wsettings = Settings()
    window = MyWindow()

    sys.exit(app.exec_())
示例#15
0
    def update_tray_icon(self, use_monochrome_icon):
        if not QSystemTrayIcon.isSystemTrayAvailable() or not self.tray_icon:
            return

        if use_monochrome_icon:
            self.tray_icon.setIcon(QIcon(QPixmap(get_image_path('monochrome_tribler.png'))))
        else:
            self.tray_icon.setIcon(QIcon(QPixmap(get_image_path('tribler.png'))))
        self.tray_icon.show()
示例#16
0
    def update_tray_icon(self, use_monochrome_icon):
        if not QSystemTrayIcon.isSystemTrayAvailable():
            return

        if use_monochrome_icon:
            self.tray_icon.setIcon(QIcon(QPixmap(get_image_path('monochrome_tribler.png'))))
        else:
            self.tray_icon.setIcon(QIcon(QPixmap(get_image_path('tribler.png'))))
        self.tray_icon.show()
示例#17
0
    def on_received_downloads(self, downloads):
        if not downloads:
            return  # This might happen when closing Tribler

        total_download = 0
        total_upload = 0
        self.received_downloads.emit(downloads)
        self.downloads = downloads

        download_infohashes = set()
        for download in downloads["downloads"]:
            if download["infohash"] in self.download_widgets:
                item = self.download_widgets[download["infohash"]]
            else:
                item = DownloadWidgetItem(self.window().downloads_list)
                self.download_widgets[download["infohash"]] = item

            item.update_with_download(download)

            # Update video player with download info
            video_infohash = self.window().video_player_page.active_infohash
            if video_infohash != "" and download["infohash"] == video_infohash:
                self.window().video_player_page.update_with_download_info(
                    download)

            total_download += download["speed_down"]
            total_upload += download["speed_up"]

            download_infohashes.add(download["infohash"])

            if self.window().download_details_widget.current_download is not None and \
                    self.window().download_details_widget.current_download["infohash"] == download["infohash"]:
                self.window(
                ).download_details_widget.current_download = download
                self.window().download_details_widget.update_pages()

        # Check whether there are download that should be removed
        toremove = set()
        for infohash, item in self.download_widgets.iteritems():
            if infohash not in download_infohashes:
                index = self.window().downloads_list.indexOfTopLevelItem(item)
                toremove.add((infohash, index))

        for infohash, index in toremove:
            self.window().downloads_list.takeTopLevelItem(index)
            del self.download_widgets[infohash]

        if QSystemTrayIcon.isSystemTrayAvailable():
            self.window().tray_icon.setToolTip(
                "Down: %s, Up: %s" %
                (format_speed(total_download), format_speed(total_upload)))
        self.update_download_visibility()
        self.schedule_downloads_timer()

        # Update the top download management button if we have a row selected
        if len(self.window().downloads_list.selectedItems()) > 0:
            self.on_download_item_clicked()
示例#18
0
文件: main.py 项目: minlexx/xnovacmd
 def create_tray_icon(self):
     if QSystemTrayIcon.isSystemTrayAvailable():
         logger.debug('System tray icon is available, showing')
         self.tray_icon = QSystemTrayIcon(QIcon(':/i/xnova_logo_32.png'), self)
         self.tray_icon.setToolTip(self.tr('XNova Commander'))
         self.tray_icon.activated.connect(self.on_tray_icon_activated)
         self.tray_icon.show()
     else:
         self.tray_icon = None
示例#19
0
文件: main.py 项目: minlexx/xnovacmd
 def create_tray_icon(self):
     if QSystemTrayIcon.isSystemTrayAvailable():
         logger.debug('System tray icon is available, showing')
         self.tray_icon = QSystemTrayIcon(QIcon(':/i/xnova_logo_32.png'),
                                          self)
         self.tray_icon.setToolTip(self.tr('XNova Commander'))
         self.tray_icon.activated.connect(self.on_tray_icon_activated)
         self.tray_icon.show()
     else:
         self.tray_icon = None
示例#20
0
    def __init__(self, parent: QObject = None) -> None:
        super().__init__(parent)
        if not QSystemTrayIcon.isSystemTrayAvailable():
            raise Error("No system tray available")
        if not QSystemTrayIcon.supportsMessages():
            raise Error("System tray does not support messages")

        self._systray = QSystemTrayIcon(self)
        self._systray.setIcon(objects.qapp.windowIcon())
        self._systray.messageClicked.connect(self._on_systray_clicked)
示例#21
0
    def show_in_tray_when_available(self):
        """Show status icon when system tray is available

		If available, show icon, otherwise, set a timer to check back later.
		This is a workaround for https://bugreports.qt.io/browse/QTBUG-61898
		"""
        if QSystemTrayIcon.isSystemTrayAvailable():
            self.tray.show()
        else:
            QtCore.QTimer.singleShot(1000, self.show_in_tray_when_available)
示例#22
0
    def isTrayAvailable(self):
        if TrayEngine in ("KDE", "Qt"):
            # Ask Qt
            return QSystemTrayIcon.isSystemTrayAvailable()

        if TrayEngine == "AppIndicator":
            # Ubuntu/Unity always has a systray
            return True

        return False
示例#23
0
 def delayed_start(self, event_count):
     if not QSystemTrayIcon.isSystemTrayAvailable():
         if event_count == 5:
             QMessageBox.critical(
                 None, "BuildNotify",
                 "I couldn't detect any system tray on this system.")
             sys.exit(1)
         self.timed_event.start()
     if not self.ready:
         self.ready = True
         self.run_app()
示例#24
0
    def __init__(self):
        super().__init__()
        self.ui = ui.Ui_MainWidget()
        self.ui.setupUi(self)
        self.monitors = []

        self.__enable = True

        self._start_pos = None
        self._end_pos = None
        self._is_drag = False
        self._press = False
        self._is_resize = False
        self._resize_direction = None
        self._margin = 10
        self.setMouseTracking(True)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.ui.label_wintitle.setText("Brightness Ctrl v%.1f" % version)
        shadow = QGraphicsDropShadowEffect(self)
        shadow.setOffset(0, 0)
        shadow.setColor(Qt.black)
        shadow.setBlurRadius(8)
        self.setGraphicsEffect(shadow)

        self.tray_icon = None
        self.tray_icon_menu = None
        if QSystemTrayIcon.isSystemTrayAvailable():
            self.tray_icon_menu = QMenu(self)
            restore_action = QAction("恢复主窗口", self)
            restore_action.triggered.connect(self.action_restore)
            self.tray_icon_menu.addAction(restore_action)
            self.tray_icon = QSystemTrayIcon(self)
            self.tray_icon.setContextMenu(self.tray_icon_menu)
            self.tray_icon.setIcon(QIcon(':/images/icon.ico'))
            self.tray_icon.show()
        self.ui.btn_exit.clicked.connect(self.slot_btn_exit)
        self.ui.tbtn_refresh.clicked.connect(self.slot_tbtn_refresh_clicked,
                                             Qt.DirectConnection)
        self.ui.btn_show_monitor_info.clicked.connect(
            self.slot_btn_show_monitor_info)
        self.ui.hsilder_brightness.valueChanged.connect(
            self.slot_hsilder_brightness_value_changed)
        self.ui.spinbox_brightness.valueChanged.connect(
            self.slot_spinbox_brightness_value_changed)
        self.ui.hsilder_contrast.valueChanged.connect(
            self.slot_hsilder_contrast_value_changed)
        self.ui.spinbox_contrast.valueChanged.connect(
            self.slot_spinbox_contrast_value_changed)
        self.tray_icon.activated.connect(self.slot_system_tray_activated)
        self.ui.btn_x.clicked.connect(self.close)
        self.ui.btn_x.setAttribute(Qt.WA_Hover, True)
        self.init_monitors()
示例#25
0
 def on_export_download_request_done(self, filename, data):
     dest_path = os.path.join(self.export_dir, filename)
     try:
         torrent_file = open(dest_path, "wb")
         torrent_file.write(data)
         torrent_file.close()
     except IOError as exc:
         ConfirmationDialog.show_error(self.window(),
                                       "Error when exporting file",
                                       "An error occurred when exporting the torrent file: %s" % str(exc))
     else:
         if QSystemTrayIcon.isSystemTrayAvailable():
             self.window().tray_icon.showMessage("Torrent file exported", "Torrent file exported to %s" % dest_path)
示例#26
0
def main():
    app = QApplication(sys.argv)

    if not QSystemTrayIcon.isSystemTrayAvailable():
        QMessageBox.critical(
            None, "Systray",
            "I couldn't detect any system tray on this system.")
        sys.exit(1)

    QApplication.setQuitOnLastWindowClosed(False)

    ex = Multitool()
    sys.exit(app.exec_())
示例#27
0
def main():

    d = getDateTime()

    # Global app
    app = QApplication(sys.argv)

    QApplication.setQuitOnLastWindowClosed(False)
    qIcon = QIcon('icons/shotty.png')
    app.setWindowIcon(qIcon)

    shotty = ShottyFullscreen()

    showNotification('Shotty', 'Running in the background')

    tray = QSystemTrayIcon()
    if tray.isSystemTrayAvailable():
        tray.setIcon(QIcon('icons/shotty.png'))
        tray.setVisible(True)
        tray.show()

        # Add a menu
        trayMenu = QMenu()
        region_screenshot_action = QAction(QIcon("icons/screenshot.png"),
                                           'Take region screenshot')
        full_screenshot_action = QAction(QIcon("icons/screenshot.png"),
                                         'Take screenshot')
        settings_action = QAction(QIcon("icons/settings.png"), 'Settings')
        about_action = QAction(QIcon("icons/info.png"), 'About')
        exit_action = QAction(QIcon("icons/exit.png"), 'Exit Shoty')

        exit_action.triggered.connect(app.exit)
        about_action.triggered.connect(shotty.showShottyAboutWindow)
        region_screenshot_action.triggered.connect(shotty.initUI)
        # We need to pass checked because connect passes
        # a bool arg as first param
        full_screenshot_action.triggered.connect(
            lambda checked, date=getDateTime(
            ), x1=-1, y1=-1, x2=-1, y2=-1, im=screenshot(
            ): shotty.saveScreenShot(date, x1, y1, x2, y2, im=im[:, :, :3]))
        trayMenu.addAction(region_screenshot_action)
        trayMenu.addAction(full_screenshot_action)
        trayMenu.addAction(settings_action)
        trayMenu.addAction(about_action)
        trayMenu.addAction(exit_action)

        tray.setContextMenu(trayMenu)
    else:
        print("[ERROR] Can't instantiate tray icon")

    sys.exit(app.exec_())
def main():
    app = QApplication(sys.argv)

    if not QSystemTrayIcon.isSystemTrayAvailable():
        QMessageBox.critical(QWidget(), '提示', '在这个操作系统上无法找到系统托盘')
        return app.exec_()

    QApplication.setQuitOnLastWindowClosed(False)

    # 创建主窗口
    main_window = MainWindow()
    # 显示主窗口
    main_window.show()
    return app.exec_()
示例#29
0
 def add_tray_icon(self):
     if not QSystemTrayIcon.isSystemTrayAvailable() or not settings.get_value(
         "global/tray_enabled", "true"
     ):
         return
     self.tray = QSystemTrayIcon(self)
     menu = QMenu()
     action = menu.addAction(QCoreApplication.translate(self.__class__.__name__, "Show window"))
     action.triggered.connect(self.show_top)
     action = menu.addAction(QCoreApplication.translate(self.__class__.__name__, "Exit"))
     action.triggered.connect(self.close_app)
     self.tray.setContextMenu(menu)
     self.tray.setIcon(QIcon(":/icons/images/icons/parsec.png"))
     self.tray.activated.connect(self.tray_activated)
     self.tray.show()
示例#30
0
    def run(self):
        with session_scope() as session:
            user = session.query(User).first()
            if not user:
                user = User(idx=str(uuid4()))
                session.add(user)
        self.main_window.show()

        # Check if DE supports system tray
        if not QSystemTrayIcon.isSystemTrayAvailable():
            QMessageBox.critical(
                None, "Error",
                "I couldn't detect any system tray on this system.")

        return self.app.exec_()
示例#31
0
def init_tray_icon(app_window):
    if not QSystemTrayIcon.isSystemTrayAvailable():
        QMessageBox.critical(
            None, APP_NAME, 'System tray is not supported, app will exit'
        )
        sys.exit(1)

    icon = QIcon(':/images/app.png')
    icon.setIsMask(True)

    tray_icon = QSystemTrayIcon(icon, app_window)
    tray_icon.activated.connect(
        lambda reason: tray_icon_activated(reason, app_window, tray_icon)
    )
    tray_icon.setToolTip(APP_NAME)
    return tray_icon
示例#32
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_())
示例#33
0
    def start(self):
        settings.load_configuration()
        settings.set_window_manager(self.window_manager)
        self.window_manager.start()
        self.audio_manager.start()

        app = QApplication(sys.argv)
        main_window = MainWindow()

        if not QSystemTrayIcon.isSystemTrayAvailable():
            QMessageBox.critical(None, self.APP_NAME,
                                 "I couldn't detect any system tray on this system.")
            sys.exit(1)

        app.setQuitOnLastWindowClosed(False)

        window = TrayWindow(main_window)
        sys.exit(app.exec_())
示例#34
0
def run(manager: Manager, testing: bool = False) -> Any:
    logger.info("Creating trayicon...")
    # print(QIcon.themeSearchPaths())

    app = QApplication(sys.argv)

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

    # Allow pixmaps (e.g. trayicon) to use higher DPI images to make icons less
    # blurry when fractional scaling is used
    app.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)

    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()
    if sys.platform == "darwin":
        icon = QIcon(":/black-monochrome-logo.png")
        # Allow macOS to use filters for changing the icon's color
        icon.setIsMask(True)
    else:
        icon = QIcon(":/logo.png")

    trayIcon = TrayIcon(manager, icon, widget, testing=testing)
    trayIcon.show()

    QApplication.setQuitOnLastWindowClosed(False)

    logger.info("Initialized aw-qt and trayicon succesfully")
    # Run the application, blocks until quit
    return app.exec_()
示例#35
0
 def __init__(self):
     super().__init__()
     self._supported = QSystemTrayIcon.isSystemTrayAvailable()
     self._context_menu = None
     self._enabled = False
     self._trayicon = None
     self._state_icons = {}
     for state in (
         'disconnected',
         'disabled',
         'enabled',
     ):
         icon = QIcon(':/state-%s.svg' % state)
         if hasattr(icon, 'setIsMask'):
             icon.setIsMask(True)
         self._state_icons[state] = icon
     self._machine = None
     self._machine_state = 'disconnected'
     self._is_running = False
     self._update_state()
示例#36
0
 def __init__(self):
     super().__init__()
     self._supported = QSystemTrayIcon.isSystemTrayAvailable()
     self._context_menu = None
     self._enabled = False
     self._trayicon = None
     self._state_icons = {}
     for state in (
         'disconnected',
         'disabled',
         'enabled',
     ):
         icon = QIcon(':/state-%s.svg' % state)
         if hasattr(icon, 'setIsMask'):
             icon.setIsMask(True)
         self._state_icons[state] = icon
     self._machine = None
     self._machine_state = 'disconnected'
     self._is_running = False
     self._update_state()
示例#37
0
    def __init__(self, device_name=None, container_path=None, key_file=None, mount_point=None):
        """ Command line arguments checks are done here to be able to display a graphical dialog with error messages .
            If no arguments were supplied on the command line a setup dialog will be shown.
            All commands will be executed from a separate worker process with administrator privileges that gets initialized here.
            :param device_name: The device mapper name
            :type device_name: str/unicode or None
            :param container_path: The path of the container file
            :type container_path: str/unicode or None
            :param key_file: The path of an optional key file
            :type key_file: str/unicode or None
            :param mount_point: The path of an optional mount point
            :type mount_point: str/unicode or None
        """
        super(MainWindow, self).__init__()

        self.luks_device_name = device_name
        self.encrypted_container = container_path
        self.key_file = key_file
        self.mount_point = mount_point

        self.worker = None
        self.is_waiting_for_worker = False
        self.is_unlocked = False
        self.is_initialized = False
        self.has_tray = QSystemTrayIcon.isSystemTrayAvailable()

        # L10n: program name - translatable for startmenu titlebar etc
        self.setWindowTitle(_('luckyLUKS'))
        self.setWindowIcon(QIcon.fromTheme('dialog-password', QApplication.style().standardIcon(QStyle.SP_DriveHDIcon)))

        # check if cryptsetup and sudo are installed
        not_installed_msg = _('{program_name} executable not found!\nPlease install, eg for Debian/Ubuntu\n`apt-get install {program_name}`')
        if not utils.is_installed('cryptsetup'):
            show_alert(self, not_installed_msg.format(program_name='cryptsetup'), critical=True)
        if not utils.is_installed('sudo'):
            show_alert(self, not_installed_msg.format(program_name='sudo'), critical=True)
        # quick sanity checks before asking for passwd
        if os.getuid() == 0:
            show_alert(self, _('Graphical programs should not be run as root!\nPlease call as normal user.'), critical=True)
        if self.encrypted_container and not os.path.exists(self.encrypted_container):
            show_alert(self, _('Container file not accessible\nor path does not exist:\n\n{file_path}').format(file_path=self.encrypted_container), critical=True)

        # only either encrypted_container or luks_device_name supplied
        if bool(self.encrypted_container) != bool(self.luks_device_name):
            show_alert(self, _('Invalid arguments:\n'
                               'Please call without any arguments\n'
                               'or supply both container and name.\n\n'
                               '<b>{executable} -c CONTAINER -n NAME [-m MOUNTPOINT]</b>\n\n'
                               'CONTAINER = Path of the encrypted container file\n'
                               'NAME = A (unique) name to identify the unlocked container\n'
                               'Optional: MOUNTPOINT = where to mount the encrypted filesystem\n\n'
                               'If automatic mounting is configured on your system,\n'
                               'explicitly setting a mountpoint is not required\n\n'
                               'For more information, visit\n'
                               '<a href="{project_url}">{project_url}</a>'
                               ).format(executable=os.path.basename(sys.argv[0]),
                                        project_url=PROJECT_URL), critical=True)

        # spawn worker process with root privileges
        try:
            self.worker = utils.WorkerMonitor(self)
            # start communication thread
            self.worker.start()
        except utils.SudoException as se:
            show_alert(self, format_exception(se), critical=True)
            return

        # if no arguments supplied, display dialog to gather this information
        if self.encrypted_container is None and self.luks_device_name is None:

            from luckyLUKS.setupUI import SetupDialog
            sd = SetupDialog(self)

            if sd.exec_() == QDialog.Accepted:
                self.luks_device_name = sd.get_luks_device_name()
                self.encrypted_container = sd.get_encrypted_container()
                self.mount_point = sd.get_mount_point()
                self.key_file = sd.get_keyfile()

                self.is_unlocked = True  # all checks in setup dialog -> skip initializing state
            else:
                # user closed dialog -> quit program
                # and check if a keyfile create thread has to be stopped
                # the worker process terminates itself when its parent dies
                if hasattr(sd, 'create_thread') and sd.create_thread.isRunning():
                    sd.create_thread.terminate()
                QApplication.instance().quit()
                return

        # center window on desktop
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

        # widget content
        main_grid = QGridLayout()
        main_grid.setSpacing(10)
        icon = QLabel()
        icon.setPixmap(QIcon.fromTheme('dialog-password', QApplication.style().standardIcon(QStyle.SP_DriveHDIcon)).pixmap(32))
        main_grid.addWidget(icon, 0, 0)
        main_grid.addWidget(QLabel('<b>' + _('Handle encrypted container') + '</b>\n'), 0, 1, alignment=Qt.AlignCenter)

        main_grid.addWidget(QLabel(_('Name:')), 1, 0)
        main_grid.addWidget(QLabel('<b>{dev_name}</b>'.format(dev_name=self.luks_device_name)), 1, 1, alignment=Qt.AlignCenter)

        main_grid.addWidget(QLabel(_('File:')), 2, 0)
        main_grid.addWidget(QLabel(self.encrypted_container), 2, 1, alignment=Qt.AlignCenter)

        if self.key_file is not None:
            main_grid.addWidget(QLabel(_('Key:')), 3, 0)
            main_grid.addWidget(QLabel(self.key_file), 3, 1, alignment=Qt.AlignCenter)

        if self.mount_point is not None:
            main_grid.addWidget(QLabel(_('Mount:')), 4, 0)
            main_grid.addWidget(QLabel(self.mount_point), 4, 1, alignment=Qt.AlignCenter)

        main_grid.addWidget(QLabel(_('Status:')), 5, 0)
        self.label_status = QLabel('')
        main_grid.addWidget(self.label_status, 5, 1, alignment=Qt.AlignCenter)

        self.button_toggle_status = QPushButton('')
        self.button_toggle_status.setMinimumHeight(34)
        self.button_toggle_status.clicked.connect(self.toggle_container_status)
        main_grid.setRowMinimumHeight(6, 10)
        main_grid.addWidget(self.button_toggle_status, 7, 1)

        widget = QWidget()
        widget.setLayout(main_grid)
        widget.setContentsMargins(10, 10, 10, 10)
        self.setCentralWidget(widget)

        # tray popup menu
        if self.has_tray:
            tray_popup = QMenu(self)
            tray_popup.addAction(QIcon.fromTheme('dialog-password', QApplication.style().standardIcon(QStyle.SP_DriveHDIcon)), self.luks_device_name).setEnabled(False)
            tray_popup.addSeparator()
            self.tray_toggle_action = QAction(QApplication.style().standardIcon(QStyle. SP_DesktopIcon), _('Hide'), self)
            self.tray_toggle_action.triggered.connect(self.toggle_main_window)
            tray_popup.addAction(self.tray_toggle_action)
            quit_action = QAction(QApplication.style().standardIcon(QStyle.SP_MessageBoxCritical), _('Quit'), self)
            quit_action.triggered.connect(self.tray_quit)
            tray_popup.addAction(quit_action)
            # systray
            self.tray = QSystemTrayIcon(self)
            self.tray.setIcon(QIcon.fromTheme('dialog-password', QApplication.style().standardIcon(QStyle.SP_DriveHDIcon)))
            self.tray.setContextMenu(tray_popup)
            self.tray.activated.connect(self.toggle_main_window)
            self.tray.show()

        self.init_status()
示例#38
0
    def __init__(self, core_args=None, core_env=None, api_port=None):
        QMainWindow.__init__(self)

        QCoreApplication.setOrganizationDomain("nl")
        QCoreApplication.setOrganizationName("TUDelft")
        QCoreApplication.setApplicationName("Tribler")
        QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)

        self.gui_settings = QSettings()
        api_port = api_port or int(get_gui_setting(self.gui_settings, "api_port", DEFAULT_API_PORT))
        dispatcher.update_worker_settings(port=api_port)

        self.navigation_stack = []
        self.tribler_started = False
        self.tribler_settings = None
        self.debug_window = None
        self.core_manager = CoreManager(api_port)
        self.pending_requests = {}
        self.pending_uri_requests = []
        self.download_uri = None
        self.dialog = None
        self.new_version_dialog = None
        self.start_download_dialog_active = False
        self.request_mgr = None
        self.search_request_mgr = None
        self.search_suggestion_mgr = None
        self.selected_torrent_files = []
        self.vlc_available = True
        self.has_search_results = False
        self.last_search_query = None
        self.last_search_time = None
        self.start_time = time.time()
        self.exception_handler_called = False
        self.token_refresh_timer = None
        self.shutdown_timer = None
        self.add_torrent_url_dialog_active = False

        sys.excepthook = self.on_exception

        uic.loadUi(get_ui_file_path('mainwindow.ui'), self)
        TriblerRequestManager.window = self
        self.tribler_status_bar.hide()

        self.token_balance_widget.mouseReleaseEvent = self.on_token_balance_click

        def on_state_update(new_state):
            self.loading_text_label.setText(new_state)

        self.core_manager.core_state_update.connect(on_state_update)

        self.magnet_handler = MagnetHandler(self.window)
        QDesktopServices.setUrlHandler("magnet", self.magnet_handler, "on_open_magnet_link")

        self.debug_pane_shortcut = QShortcut(QKeySequence("Ctrl+d"), self)
        self.debug_pane_shortcut.activated.connect(self.clicked_menu_button_debug)
        self.import_torrent_shortcut = QShortcut(QKeySequence("Ctrl+o"), self)
        self.import_torrent_shortcut.activated.connect(self.on_add_torrent_browse_file)
        self.add_torrent_url_shortcut = QShortcut(QKeySequence("Ctrl+i"), self)
        self.add_torrent_url_shortcut.activated.connect(self.on_add_torrent_from_url)

        # Remove the focus rect on OS X
        for widget in self.findChildren(QLineEdit) + self.findChildren(QListWidget) + self.findChildren(QTreeWidget):
            widget.setAttribute(Qt.WA_MacShowFocusRect, 0)

        self.menu_buttons = [self.left_menu_button_home, self.left_menu_button_search, self.left_menu_button_my_channel,
                             self.left_menu_button_subscriptions, self.left_menu_button_video_player,
                             self.left_menu_button_downloads, self.left_menu_button_discovered]

        self.video_player_page.initialize_player()
        self.search_results_page.initialize_search_results_page(self.gui_settings)
        self.settings_page.initialize_settings_page()
        self.subscribed_channels_page.initialize()
        self.edit_channel_page.initialize_edit_channel_page(self.gui_settings)
        self.downloads_page.initialize_downloads_page()
        self.home_page.initialize_home_page()
        self.loading_page.initialize_loading_page()
        self.discovering_page.initialize_discovering_page()
        self.discovered_page.initialize_discovered_page(self.gui_settings)
        self.channel_page.initialize_channel_page(self.gui_settings)
        self.trust_page.initialize_trust_page()
        self.token_mining_page.initialize_token_mining_page()

        self.stackedWidget.setCurrentIndex(PAGE_LOADING)

        # Create the system tray icon
        if QSystemTrayIcon.isSystemTrayAvailable():
            self.tray_icon = QSystemTrayIcon()
            use_monochrome_icon = get_gui_setting(self.gui_settings, "use_monochrome_icon", False, is_bool=True)
            self.update_tray_icon(use_monochrome_icon)

            # Create the tray icon menu
            menu = self.create_add_torrent_menu()
            show_downloads_action = QAction('Show downloads', self)
            show_downloads_action.triggered.connect(self.clicked_menu_button_downloads)
            token_balance_action = QAction('Show token balance', self)
            token_balance_action.triggered.connect(lambda: self.on_token_balance_click(None))
            quit_action = QAction('Quit Tribler', self)
            quit_action.triggered.connect(self.close_tribler)
            menu.addSeparator()
            menu.addAction(show_downloads_action)
            menu.addAction(token_balance_action)
            menu.addSeparator()
            menu.addAction(quit_action)
            self.tray_icon.setContextMenu(menu)
        else:
            self.tray_icon = None

        self.hide_left_menu_playlist()
        self.left_menu_button_debug.setHidden(True)
        self.top_menu_button.setHidden(True)
        self.left_menu.setHidden(True)
        self.token_balance_widget.setHidden(True)
        self.settings_button.setHidden(True)
        self.add_torrent_button.setHidden(True)
        self.top_search_bar.setHidden(True)

        # Set various icons
        self.top_menu_button.setIcon(QIcon(get_image_path('menu.png')))

        self.search_completion_model = QStringListModel()
        completer = QCompleter()
        completer.setModel(self.search_completion_model)
        completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.item_delegate = QStyledItemDelegate()
        completer.popup().setItemDelegate(self.item_delegate)
        completer.popup().setStyleSheet("""
        QListView {
            background-color: #404040;
        }

        QListView::item {
            color: #D0D0D0;
            padding-top: 5px;
            padding-bottom: 5px;
        }

        QListView::item:hover {
            background-color: #707070;
        }
        """)
        self.top_search_bar.setCompleter(completer)

        # Toggle debug if developer mode is enabled
        self.window().left_menu_button_debug.setHidden(
            not get_gui_setting(self.gui_settings, "debug", False, is_bool=True))

        # Start Tribler
        self.core_manager.start(core_args=core_args, core_env=core_env)

        self.core_manager.events_manager.torrent_finished.connect(self.on_torrent_finished)
        self.core_manager.events_manager.new_version_available.connect(self.on_new_version_available)
        self.core_manager.events_manager.tribler_started.connect(self.on_tribler_started)
        self.core_manager.events_manager.events_started.connect(self.on_events_started)
        self.core_manager.events_manager.low_storage_signal.connect(self.on_low_storage)
        self.core_manager.events_manager.credit_mining_signal.connect(self.on_credit_mining_error)
        self.core_manager.events_manager.tribler_shutdown_signal.connect(self.on_tribler_shutdown_state_update)

        self.core_manager.events_manager.upgrader_tick.connect(
            lambda text: self.show_status_bar("Upgrading Tribler database: " + text))
        self.core_manager.events_manager.upgrader_finished.connect(
            lambda _: self.hide_status_bar())

        self.core_manager.events_manager.received_search_result.connect(
            self.search_results_page.received_search_result)

        # Install signal handler for ctrl+c events
        def sigint_handler(*_):
            self.close_tribler()

        signal.signal(signal.SIGINT, sigint_handler)

        self.installEventFilter(self.video_player_page)

        # Resize the window according to the settings
        center = QApplication.desktop().availableGeometry(self).center()
        pos = self.gui_settings.value("pos", QPoint(center.x() - self.width() * 0.5, center.y() - self.height() * 0.5))
        size = self.gui_settings.value("size", self.size())

        self.move(pos)
        self.resize(size)

        self.show()
示例#39
0
        self.quitAction = QAction("&Quit", self,
                triggered=QApplication.instance().quit)

    def createTrayIcon(self):
         self.trayIconMenu = QMenu(self)
         self.trayIconMenu.addAction(self.minimizeAction)
         self.trayIconMenu.addAction(self.maximizeAction)
         self.trayIconMenu.addAction(self.restoreAction)
         self.trayIconMenu.addSeparator()
         self.trayIconMenu.addAction(self.quitAction)

         self.trayIcon = QSystemTrayIcon(self)
         self.trayIcon.setContextMenu(self.trayIconMenu)


if __name__ == '__main__':

    import sys

    app = QApplication(sys.argv)

    if not QSystemTrayIcon.isSystemTrayAvailable():
        QMessageBox.critical(None, "Systray",
                "I couldn't detect any system tray on this system.")
        sys.exit(1)

    QApplication.setQuitOnLastWindowClosed(False)

    window = Window()
    window.show()
    sys.exit(app.exec_())