Exemple #1
0
 def run_app(self):
     signal_handler = SignalHandler()
     signal_handler.register()
     message = check_update(suppress_uptodate=True)
     if message:
         logger.error(message)
     parser = MyArgumentParser(signal_handler=signal_handler)
     parser.configure()
     # first parse is just for debug
     result = parser.parser.parse_args(sys.argv[1:])
     debug = result.debug
     #
     rumps.debug_mode(debug)
     #
     result = parser.parser.parse_args(['-c'])
     vicki = Vicki(debug=debug, player_backend=result.player_backend)
     vicki.player.player.set_argparser(result)
     #
     self.console = Console()
     #
     self.queue = multiprocessing.Queue()
     vicki.player.start()
     self.vicki = vicki
     self.parser = parser
     self.__run_bg__()
     self.run()
Exemple #2
0
 def run_app(self):
     signal_handler = SignalHandler()
     signal_handler.register()
     message = check_update(suppress_uptodate=True)
     if message:
         logger.error(message)
     parser = MyArgumentParser(signal_handler=signal_handler)
     parser.configure()
     # first parse is just for debug
     result = parser.parser.parse_args(sys.argv[1:])
     debug = result.debug
     #
     rumps.debug_mode(debug)
     #
     result = parser.parser.parse_args(['-c'])
     vicki = Vicki(debug=debug, player_backend=result.player_backend)
     vicki.player.player.set_argparser(result)
     #
     self.console = Console()
     #
     self.queue = multiprocessing.Queue()
     vicki.player.start()
     self.vicki = vicki
     self.parser = parser
     self.__run_bg__()
     self.run()
Exemple #3
0
    def __init__(self):
        super(CpuUsageApp, self).__init__("CPU Usage App")
        rumps.debug_mode(False)
        self.menu = ['Show text']
        self.enable_text = True

        #CPU使用率グラフ作成
        self.time = np.arange(10)
        self.usage = np.zeros_like(self.time)
        self.mem = np.zeros_like(self.time)
        self.fig = plt.figure(figsize=(1, 1), dpi=100)
        self.ax = self.fig.add_subplot(111)
        self.ax.set_xlim(0, 9)
        self.ax.set_ylim(0, 100)
        self.ax.plot(self.time, self.usage, color="blue", lw=3)
        self.ax.plot(self.time, self.mem, color="gray", lw=3)
        plt.axis('off')

        #iconは一時保存ディレクトリに入れてアプリ終了後に消す
        self.tmp_dir = tempfile.mkdtemp()
        self.img_path = os.path.join(self.tmp_dir, 'cpu_usage.png')
        plt.savefig(self.img_path, transparent=True, dpi=100)

        #iconをセット
        self.icon = self.img_path
Exemple #4
0
    def about(self, welcome=False):
        res = osa_api.dialog_input(
            self.lang.menu_about if not welcome else self.lang.title_welcome,
            self.lang.description_about, Const.github_page)

        if isinstance(res, str):
            res = res.strip().lower()

        if res == ':export log':
            self.export_log()
        elif res == ':view log':
            p_console_app = '/System/Applications/Utilities/Console.app'
            system_api.open_url(p_console_app,
                                p_args=(Log.path_log, ),
                                new=True)
            system_api.open_url(p_console_app,
                                p_args=(Log.path_err, ),
                                new=True)
        elif res == ':check update':
            self.check_update(by_user=True, test=True)
        elif res == ':restart':
            self.restart()
        elif res == ':debug':
            rumps.debug_mode(True)
        elif res == Const.github_page.lower() and not welcome:
            system_api.open_url(Const.github_page)
        else:
            return res
Exemple #5
0
 def __init__(self):
     #初期設定
     super(TrainNext, self).__init__("TrainNext")
     rumps.debug_mode(True)
     self.menu = ["そのつぎ"]
     self.menu["そのつぎ"].add("なし")
     self.menu["そのつぎ"].add("なし")
     self.menu = ["運行情報"]
     self.menu["運行情報"].add("未取得")
     self.enable_text = False
     self.icon = "./icon.png"
