Ejemplo n.º 1
0
    def _convert_psg_menu_to_tray(self, psg_menu):
        menu_items = []
        i = 0
        if isinstance(psg_menu, list):
            while i < len(psg_menu):
                item = psg_menu[i]
                look_ahead = item
                if i != (len(psg_menu) - 1):
                    look_ahead = psg_menu[i + 1]
                if not isinstance(item, list) and not isinstance(
                        look_ahead, list):
                    disabled = False
                    if item == sg.MENU_SEPARATOR_LINE:
                        item = pystray.Menu.SEPARATOR
                    elif item.startswith(sg.MENU_DISABLED_CHARACTER):
                        disabled = True
                        item = item[1:]
                    if not (item == pystray.Menu.SEPARATOR
                            and sg.running_linux()):
                        menu_items.append(
                            pystray.MenuItem(item,
                                             self._on_clicked,
                                             enabled=not disabled,
                                             default=False))
                elif look_ahead != item:
                    if isinstance(look_ahead, list):
                        if menu_items is None:
                            menu_items = pystray.MenuItem(
                                item,
                                pystray.Menu(*self._convert_psg_menu_to_tray(
                                    look_ahead)))
                        else:
                            menu_items.append(
                                pystray.MenuItem(
                                    item,
                                    pystray.Menu(
                                        *self._convert_psg_menu_to_tray(
                                            look_ahead))))
                i += 1
        # important item - this is where clicking the icon itself will go
        menu_items.append(
            pystray.MenuItem('default',
                             self._default_action_callback,
                             enabled=True,
                             default=True,
                             visible=False))

        return menu_items
Ejemplo n.º 2
0
Archivo: run.py Proyecto: ellet/PyleWM
def start():
    import ctypes
    if not ctypes.windll.shell32.IsUserAnAdmin():
        script_name = sys.argv[0]
        if not script_name.endswith(".py"):
            script_name = "-m pylewm"
        argument_str = " ".join((script_name, *sys.argv[1:]))
        ctypes.windll.shell32.ShellExecuteW(None, "runas", find_pythonw_executable(), argument_str, None, 1)
        sys.exit()
        return
    else:
        # Set up registry variables for running PyleWM correctly
        init_registry_vars()

    pylewm.config.apply()

    for fun in InitFunctions:
        fun()

    threading.Thread(target=key_process_thread, daemon=True).start()

    global tray_icon
    tray_icon = pystray.Icon('PyleWM')
    png_path = os.path.join(os.path.dirname(__file__), "PyleWM.png")
    tray_icon.icon = Image.open(png_path)
    tray_icon.title = "PyleWM"
    tray_icon.menu = pystray.Menu(
        pystray.MenuItem("Open Config Directory", lambda: run_pyle_command(pylewm.execution.open_config)),
        pystray.MenuItem("Restart", lambda: run_pyle_command(restart)),
        pystray.MenuItem("Quit", lambda: run_pyle_command(quit)),
    )
    tray_icon.run()
Ejemplo n.º 3
0
def setIconMenu():
    global icon
    icon.menu = pystray.Menu(
        getToggleMenu(), pystray.Menu.SEPARATOR,
        pystray.MenuItem('Info', onCredits),
        pystray.MenuItem('Donate', onDonate),
        pystray.MenuItem('Exit ' + hv.shortcut_exit, onQuit))
Ejemplo n.º 4
0
    def build_tray(self):
        """
        Creates the system tray icon.
        """
        try:
            image = Image.open('kodi-icon.ico')
        except FileNotFoundError:
            image = Image.new('RGB', (64, 64))
        menu = pystray.Menu(
            pystray.MenuItem("KoDiscord v{version}".format(
                version=Path('version').read_text().strip()),
                             self.reload_settings,
                             enabled=False),
            pystray.MenuItem(
                "Settings",
                self.open_settings,
            ),
            pystray.MenuItem("Autoboot",
                             self.auto_start_on_boot,
                             checked=lambda item: state),
            pystray.MenuItem(
                "Reload Settings",
                self.reload_settings,
            ),
            pystray.MenuItem("Exit", self.exit_app),
        )

        self._tray = pystray.Icon("KoDiscord", image, "KoDiscord", menu)

        self._tray.run()
