Beispiel #1
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
Beispiel #2
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
Beispiel #3
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)
Beispiel #4
0
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()
Beispiel #5
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))
Beispiel #6
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))
        )
Beispiel #7
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()
Beispiel #8
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()))
Beispiel #9
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)
Beispiel #10
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
Beispiel #11
0
    def run(self) -> None:
        """ Start everything because the tray controls most of the components
        """
        try:
            self.tray = ps.Icon(
                "FOV Changer",
                icon=self.icon_image,
                title="FOV Changer",
                menu=ps.Menu(
                    ps.MenuItem("FOV Changer", self.void,
                                enabled=False), ps.Menu.SEPARATOR,
                    ps.MenuItem("Open Window", self.action),
                    ps.MenuItem("Enabled",
                                self.action,
                                checked=lambda item: self.states["Enabled"]),
                    ps.Menu.SEPARATOR, ps.MenuItem("Exit", self.action)))

            # Start GUI
            self.root_thread.start()

            # Start Processing stuff
            self.processing_thread.start()

            # Start tray
            Logger.log("System Tray", add=True)
            self.tray.run()
            Logger.log("System Tray", add=False)

            self.on_shutdown()

        except Exception:
            exceptions.handle_error(self.references)
Beispiel #12
0
def getToggleMenu():
    global keySoundOn
    if keySoundOn:
        return pystray.MenuItem('Disable ' + hv.shortcut_toggle,
                                onToggleViaTray, None, False, True, True)
    else:
        return pystray.MenuItem('Enable ' + hv.shortcut_toggle,
                                onToggleViaTray, None, False, True, True)
Beispiel #13
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)
     )
Beispiel #14
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
Beispiel #15
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)
Beispiel #16
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)
    def _init_systray(self, systray_icon_path):
        icon = Image.open(systray_icon_path)
        menu_open_log = pystray.MenuItem(
            'View log',
            lambda: self._open_file_with_associated_app(self._log_file_path))
        menu_quit = pystray.MenuItem('Quit', lambda: self.stop())

        menu = self._create_pystray_menu(menu_open_log, menu_quit)

        self.systray = pystray.Icon('Moonlight Desktop',
                                    icon=icon,
                                    title='Moonlight Desktop',
                                    menu=menu)
Beispiel #18
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()
Beispiel #19
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)
Beispiel #20
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)
Beispiel #21
0
 def __init__(self):
     # image for tray
     self._image = Image.open("tap.ico")
     # create
     self._menu = (pystray.MenuItem("Deploy", self.deploy),
                   pystray.MenuItem("Statistics", self.statistics),
                   pystray.MenuItem("Save", self.save),
                   pystray.MenuItem("Exit", self.exit))
     self._icon = pystray.Icon(name="Cliker",
                               icon=self._image,
                               title="Cliker",
                               menu=self._menu)
     # variable for determining the tray status
     self._status = None
Beispiel #22
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)
Beispiel #23
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
Beispiel #24
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)
Beispiel #25
0
def menu():
    for zone in soco.discover():

        def _mute():
            mute(zone)

        yield pystray.MenuItem(text=zone.player_name, action=_mute)
Beispiel #26
0
def normal_main():
    def sudo_execute(cmd):
        if platform == "darwin":
            pass
            # script_text = 'do shell script "{}" with administrator privileges'.format(cmd)
            # os.spawnlp(os.P_NOWAIT, 'osascript', 'osascript', '-e', script_text)
        else:
            os.spawnlp(os.P_NOWAIT, 'pkexec', 'pkexec', cmd)

    def setup(ico):
        ico.visible = True

    def shutdown(ico):
        ico.stop()

    def show(_ico):
        if platform == "darwin":
            os.spawnlp(os.P_NOWAIT, 'open', 'open', 'http://localhost:5000/')
        else:
            os.spawnlp(os.P_NOWAIT, 'xdg-open', 'xdg-open',
                       'http://localhost:5000/')

    def nfd_start(_ico):
        sudo_execute('nfd-start')

    def nfd_stop(_ico):
        sudo_execute('nfd-stop')

    menu = pystray.Menu(
        pystray.MenuItem('Show', show),
        pystray.Menu.SEPARATOR,
        pystray.MenuItem('NFD Start', nfd_start),
        pystray.MenuItem('NFD Stop', nfd_stop),
        pystray.Menu.SEPARATOR,
        pystray.MenuItem('Exit', shutdown),
    )

    icon = pystray.Icon('ndncc', menu=menu)
    img = Image.open('ndn_app.png')
    icon.icon = img

    app_thread = Thread(target=app_main)
    app_thread.daemon = True
    app_thread.start()

    icon.run(setup)
def update_menus(icon):
    # menu must be converted to a list to be mutable
    menu_list = list(icon.menu)
    menu_list[3] = pystray.MenuItem(
        "Time Passed: {}min {}sec".format(get_min_passed(), get_sec_passed()),
        get_sec_passed,
    )
    icon.menu = tuple(menu_list)
Beispiel #28
0
def main(argv):
    if os.path.exists(f"{here}/friends.txt"):
        with open(f"{here}/friends.txt", "r") as f:
            friends.extend(f.read().splitlines())

    menu = pystray.Menu(
        pystray.MenuItem("Launch", launch),
        pystray.MenuItem("Check now", check),
        pystray.MenuItem("Clear", clear),
        pystray.MenuItem("Quit", quit),
    )

    icon = pystray.Icon("TS Notifier",
                        icon=create_image(color_default),
                        title="TS Notifier",
                        menu=menu)
    icon.visible = True
    icon.run(run)
Beispiel #29
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()
Beispiel #30
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