Exemple #6
0
    def __init__(self, autostart=True, debug=False):
        # Set default values
        self.debug_mode = debug
        rumps.debug_mode(self.debug_mode)

        self.setting_file = SETTING_FILE
        self.plist_file = PLIST_FILE
        self.karabiner_json = KARABINER_JSON
        self.icon_set = ICON_SET
        self.icon_set_gray = ICON_SET_GRAY
        self.icons = self.icon_set

        # Read settings
        self.settings = {}
        self.read_settings()

        # Application setup
        super(VEM, self).__init__(type(self).__name__,
                                  title=None,
                                  icon=self.icons['insert'])
        self.menu = [
            'About',
            None,
            'Gray icon',
            None,
            'Set check interval',
            'Start at login',
            None,
            'Uninstall',
            None,
        ]

        # Other class variables

        if 'gray_icon' in self.settings and self.settings['gray_icon'] == '1':
            self.icons = self.icon_set_gray
            self.menu['Gray icon'].state = True
        else:
            self.icons = self.icon_set
            self.menu['Gray icon'].state = False

        if 'start_at_login' in self.settings\
                and self.settings['start_at_login'] == '1':
            self.menu['Start at login'].state = True
        else:
            self.menu['Start at login'].state = False

        # Set and start get_messages
        self.timer = rumps.Timer(
            self.check_karabiner,
            int(self.settings['interval'])
            if 'interval' in self.settings else CHECK_INTERVAL)
        if autostart:
            self.start()
Exemple #7
0
 def __init__(self, api):
     super().__init__(consts.LOADING_ICON)
     self.api = api
     self.last_data = None
     for key in consts.LABELS:
         if key == consts.KEY_SEPARATOR:
             self.menu.add(rumps.separator)
         else:
             self.add_menu(key)
     self.menu.add(rumps.separator)
     self.add_menu("Refresh Now...")
     self.add_menu("Debug")
     self.warns = set()
     rumps.debug_mode(True)
    def __init__(self):
        super(StatusBarApp, self).__init__(
            "SSHFS"
        )  # refers to parent base class without explicitly calling their intits methods
        self.menu = [
            rumps.MenuItem('Mount HPCC', callback=self.mount, key='q'),
            rumps.MenuItem('Unmount', callback=self.unmount), {
                "More info": {"ICER", "SSH KEYS"}
            }
        ]

        self.icon = 'icer.png'
        self.local_mount_point = "/Volumes"
        self.path = "/HPCC"
        self.login = getpass.getuser()
        rumps.debug_mode(True)
Exemple #9
0
def main():
    # Read the configuration file
    config_file = os.path.join(rumps.application_support(APP_TITLE),
                               'config.yaml')
    with open(config_file, 'r') as conf:
        try:
            config = yaml.safe_load(conf)
        except yaml.YAMLError as exc:
            print(exc)
            return

    # Setup our CTRL+C signal handler
    signal.signal(signal.SIGINT, _signal_handler)

    # Enable debug mode
    rumps.debug_mode(config['debug'])

    # Startup application
    SlackStatusBarApp(config).run()
Exemple #10
0
 def __init__(self):
     super().__init__()
     self.config = {
         "app_name": UNICODE,
         "add": f"{ADD_UNI} Add Entry",
         "delete": f"{REMOVE_UNI} Delete Entry",
         "view": f"{VIEW_UNI} View All",
     }
     self.pickle = PickleWrap(self.storage_file)
     self.pickle.checking_db_path()
     self.app = rumps.App(self.config["app_name"])
     self.entry = rumps.MenuItem(title=self.config["add"],
                                 callback=self.run_entry)
     self.delete = rumps.MenuItem(title=self.config["delete"],
                                  callback=self.delete_entry)
     self.view = rumps.MenuItem(title=self.config["view"],
                                callback=self.viewer)
     if self.get_level() == logging.DEBUG:
         rumps.debug_mode(True)