Ejemplo n.º 5
0
def start_tray(background_function, shutdown_function):
    """Add an tray icon and is blocking the program. Must be called from the main thread."""
    global tray

    def background_wrapper(icon_):
        background_function()

    def _stop():
        """
        Stops synchronization. Tray keeps open
        """
        shutdown_function()

    def _close():
        """
        Stops synchronization and stops the tray.
        """
        shutdown_function()
        stop_tray()

    image = PIL.Image.open(c_paths.normalize_path(c_paths.ASSETS, "Logo.png"))
    menu = pystray.Menu(pystray.MenuItem("Open", _open_gui),
                        pystray.MenuItem("Stop", _stop),
                        pystray.MenuItem("Close", _close))
    tray = pystray.Icon("OpenDrive", image, "OpenDrive", menu)
    tray.icon = image
    tray.visible = True
    tray.run(background_wrapper)
Ejemplo n.º 6
0
 def withdraw_window(self):
     self.root.withdraw()
     image = Image.open(self.resource_path("mirror_assets/logo.png"))
     menu = pystray.Menu(item('Quit', self.quit_window),
                         item('Show', self.show_window, default=True))
     icon = pystray.Icon("Mirror", image, "Mirror", menu)
     icon.run()
Ejemplo n.º 7
0
    def __init__(self, title=program_settings.names['Program name']):
        self.running = False
        self.visible = False

        # Create icon
        self.icon = pystray.Icon(name=title, icon=title, title=title)

        # Use provided image as icon or generate default one
        try:
            image = Image.open('icon.ico')
        except IOError:
            print("Could not find icon file")
            image = None

        if image is not None:
            try:
                self.icon.icon = image
            except Exception as e:
                print(e)
                self.icon.icon = generate_icon()
        else:
            self.icon.icon = generate_icon()

        # Add entries to 'right click' menu
        self.icon.menu = pystray.Menu(pystray.MenuItem(text=program_settings.names['Program name'], action=lambda: None, default=True),
                                      pystray.MenuItem(text="Capture text", action=lambda: self.capture_text()),
                                      pystray.MenuItem(text="Exit", action=lambda: self.exit_program()))
Ejemplo n.º 8
0
    def start_client(self, addr):
        """Start up the client app
        
        """
        self.client = self.client_cls()

        self.loop = asyncio.new_event_loop()

        @net.protect_ssl(addr, retry=self.start_client)
        def target(addr):
            asyncio.set_event_loop(self.loop)
            self.loop.run_until_complete(self.client.connect(addr))

        logger.debug('Starting client thread')
        self.thread = threading.Thread(target=target)
        self.thread.start()

        logger.debug('Updating menu')
        menu = pystray.Menu(
            pystray.MenuItem("pymouseshift", None),
            pystray.MenuItem(f'Disconnect from {addr}', self.stop),
            pystray.MenuItem("Quit", self.quit))
        self.icon.menu = menu
        self.icon.update_menu()
        self.icon.icon = icon_filled
Ejemplo n.º 9
0
def run_sys_tray():
    import webbrowser
    import pystray
    from PIL import Image

    def _sys_tray_main(_icon: pystray.Icon):
        _icon.visible = True
        threading.Thread(target=_wait_server_ready,
                         args=[_open_browser]).start()
        run_server()

    def _open_browser():
        webbrowser.open(SERVER_URL)

    def _sys_tray_stop():
        shutdown_server()
        icon.visible = False
        icon.stop()

    icon = pystray.Icon(name='neteasy',
                        icon=Image.open('neteasy/static/image/logo-64.png'),
                        title='Neteasy Music Server',
                        menu=pystray.Menu(
                            pystray.MenuItem('Open',
                                             _open_browser,
                                             default=True),
                            pystray.MenuItem('Stop Server', _sys_tray_stop)))

    icon.run(_sys_tray_main)
Ejemplo n.º 10
0
    def __init__(self, title, menu):
        self.activates = {i: m.get('activate', self.activate) for i, m in enumerate(menu)}
        self.deactivates = {i: m.get('deactivate', self.deactivate) for i, m in enumerate(menu)}

        self.menu = []
        for m in menu:
            item = pystray.MenuItem(
                text=f'啟動 {m["title"]}',
                action=self.on_clicked,
                checked=lambda item: item.state
            )
            item.function = m.get('function', self.function)
            item.activate = m.get('activate', self.activate)
            item.deactivate = m.get('deactivate', self.deactivate)
            if m.get('function'):
                item.state = None
            else:
                item.state = True

            self.menu.append(item)

        self.icon = pystray.Icon(
            title,
            icon=Image.open('icon.png'),
            menu=pystray.Menu(*self.menu, pystray.MenuItem(text='關閉', action=self.stop))
        )