Exemple #11
0
 def __init__(self, work_interval=3600, nag_interval=60, debug=False):
     """
     Constructor.
     
     work_interval - integer, seconds. Time that will elapse before telling 
                     the user to take a break.
                     
     nag_interval - integer, seconds. After an initial notification, notifications
                    will increase in frequency - this setting controls how long
                    to wait between each subsequent notice.
     
     debug - boolean. Proxy for the rumps.debug function, turns on detailed 
             logging within rumps (log entries end up in the MacOS Console)
     """
     
     self.work_interval = work_interval
     self.nag_interval = nag_interval
     
     self.work_delta = datetime.timedelta(seconds=work_interval)
     self.nag_delta = datetime.timedelta(seconds=nag_interval)
     self.delta = self.work_delta
     
     self.checkin = datetime.datetime.now()
     
     self.app = rumps.App(
         "Break Timer", 
         icon=NORMAL_ICON)
     
     self.app.menu = [
         rumps.MenuItem('Stop', self.stop),
         rumps.MenuItem('Take Break', self.break_popup),
         rumps.MenuItem("Time Left", None)
     ]
     
     self.work_timer = rumps.Timer(self.take_break, 10)
     self.front_timer = rumps.Timer(self.bring_to_front, 10)
     self.time_left_timer = rumps.Timer(self.update_time_left, 45)
     
     self.nag = False
     self.paused = False       
     
     rumps.debug_mode(debug)
Exemple #12
0
def menu():
    """Show the app menu on the status bar."""
    from dontforget.default_pipes.gmail_plugin import GMailPlugin
    from dontforget.default_pipes.toggl_plugin import TogglPlugin

    if DEBUG:
        rumps.debug_mode(True)

    app = DontForgetApp()
    config_yaml = load_config_file()

    for plugin_class in (GMailPlugin, TogglPlugin):
        plugin = plugin_class(config_yaml)
        app.plugins.append(plugin)

        app.menu.add(plugin.name)
        app.menu.add(rumps.separator)
        if not plugin.init_app(app):
            sys.exit(1)
    app.create_preferences_menu()
    if not app.start_scheduler():
        sys.exit(2)
    app.run()
Exemple #13
0
    def __init__(self, log, quote, debug_mode):
        self.timer = rumps.Timer(self.on_tick, 1)
        self.log = log
        self.quote = quote
        self.debug_mode = debug_mode
        with open(self.log, 'a') as log_writer:  # append mode
            log_writer.write('raindrop.open: {}\n'.format(timez()))
        if self.debug_mode:
            rumps.debug_mode(True)  # rumps debug info is useful for dev and usage
        self.timer.stop()  # timer running when initialized
        self.timer.count = 0
        self.app = rumps.App("Raindrop", "💧")
        self.start_pause_button = rumps.MenuItem(title='Start Timer',
                                                 callback=lambda _: self.start_timer(_, self.interval))
        self.stop_button = rumps.MenuItem(title='Stop Timer',
                                          callback=None)
        self.buttons = {}
        self.buttons_callback = {}
        self.timer_list = [5, 10, 15, 20, 25]  # TODO(mofhu): maybe extend it later as an optional user input
        if self.debug_mode:
            self.timer_list.append(1)  # only add 1 min in debug mode

        for i in self.timer_list:
            title = str(i) + ' Minutes'
            callback = lambda _, j=i: self.set_mins(_, j)
            self.buttons["btn_" + str(i)] = rumps.MenuItem(title=title, callback=callback)
            self.buttons_callback[title] = callback
        self.interval = 5 * SEC_TO_MIN  # current 5 min by default
        self.buttons['btn_5'].state = True
        self.app.menu = [
            self.start_pause_button,
            None,
            # self.button_things,
            # None,
            *self.buttons.values(),
            None,
            self.stop_button]
Exemple #14
0
    def __init__(self):
        rumps.debug_mode(True)
        self.glitz = Glitz()

        self.config = {
            "app_name": "Glitz",
            "app_icon": "icons/app.png",
            "switch_icon": "icons/switch.png"
        }

        active_account = self.glitz.active_account if self.glitz.active_account != None else "No account active"

        menu = [
            rumps.MenuItem(title="app", template=True, callback=None),
            rumps.MenuItem(title="Switch",
                           icon=self.config["switch_icon"],
                           dimensions=(16, 16),
                           template=True)
        ]

        super(GlitzApp, self).__init__(name=self.config["app_name"],
                                       icon=self.config["app_icon"],
                                       template=True,
                                       menu=menu)
Exemple #15
0
    def __init__(self):
        super(RTNotifier, self).__init__("RT Notifier", icon='57365.png')
        self.config = None

        # Set user/password/url, either by asking or by getting from the config
        xdg_base = xdg.BaseDirectory.load_first_config(self.__class__.__name__)
        config_path = os.path.join(xdg_base, RTNotifier.CONFIG_NAME) if xdg_base else ''

        self.config = SafeConfigParser()
        if os.path.isfile(config_path):
            # Load config file
            with open(config_path) as f:
                self.config.readfp(f)
        else:
            self.config.add_section('main')
            if self.set_user_pass(None) and self.set_url(None) and self.set_renotify_time(None):
                self.save_config()
            else:
                rumps.quit_application()

        renotify_time = self.config.getint('main', 'renotify_time') * 60
        self.tickets = expiringdict.ExpiringDict(max_len=100, max_age_seconds=renotify_time)
        self.debug = False
        rumps.debug_mode(self.debug)
Exemple #16
0
class App(rumps.App):
    # pylint: disable=too-many-instance-attributes
    """Main app with rumps sub"""

    rumps.debug_mode(True)

    def __init__(self) -> None:
        super(App, self).__init__("Speck")
        self.token = ""
        self.spotify = ""
        self.state_prev = ""
        self.state = ""
        self.pause_count = 0
        self.track_data = {}
        self.menu = [
            "Pause/Play",
            None,
            "Next",
            "Previous",
            None,
            "Save to your Liked Songs",
            None,
            "Track Info",
            None,
        ]
        self.authorize_spotify()

    def authorize_spotify(self) -> None:
        """Authorization method used in stand up and checks"""
        self.token = util.prompt_for_user_token(
            USERNAME,
            scope=SCOPE,
            redirect_uri=REDIRECT_URI,
            client_id=CLIENT_ID,
            client_secret=CLIENT_SECRET,
        )
        self.spotify = spotipy.Spotify(auth=self.token,
                                       retries=MAX_RETRIES,
                                       status_retries=MAX_RETRIES)

        self.update_track()

    def __shorten_text(self, text: str) -> str:
        if len(text) > MAX_TRACK_LENGTH:
            text = text[0:MAX_TRACK_LENGTH] + "..."
        return text

    def __get_active_device(self) -> list:
        devices = self.spotify.devices()["devices"]
        active_devices = [
            device for device in devices if device["is_active"] is True
        ]

        if active_devices:
            active_device = active_devices[0]["id"]
        else:
            rumps.alert(
                title="No active sessions",
                message=
                "Start playing music on one of your devices and Speck will start up!",
            )
            active_device = None

        return active_device

    def __set_saved_track(self, track_id: str) -> None:
        menu_item = self._menu["Save to your Liked Songs"]

        if self.spotify.current_user_saved_tracks_contains([track_id
                                                            ])[0] is True:
            menu_item.title = "Remove from your Liked Songs"
        else:
            menu_item.title = "Save to your Liked Songs"
            menu_item.set_callback(self.add_remove_saved_track)

    def __get_playback_state(self) -> None:
        menu_item = self._menu["Pause/Play"]

        if self.track_data["is_playing"] is True:
            menu_item.title = "Pause"
        else:
            menu_item.title = "Play"
            menu_item.set_callback(self.pause_play_track)

    def __set_menu_playback_state(self,
                                  state: str,
                                  track: str = None,
                                  band: str = None) -> None:
        self.state = state

        if self.state != self.state_prev:
            self.icon = f"./resources/{state}.png"
        if state == "active":
            self.title = track + " · " + str(band)
            self.pause_count = 0
        elif state == "paused":
            self.title = track + " · " + str(band)
        else:
            self.title = str.capitalize(f"{state}")
        if self.state and self.state_prev == "paused":
            self.pause_count += 1

    @rumps.clicked("Track Info")
    def open_browser(self, sender) -> None:
        """Open web browser to search track information"""
        webbrowser.open(
            f'https://google.com/search?q={self.track_data["item"]["name"]}+{self.track_data["item"]["artists"][0]["name"]}'
        )

    @rumps.clicked("Save to your Liked Songs")
    def add_remove_saved_track(self, sender) -> None:
        "Add or remove playing track to Liked playlist"
        track_id = self.track_data["item"]["id"]
        if self.spotify.current_user_saved_tracks_contains([track_id
                                                            ])[0] is False:
            try:
                self.spotify.current_user_saved_tracks_add(tracks=[track_id])
                rumps.notification(
                    title="Saved to your liked songs",
                    subtitle=None,
                    message=
                    f'{self.track_data["item"]["artists"][0]["name"]} - {self.track_data["item"]["name"]}',
                )
            except SpotifyException:
                self.authorize_spotify()
        else:
            self.spotify.current_user_saved_tracks_delete([track_id])

    @rumps.clicked("Pause/Play")
    def pause_play_track(self, sender) -> None:
        """Pause or play track based on playback status"""
        try:
            if self.track_data is None or self.track_data[
                    "is_playing"] is False:
                self.spotify.start_playback(self.__get_active_device())
            else:
                self.spotify.pause_playback()
            self.update_track(self)
        except SpotifyException:
            self.authorize_spotify()

    @rumps.clicked("Next")
    def next_track(self, sender) -> None:
        """Next track"""
        try:
            self.spotify.next_track()
            time.sleep(0.25)
            self.update_track()
        except SpotifyException:
            self.authorize_spotify()

    @rumps.clicked("Previous")
    def prev_track(self, sender) -> None:
        """Previous track"""
        try:
            self.spotify.previous_track()
            time.sleep(0.25)
            self.update_track()
        except SpotifyException:
            self.authorize_spotify()

    @rumps.timer(UPDATE_INTERVAL)
    def update_track(self, sender=None) -> None:
        """Update the track data listed in menubar"""
        if self.token:
            try:
                self.track_data = self.spotify.current_user_playing_track()
            except SpotifyException:
                self.authorize_spotify()
                self.update_track()

            if self.track_data is not None:
                is_playing = self.track_data["is_playing"]
                artists = self.track_data["item"]["artists"]
                track_id = self.track_data["item"]["id"]
                band = []

                self.__get_playback_state()
                self.__set_saved_track(track_id)

                for artist in artists:
                    band.append(self.__shorten_text(artist["name"]))
                    track = self.__shorten_text(
                        self.track_data["item"]["name"])
                band = ", ".join(band)

                if is_playing is True:
                    time_left = (
                        int(self.track_data["item"]["duration_ms"]) / 1000 -
                        int(self.track_data["progress_ms"]) / 1000
                    )  # currently unused; TBU for better tracking without polling

                    self.state_prev = self.state
                    self.state = "active"

                else:  # Spotify is Paused
                    self.state_prev = self.state
                    self.state = "paused"

                self.__set_menu_playback_state(self.state, track, band)

            else:
                self.state = "sleeping"
                self.__set_menu_playback_state(self.state)
        else:
            self.__set_menu_playback_state("error")