Ejemplo n.º 11
0
def createApp(io):
    def connectToServer():
        url = 'http://localhost:3333'
        headers = {'usertype': 'desktop', 'password': '******'}

        response = requests.get(url, headers=headers)

        jsonResponse = response.json()

        if (jsonResponse["status"] == 'permission accepted'):
            io.connect('http://localhost:3333')
        else:
            print(jsonResponse["status"])

    def disconnectFromServer(app):
        io.disconnect()
        app.stop()

    connectItem = pystray.MenuItem('Conectar', connectToServer)
    closeItem = pystray.MenuItem('Fechar', disconnectFromServer)

    menuApp = pystray.Menu(connectItem, closeItem)

    filename = abspath('assets/icon.png')
    iconImage = Image.open(filename)

    app = pystray.Icon('Mobile Keyboard', iconImage, menu=menuApp)

    return app
Ejemplo n.º 12
0
def createSystemTray():
    """
	Sends the script to run in the system tray.
	This method runs infinitely, until the program is stopped.
	"""

    image = Image.open("icon-64.png")
    menu = tray.Menu(
        tray.MenuItem("VI Arrow Keys", lambda: 1,
                      enabled=False),  # inactive item with the program's title
        tray.MenuItem('Enabled',
                      trayEnabledChanged,
                      checked=lambda item: gstate['enabled']),
        tray.MenuItem('Restart', trayRestartButton),
        tray.MenuItem('Quit/Exit', lambda: gstate['icon'].stop()
                      ),  # just calls icon.stop(), steps the whole program
    )

    gstate['icon'] = tray.Icon(
        "VI Arrow Keys", image, "VI Arrow Keys",
        menu)  # originally stored in "icon", stored globally though
    gstate['icon'].visible = True
    gstate['icon'].run(
        setup=traySetup
    )  # this creates an infinite loops and runs forever until exit here
Ejemplo n.º 13
0
 def _pystray_thread(self):
     self.tray_icon = pystray.Icon(self.title,
                                   self._create_image(self.icon))
     self.tray_icon.default_action = self._default_action_callback
     self.tray_icon.menu = pystray.Menu(*self.menu_items)
     self.tray_icon.title = self.tooltip  # tooltip for the icon
     self.thread_started = True
     self.tray_icon.run()
Ejemplo n.º 14
0
 def init_icon(self):
     self.withdraw()
     menu = []
     for name, lst in engine.tray_buttons.items():
         menu.append(MenuItem(name, partial(lst[0], self), **lst[1]))
     self.tray_icon = pystray.Icon("AutoClicker", self.tray_ico,
                                   "AutoClicker", pystray.Menu(*menu))
     self.tray_icon.run()
Ejemplo n.º 15
0
def main():
    image = Image.open("icon.png")

    menu = pystray.Menu(
        item('Clipboard Scrubber', scrub, default=True, enabled=False),
        pystray.Menu.SEPARATOR, item('Exit', exit))
    icon = pystray.Icon('clipboardscrubber', image, 'Clipboard Scrubber', menu)
    icon.run()
Ejemplo n.º 16
0
    def default_menu(self):
        #generate all the previous servers
        servers = []
        for server in config['servers']:

            def connect(icon, item):
                self.start_client(server)

            servers.append(pystray.MenuItem(server, connect))

        servers.append(pystray.MenuItem("+ Add new server", self.connect))
        client_menu = pystray.Menu(*servers)
        return pystray.Menu(
            pystray.MenuItem("pymouseshift", None),
            pystray.MenuItem("Start Server", self.start_server),
            pystray.MenuItem("Connect as client", client_menu),
            pystray.MenuItem("Quit", self.quit),
        )
Ejemplo n.º 17
0
def generateTrayIcon(release_func):
    global icon, icon_exist
    icon_exist = True
    icon = pystray.Icon('Speak Screenshot')
    ico = Image.open("../src/icon.ico")
    icon.icon = ico
    icon.menu = pystray.Menu(
        pystray.MenuItem('Resume', lambda: resume(release_func)))
    icon.run()
Ejemplo n.º 18
0
 def create_menu(self):
     self.menu = pystray.Menu(
         pystray.MenuItem('Settings', self.launch_settings),
         pystray.MenuItem(
             'Enabled',
             self.on_enabled,
             checked=lambda item: self.enabled
         ),
         pystray.MenuItem('Exit', self.terminate)
     )