Exemple #17
0
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

import multiprocessing
import sys

import rumps
rumps.debug_mode(True)

from voiceplay import __title__ as vp_title
from voiceplay.cli.argparser.argparser import MyArgumentParser, Help
from voiceplay.logger import logger
from voiceplay.utils.updatecheck import check_update
from voiceplay.utils.crashlog import send_traceback
from voiceplay.utils.helpers import SignalHandler
from voiceplay.recognition.vicki import Vicki

from voiceplay.cli.console.console import Console
from voiceplay.utils.command import Command
from voiceplay.utils.helpers import ThreadGroup, cmp


class VoicePlayApp(rumps.App):
    def __init__(self):
        super(VoicePlayApp, self).__init__(vp_title, quit_button=None)
        self.menu = ['Pause/Resume', 'Quit']

    @rumps.clicked('Pause/Resume')
    def pause_resume(self, _):
        try:
            self.console.parse_command('pause')
Exemple #18
0
import rumps
import time

rumps.debug_mode(True)  # turn on command line logging information for development - default is off


@rumps.clicked("About")
def about(sender):
    sender.title = 'NOM' if sender.title == 'About' else 'About'  # can adjust titles of menu items dynamically
    rumps.alert("This is a cool app!")


@rumps.clicked("Arbitrary", "Depth", "It's pretty easy")  # very simple to access nested menu items
def does_something(sender):
    my_data = {'poop': 88}
    rumps.notification(title='Hi', subtitle='There.', message='Friend!', sound=does_something.sound, data=my_data)
does_something.sound = True


@rumps.clicked("Preferences")
def not_actually_prefs(sender):
    if not sender.icon:
        sender.icon = 'level_4.png'
    sender.state = not sender.state
    does_something.sound = not does_something.sound


@rumps.timer(4)  # create a new thread that calls the decorated function every 4 seconds
def write_unix_time(sender):
    with app.open('times', 'a') as f:  # this opens files in your app's Application Support folder
        f.write('The unix time now: {}\n'.format(time.time()))
Exemple #19
0
import webbrowser

#------------------------------------------------------
# iBrew
#
# Taskbar Launcher MacOS
#
# https://github.com/Tristan79/iBrew
#
# Copyright © 2017 Tristan (@monkeycat.nl). All Rights Reserved
#
# The Dream Tea
#------------------------------------------------------

rumps.debug_mode(
    False
)  # turn on command line logging information for development - default is off


class MacGui(rumps.App):
    def __init__(self, apiServer):
        super(MacGui, self).__init__("iBrew",
                                     icon=AppFolders.iconsPath("logo.png"),
                                     quit_button=None)
        self.apiServer = apiServer
        self.menu = [
            'Interface',
            #          None,
            #          'Tea',
            None
        ]
        dimensions=(320, 22),
    )
    window.default_text = config.get_host()
    window.add_buttons('Cancel')

    response = window.run()
    if response.clicked == 1:
        config.set_host(response.text.strip())
        update_data(None)

def open_project_homepage(sender):
    webbrowser.open_new(PROJECT_HOMEPAGE)

def open_nightscout_url(sender):
    webbrowser.open_new(config.get_host())

def choose_units_mgdl(sender):
    config.set_use_mmol(False)
    update_data(None)

def choose_units_mmol(sender):
    config.set_use_mmol(True)
    update_data(None)

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == '--debug':
        rumps.debug_mode(True)
    app = rumps.App(APP_NAME, title='<Connecting to Nightscout...>')
    app.menu = ['connecting...'] + post_history_menu_options()
    app.run()
Exemple #21
0
    def __init__(self, autostart=True):
        # Set default values
        self.debug_mode = DEBUG
        rumps.debug_mode(self.debug_mode)
        self.mails_max_get = MAILS_MAX_GET
        self.mails_max_show = MAILS_MAX_SHOW
        self.authentication_file = AUTHENTICATION_FILE
        self.setting_file = SETTING_FILE
        self.plist_file = PLIST_FILE
        self.google_client_id = GOOGLE_CLIENT_ID
        self.google_client_secret = GOOGLE_CLIENT_SECRET
        self.menu_bar_icon = MENU_BAR_ICON

        # Read settings
        self.settings = {}
        self.read_settings()

        # Application setup
        super(MenuBarGmail, self).__init__(type(self).__name__, title=None,
                                           icon=self.menu_bar_icon)
        self.menu = [
            'About',
            None,
            'Account',
            'Check now',
            'Reconnect',
            'Unread messages',
            'Set checking interval',
            'Set labels',
            'Set filter',
            'Mail notification',
            'Start at login',
            None,
            'Uninstall',
            None,
        ]

        # Other class variables
        self.address = ''
        self.address = ''
        self.messages = {}
        self.message_contents = {}
        self.service = None
        self.is_first = True

        if 'notification' in self.settings\
                and self.settings['notification'] == '1':
            self.menu['Mail notification'].state = True
        else:
            self.menu['Mail notification'].state = False
        if 'startatlogin' in self.settings\
                and self.settings['startatlogin'] == '1':
            self.menu['Start at login'].state = True
        else:
            self.menu['Start at login'].state = False

        # Set and start get_messages
        self.get_messages_timer = rumps.Timer(self.get_messages_wrapper,
                                              int(self.settings['interval'])
                                              if 'interval' in self.settings
                                              else 60)
        if autostart:
            self.start()
Exemple #22
0
    def add_local_clock(self):
        # add local zone by default
        local_zone = get_localzone().zone
        self.add_clock(local_zone)
        if self.timezones_menu.has_key(local_zone):
            self.timezones_menu[local_zone].state = 1
        else:
            item = MenuItem(local_zone, callback=self.switch_clock_callback)
            item.state = 1
            self.timezones_menu.add(item)

    def open_about(self, sender):
        import webbrowser
        # new = 2 for opening in the tab if possible
        webbrowser.open(ABOUT_URL, new=2)
        return

    def quit_app(self, sender):
        self.dump_clocks_data()
        self.dump_intvl_data()
        quit_application(sender)


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == 'debug':
        from rumps import debug_mode
        debug_mode(True)
    app = ClockApp()
    app.run()
Exemple #23
0
from PyObjCTools.Conversion import propertyListFromPythonCollection
from Cocoa import (NSFont, NSFontAttributeName, NSColor,
                   NSForegroundColorAttributeName)