Ejemplo n.º 19
0
    def __init__(self, config):
        self.config = config

        self.cwd = pathlib.WindowsPath(self.config['cwd'])

        self.status = 0

        # Prepare Tor
        self.password = uuid.uuid4().hex
        self.relay = tor.Tor(self.config['tor'], self.config['data'])

        # torrc
        torrc = pathlib.Path(config['data']) / 'torrc' / 'torrc'
        self.torrc = torrc.resolve()

        # The Onion Box
        self.box = box.TheOnionBox(config)

        # Stop signal, to terminate our run_loop
        self.stop = threading.Event()

        # the Tray icon
        self.tray = pystray.Icon('theonionpack', title='The Onion Pack')

        self.tray.icon = Image.open(str(self.cwd / 'icons' / 'top16.ico'))

        self.tray.menu = pystray.Menu(
            pystray.MenuItem('Monitor...',
                             action=self.on_monitor,
                             default=True), pystray.Menu.SEPARATOR,
            pystray.MenuItem(
                'Relay Control',
                pystray.Menu(
                    pystray.MenuItem('Edit configuration file...',
                                     action=self.on_open_torrc),
                    pystray.MenuItem('Show logfile...',
                                     action=self.on_show_messages),
                    pystray.Menu.SEPARATOR,
                    pystray.MenuItem('Reload relay configuration',
                                     action=self.on_reload_config))),
            pystray.Menu.SEPARATOR,
            pystray.MenuItem('Stop!', action=self.on_quit))
Ejemplo n.º 20
0
def create_icon():
    icon = pystray.Icon('AutoMO')
    icon.icon = Image.open(
        os.path.join(basedir, 'app', 'static', 'images', 'icon.ico'))
    icon.menu = pystray.Menu(
        pystray.MenuItem('Open {}:{}'.format(SERVER_HOST, SERVER_PORT),
                         on_open_site,
                         default=True), pystray.Menu.SEPARATOR,
        pystray.MenuItem('Exit', on_menu_exit))

    return icon
Ejemplo n.º 21
0
def create_tray_icon():
    def tray_exit_cb(icon):
        icon.visible = False
        icon.stop()

    icon = pystray.Icon('cafeden')
    icon.menu = pystray.Menu(
        pystray.MenuItem('Exit', lambda: tray_exit_cb(icon)), )
    icon.icon = Image.open(io.BytesIO(base64.b64decode(APP_ICO)))
    icon.title = 'cafeden'
    return icon
Ejemplo n.º 22
0
    def __init__(self):
        icon = pystray.Icon(
            "KSCollector",
            menu=pystray.Menu(
                pystray.MenuItem(
                    "Enabled",
                    on_activate,
                    default=True,
                    checked=lambda item: self.enabled,
                ),
                pystray.MenuItem("Quit", on_quit),
            ),
        )

        icon.icon = self.__generate_icon()
        img = self.__generate_icon("yellow")
        img.save("N.ico")
        self.icon = icon
        self.sequence = None
        self.actors = []
        self.stop_event = Event()
        self.user = g_user
        self.enabled = True
        self.dnaref = ActorSystem().createActor(
            DisplayNotificationActorNew, globalName="DisplayNotification")
        self.datastore = ActorSystem().createActor(DataStoreActor,
                                                   globalName="DataStore")
        self.downKeys = {}
        self.filters = []
        # Ugly hack that needs to be fixed eventually
        global KSAPP
        KSAPP = self

        if os.path.exists('filters.ini'):
            #Load the config file to get the filtered apps
            cfg = configparser.ConfigParser()
            cfg.read("filters.ini")

            if 'Filters' in cfg:
                if 'Apps' in cfg['Filters']:
                    apps = cfg['Filters']['Apps']
                    apps = list(map(lambda x: x.strip(), apps.split(',')))

                    for a in apps:
                        if a == '':
                            continue
                        self.filters.append(a)
        else:
            cfg = configparser.ConfigParser()
            cfg['Filters'] = {'Apps': ''}
            with open('filters.ini', 'w') as cfile:
                cfg.write(cfile)
Ejemplo n.º 23
0
    def __init__(self, app):
        dirname = os.path.dirname(__file__)
        filename = os.path.join(dirname, 'midi_keyboard_white.ico')
        img = PIL.Image.open(filename, 'r')
        print(filename)

        pystray.Icon.__init__(self, "Miduino", img, "Miduino")

        self.app = app

        max_btn = pystray.MenuItem("Maximize window", self.max_win)
        quit_btn = pystray.MenuItem("Quit", self.quit_app)
        self.menu = pystray.Menu(max_btn, quit_btn)