# preload libvlccore.dylib
# https://github.com/oaubert/python-vlc/issues/37
d = '/Applications/VLC.app/Contents/MacOS/'
p = d + 'lib/libvlc.dylib'
if os.path.exists(p):
    # force pre-load of libvlccore.dylib  # ****
    ctypes.CDLL(d + 'lib/libvlccore.dylib')  # ****
    dll = ctypes.CDLL(p)

import vlc

rumps.debug_mode(False)

if 'VLC_PLUGIN_PATH' not in os.environ:
    # print('VLC_PLUGIN_PATH not set. Setting now...')
    os.environ[
        'VLC_PLUGIN_PATH'] = '$VLC_PLUGIN_PATH:/Applications/VLC.app/Contents/MacOS/plugins'


class RadioBarRemoteThread(threading.Thread):
    def __init__(self, radiobar, host, port):
        super(RadioBarRemoteThread, self).__init__()
        self.stop_event = threading.Event()

        self.radiobar = radiobar

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    def __init__(self, autostart=True):
        # Set default values
        self.debug_mode = DEBUG
        rumps.debug_mode(self.debug_mode)
        self.mails_max_get = MAILS_MAX_GET
        self.mails_max_show = MAILS_MAX_SHOW
        self.authentication_file = AUTHENTICATION_FILE
        self.setting_file = SETTING_FILE
        self.plist_file = PLIST_FILE
        self.google_client_id = GOOGLE_CLIENT_ID
        self.google_client_secret = GOOGLE_CLIENT_SECRET
        self.menu_bar_icon = MENU_BAR_ICON

        # Read settings
        self.settings = {}
        self.read_settings()

        # Application setup
        super(MenuBarGmail, self).__init__(type(self).__name__,
                                           title=None,
                                           icon=self.menu_bar_icon)
        self.menu = [
            'About',
            None,
            'Account',
            'Check now',
            'Reconnect',
            'Unread messages',
            'Set checking interval',
            'Set labels',
            'Set filter',
            'Mail notification',
            'Start at login',
            None,
            'Uninstall',
            None,
        ]

        # Other class variables
        self.address = ''
        self.address = ''
        self.messages = {}
        self.message_contents = {}
        self.service = None
        self.is_first = True

        if 'notification' in self.settings\
                and self.settings['notification'] == '1':
            self.menu['Mail notification'].state = True
        else:
            self.menu['Mail notification'].state = False
        if 'startatlogin' in self.settings\
                and self.settings['startatlogin'] == '1':
            self.menu['Start at login'].state = True
        else:
            self.menu['Start at login'].state = False

        # Set and start get_messages
        self.get_messages_timer = rumps.Timer(
            self.get_messages_wrapper,
            int(self.settings['interval'])
            if 'interval' in self.settings else 60)
        if autostart:
            self.start()
Exemple #25
0
#!/usr/bin/env python

import json
import os
import threading

from envparse import env

import soco
import rumps
from rumps import MenuItem
from soco import SoCo

rumps.debug_mode(env.bool("DEBUG", default=False))

try:
    from urllib import urlretrieve
except ImportError:
    from urllib.request import urlretrieve

class SonostusApp(rumps.App):
    def update_zones(self):
        self.zones = list(soco.discover())
        try:
            with self.open('zones.json', 'w') as f:
                json.dump([{'ip_address': z.ip_address, 'player_name': z.player_name} for z in self.zones], f)
        except:
            pass

        self.update_zone_menu()
        return self.zones
Exemple #26
0
 def __init__(self):
     super(PasswordHolderApp, self).__init__('pw')
     self.update_menu()
     rumps.debug_mode(True)
Exemple #27
0
 def __init__(self):
     super(statusBar, self).__init__("Now Playing")
     self.menu = ["Inform player"]
     rumps.debug_mode(True)
     self.player = ""
     self.tuple = ""
Exemple #28
0
 def __init__(self):
     super(SomeApp, self).__init__(type(self).__name__, menu=['On', 'Testing'])
     rumps.debug_mode(True)
Exemple #29
0
class AwesomeStatusBarApp(rumps.App):

    rumps.debug_mode(True)

    cw = None

    t1 = None

    def __init__(self):
        super(AwesomeStatusBarApp, self).__init__("Wallpaper Change", "",
                                                  "trayicon.png")

        self.menu = [('Start'), ('Stop'), ('Next'), ('Resume'), None,
                     ('Time',
                      ('10 Seconds', '30 Seconds', '1 Minute', '15 Minutes',
                       '30 Minutes', '1 Hour', '3 Hours')), ('Shuffle'), None,
                     ('About')]
        self.order = 1
        self.cw = ChangeWallpaper(self.order)

    @rumps.clicked("Start")
    def start_app(self, _):

        self.cw.start()

        start_button = self.menu["Start"]
        start_button.set_callback(None)

        stop_button = self.menu["Stop"]
        stop_button.set_callback(self.stop_app)

        rumps.notification("Status", "Process Started",
                           "Wallpaper rotation has Started")

    @rumps.clicked("Next")
    def next_wallpaper(self, _):
        self.cw.go_to_next_wallpaper()

    @rumps.clicked("Shuffle")
    def do_shuffle(self, sender):
        sender.state = not sender.state
        if self.order == 1:
            self.order = 0
            self.cw.set_n_order(0)
        else:
            self.order = 1
            self.cw.set_n_order(1)

    @rumps.clicked("Resume")
    def resume_app(self, _):
        self.cw.resume()
        self.cw.kill = False

        stop_button = self.menu["Stop"]
        stop_button.set_callback(self.stop_app)

        start_button = self.menu["Resume"]
        start_button.set_callback(None)

    def stop_app(self, _):

        self.cw.kill = True
        self.cw.pause()

        stop_button = self.menu["Stop"]
        stop_button.set_callback(None)

        start_button = self.menu["Resume"]
        start_button.set_callback(self.resume_app)

        rumps.notification("Status", "Process stopped",
                           "Wallpaper rotation has stopped")

    @rumps.clicked("About")
    def about_app(self, _):
        rumps.alert(title="About", message='Wallpaper Slider Alpha 0.0.1')

    # Time Limits  (Functions)

    @rumps.clicked('Time', '10 Seconds')
    def time_span_10_seconds(self, sender):
        title = sender.title
        sender.state = not sender.state
        self.deselect_all_options(title)
        self.cw.set_time(self.convert_string_to_time(title))

    @rumps.clicked('Time', '30 Seconds')
    def time_span_30_seconds(self, sender):
        title = sender.title
        sender.state = not sender.state
        self.deselect_all_options(title)
        self.cw.set_time(self.convert_string_to_time(title))

    @rumps.clicked('Time', '1 Minute')
    def time_span_1_minute(self, sender):
        title = sender.title
        sender.state = not sender.state
        self.deselect_all_options(title)
        self.cw.set_time(self.convert_string_to_time(title))

    @rumps.clicked('Time', '15 Minutes')
    def time_span_15_minutes(self, sender):
        title = sender.title
        sender.state = not sender.state
        self.deselect_all_options(title)
        self.cw.set_time(self.convert_string_to_time(title))

    @rumps.clicked('Time', '30 Minutes')
    def time_span_30_minutes(self, sender):
        title = sender.title
        sender.state = not sender.state
        self.deselect_all_options(title)
        self.cw.set_time(self.convert_string_to_time(title))

    @rumps.clicked('Time', '1 Hour')
    def time_span_1_hour(self, sender):
        title = sender.title
        sender.state = not sender.state
        self.deselect_all_options(title)
        self.cw.set_time(self.convert_string_to_time(title))

    @rumps.clicked('Time', '3 Hours')
    def time_span_3_hours(self, sender):
        title = sender.title
        sender.state = not sender.state
        self.deselect_all_options(title)
        self.cw.set_time(self.convert_string_to_time(title))

    # Other functions

    def convert_string_to_time(self, string_time):
        splitted = string_time.split(" ", 1)
        number = 0

        if splitted[1] == "Seconds":
            number = int(splitted[0]) * 1
        elif splitted[1] == "Minutes" or splitted[1] == "Minute":
            number = int(splitted[0]) * 60
        elif splitted[1] == "Hours" or splitted[1] == "Hour":
            number = int(splitted[0]) * 3600
        else:
            number = int(splitted[0]) * 1

        return number

    def deselect_all_options(self, sender):
        for i in self.menu['Time']:
            rest = self.menu['Time'][str(i)]
            if str(i) != str(sender):
                if rest.state:
                    rest.state = not rest.state