Ejemplo n.º 24
0
 def tasks_menu():
     for task in self.tasks:
         task_menu = pystray.Menu(
             pystray.MenuItem(task.description, on_log_click(task)),
             pystray.Menu.SEPARATOR,
             pystray.MenuItem(f"Next run: {time_diff(task.next_run)}",
                              lambda: 1),
             pystray.MenuItem(f"Last run: {time_diff(task.last_run)}",
                              on_log_click(task)),
             pystray.Menu.SEPARATOR,
             pystray.MenuItem("Run Now", on_run_now_click(task)),
         )
         yield pystray.MenuItem(task.name, task_menu)
Ejemplo n.º 25
0
def run_systray_icon():
    icon = pystray.Icon('test name')
    icon.title = APP_NAME
    icon.icon = Image.open(resource_path('src/icon.png'))
    icon.menu = pystray.Menu(
        pystray.MenuItem(text='Options', action=open_ui, default=True),
        pystray.MenuItem(text='Next photo', action=Options.set_wallpaper_next),
        pystray.MenuItem(text='Previous photo',
                         action=Options.set_wallpaper_prev),
        pystray.MenuItem(text='Random photo',
                         action=Options.set_wallpaper_random))

    icon.run()
Ejemplo n.º 26
0
def main():
    global all_processes, icon
    multiprocessing.freeze_support()
    all_processes = []
    icon = pystray.Icon('test name',
                        Image.open(tray_icon_fp),
                        menu=pystray.Menu(
                            pystray.MenuItem('Quit', quit),
                            pystray.MenuItem('Refresh', reload),
                            pystray.MenuItem('Settings', settings_click),
                        ))

    icon.run(setup=setup)
Ejemplo n.º 27
0
    def __init__(self):
        print('starting ED watcher...')

        self.terminate = False

        # test if config path and file exists
        Path(CONFIG_DIR).mkdir(exist_ok=True, parents=True)
        if not Path(CONFIG_PATH).exists():
            with open(CONFIG_PATH, 'w') as f:
                f.write(
                    json.dumps({
                        'last_submitted': '',
                        'notifications': True,
                    }))
        self.conf = None
        try:
            with open(CONFIG_PATH, 'r') as f:
                self.conf = json.loads(f.read())
        except:
            print('ERROR: Can not parse config file.')
            quit(1)

        print('last submitted entry was %s' % self.conf['last_submitted'])
        self.watch_file = None
        self.entries_to_submit = []
        self.submit_entry_lock = Lock()
        self.last_submitted_lock = Lock()
        self.file_watcher = None
        self.notifier = ToastNotifier()
        self.submit_watcher = SubmitWatcher(self.update_last_submitted,
                                            self.notifier,
                                            self.conf['notifications'])
        t = Thread(target=self.submit_watcher.loop)
        self.threads = [t]
        t.start()

        icon_image = Image.open(ICON_PATH)
        exit_item = pystray.MenuItem(enabled=True,
                                     text='Exit',
                                     action=self.exit)
        notification_item = pystray.MenuItem(
            enabled=True,
            text='Notifications',
            action=self.toggle_notifications,
            checked=lambda item: self.conf['notifications'])
        tray_menu = pystray.Menu(exit_item, notification_item)
        self.icon = pystray.Icon(name='EDWatcher',
                                 icon=icon_image,
                                 title="EDWatcher",
                                 menu=tray_menu)
Ejemplo n.º 28
0
def interactive(msg: str):

    icon = pystray.Icon("ytpldiff",
                        icon=_make_icon(),
                        title="ytpldiff",
                        menu=pystray.Menu(
                            pystray.MenuItem("continue",
                                             lambda icon, _: icon.stop(),
                                             default=True)))

    def setup(icon):
        icon.visible = True
        icon.notify(msg)

    icon.run(setup=setup)
Ejemplo n.º 29
0
    def sicon_thread(self):
        self._log.debug("Icon image wird gezeichnet...")
        img, colors = self.image()

        self._log.debug("Erstelle initales Menü...")
        items: list[pystray.MenuItem] = []
        items.append(pystray.MenuItem("Warte auf verbindung...", None))
        items.append(pystray.Menu.SEPARATOR)
        items.append(pystray.MenuItem("Beenden", self.killPluginManager))
        self._menuItemsInit = tuple(items)

        self._menu = pystray.Menu(*items)

        self._log.debug("Beginne mit dem mainloop von pysystray...")
        self._sicon = pystray.Icon("mqttScripts", icon=img, menu=self._menu)
        self._sicon.run(setup=self.icon_created)