Exemplo n.º 1
0
def tap_event_callback(_tap_proxy, event_type, event_ref, _user_info):

    if event_type != NX_SYSDEFINED:
        return event_ref

    with autorelease_pool():
        event = NSEvent.eventWithCGEvent_(event_ref)

        if event.subtype() != NSEventSubtypeScreenChanged:
            # value of 8, for some reason.
            return event_ref  # pragma: no cover

        key_code = (event.data1() & 0xFFFF0000) >> 16
        if key_code not in _MEDIA_KEYS:
            return event_ref  # pragma: no cover

        iTunes = None
        for bundle_name in 'com.apple.Music', 'com.apple.iTunes':
            iTunes = SBApplication.applicationWithBundleIdentifier_(
                bundle_name)
            if iTunes is not None:
                break

        if not iTunes.isRunning():
            return event_ref  # pragma: no cover

        key_flags = event.data1() & 0x0000FFFF
        key_is_pressed = (((key_flags & 0xFF00) >> 8)) == 0xA

        if key_is_pressed:
            meth_name = _MEDIA_ACTIONS[key_code]
            getattr(iTunes, meth_name)()
Exemplo n.º 2
0
def _get_opened_files_adobe_cc(identifier: str) -> Iterator[Item]:
    """
    Retrieve documents path of opened files of the given bundle *identifier* (application).
    Where application is one of the Adobe Creative Suite:

        >>> get_opened_files_via_com("com.adobe.Photoshop")
        >>> get_opened_files_via_com("com.adobe.Illustrator")

    Complete specs of supported applications:
        - Illustrator: https://www.adobe.com/devnet/illustrator/scripting.html
        - Photoshop: https://www.adobe.com/devnet/photoshop/scripting.html
    """
    if not _is_running(identifier):
        return

    app = SBApplication.applicationWithBundleIdentifier_(identifier)

    if not app or not app.isRunning():
        return

    documents = app.documents()
    if not documents:
        return

    for doc in documents:
        file_path = doc.filePath()
        if not file_path:
            # The document is not yet saved and so has no path
            continue

        path = file_path.path()
        pid = compute_fake_pid_from_path(path)
        yield pid, Path(path)
Exemplo n.º 3
0
 def GET(self):
     
     iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
     track = iTunes.currentTrack()
     
     web.header('Content-Type','text/html; charset=utf-8') 
     return render.nowplaying(track=track, iTunes=iTunes, len=len)
Exemplo n.º 4
0
def start_server():
    """Spawn server. Does not check if the server is already running.
    """
    if run_cmd == '':
        # Complex run command not given, build it from the information available
        if mswindows or darwin:
            cmd = []
        else:
            cmd = ['xterm', '-T', 'Slimv', '-e']
        cmd = cmd + [
            python_path, slimv_path, '-p',
            str(PORT), '-l', lisp_path, '-s'
        ]
    else:
        cmd = shlex.split(run_cmd)

    # Start server
    #TODO: put in try-block
    if mswindows:
        CREATE_NEW_CONSOLE = 16
        server = Popen(cmd, creationflags=CREATE_NEW_CONSOLE)
    elif darwin:
        from ScriptingBridge import SBApplication

        term = SBApplication.applicationWithBundleIdentifier_(
            "com.apple.Terminal")
        term.doScript_in_(" ".join(cmd) + " ; exit", 0)
    else:
        server = Popen(cmd)

    # Allow subprocess (server) to start
    time.sleep(2.0)
Exemplo n.º 5
0
def start_server():
    """Spawn server. Does not check if the server is already running.
    """
    if run_cmd == '':
        # Complex run command not given, build it from the information available
        if mswindows or darwin:
            cmd = []
        else:
            cmd = ['urxvt', '-fn', 'xft:Consolas-8', '-T', 'Slimv', '-e']
        cmd = cmd + [python_path, slimv_path, '-p', str(PORT), '-l', lisp_path, '-s']
    else:
        cmd = shlex.split(run_cmd)

    # Start server
    #TODO: put in try-block
    if mswindows:
        CREATE_NEW_CONSOLE = 16
        server = Popen( cmd, creationflags=CREATE_NEW_CONSOLE )
    elif darwin:
        from ScriptingBridge import SBApplication

        term = SBApplication.applicationWithBundleIdentifier_("com.apple.Terminal")
        term.doScript_in_(" ".join(cmd) + " ; exit", 0) 
    else:
        server = Popen( cmd )

    # Allow subprocess (server) to start
    time.sleep( 2.0 )
Exemplo n.º 6
0
    def on_done(self):
        # Create a secure temporary directory, both for privacy and to allow
        # multiple files with the same basename to be edited at once without
        # overwriting each other.
        try:
            self.temp_dir = tempfile.mkdtemp(prefix='rsub-')
        except OSError as e:
            sublime.error_message(
                'Failed to create rsub temporary directory! Error: %s' % e)
            return
        self.temp_path = os.path.join(
            self.temp_dir,
            os.path.basename(self.env['display-name'].split(':')[-1]))
        try:
            temp_file = open(self.temp_path, "wb+")
            temp_file.write(self.file[:self.file_size])
            temp_file.flush()
            temp_file.close()
        except IOError as e:
            # Remove the file if it exists.
            if os.path.exists(self.temp_path):
                os.remove(self.temp_path)
            try:
                os.rmdir(self.temp_dir)
            except OSError:
                pass

            sublime.error_message('Failed to write to temp file! Error: %s' %
                                  str(e))

        # create new window if needed
        if len(sublime.windows()) == 0 or "new" in self.env:
            sublime.run_command("new_window")

        # Open it within sublime
        view = sublime.active_window().open_file(self.temp_path)

        # Add the file metadata to the view's settings
        # This is mostly useful to obtain the path of this file on the server
        view.settings().set('rsub', self.env)

        # Add the session to the global list
        SESSIONS[view.id()] = self

        # Bring sublime to front
        if (sublime.platform() == 'osx'):
            if (SBApplication):
                subl_window = SBApplication.applicationWithBundleIdentifier_(
                    "com.sublimetext.2")
                subl_window.activate()
            else:
                os.system(
                    "/usr/bin/osascript -e '%s'" %
                    'tell app "Finder" to set frontmost of process "Sublime Text" to true'
                )
        elif (sublime.platform() == 'linux'):
            import subprocess
            subprocess.call("wmctrl -xa 'sublime_text.sublime-text-2'",
                            shell=True)
Exemplo n.º 7
0
 def applicationOpenUntitledFile_(self, _):
     window, tab = find_best_yaybu_terminal()
     if window and tab:
         tab.setSelected_(True)
         window.setFrontmost_(True)
         term = SBApplication.applicationWithBundleIdentifier_("com.apple.Terminal")
         term.activate()
         return
     self.openYaybufile_(None)
Exemplo n.º 8
0
 def application_openFile_(self, ns_app, path):
     terminal = SBApplication.applicationWithBundleIdentifier_("com.apple.Terminal")
     tab = terminal.doScript_in_("clear; %s; exit 0;" % (YAYBUC,), None)
     tab.setCustomTitle_(CUSTOM_WINDOW_TITLE )
     tab.setTitleDisplaysCustomTitle_(True)
     tab.setTitleDisplaysDeviceName_(False)
     tab.setTitleDisplaysFileName_(False)
     tab.setTitleDisplaysShellPath_(False)
     tab.setTitleDisplaysWindowSize_(False)
Exemplo n.º 9
0
def showResultsBrowser(name, entries):
    BBEdit = SBApplication.applicationWithBundleIdentifier_(
        "com.barebones.BBEdit")
    ResultsBrowser = BBEdit.classForScriptingClass_("results browser")
    properties = {'name': name}
    browserSpecifier = ResultsBrowser.alloc(
    ).initWithElementCode_properties_data_(fourCharCode('RslW'), properties,
                                           entries)
    BBEdit.windows().addObject_(browserSpecifier)
Exemplo n.º 10
0
def _activate_window():
    if sublime.platform() == 'osx':
        if SBApplication:
            subl_window = SBApplication.applicationWithBundleIdentifier_("com.sublimetext.2")
            subl_window.activate()
        else:
            os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Sublime Text" to true' ''')
    elif sublime.platform() == 'linux':
        subprocess.call("wmctrl -xa 'sublime_text.sublime-text-2'", shell=True)
Exemplo n.º 11
0
Arquivo: watch.py Projeto: davea/watch
def reload_chrome(keyword):
    chrome = SBApplication.applicationWithBundleIdentifier_("com.google.Chrome")
    if not chrome:
        print("Chrome doesn't appear to be running!")
        return
    for window in chrome.windows():
        for tab in window.tabs():
            if keyword in tab.URL():
                print("Reloading Chrome: {}".format(tab.URL()))
                tab.reload()
Exemplo n.º 12
0
Arquivo: watch.py Projeto: davea/watch
def reload_safari(keyword):
    safari = SBApplication.applicationWithBundleIdentifier_("com.apple.Safari")
    if not safari:
        print("Safari doesn't appear to be running!")
        return
    for window in safari.windows():
        for tab in window.tabs():
            if keyword in tab.URL():
                print("Reloading Safari: {}".format(tab.URL()))
                tab.setURL_(tab.URL())
Exemplo n.º 13
0
Arquivo: rsub.py Projeto: aurora/rsub
    def on_done(self):
        # Create a secure temporary directory, both for privacy and to allow
        # multiple files with the same basename to be edited at once without
        # overwriting each other.
        try:
            self.temp_dir = tempfile.mkdtemp(prefix='rsub-')
        except OSError as e:
            sublime.error_message('Failed to create rsub temporary directory! Error: %s' % e)
            return
        self.temp_path = os.path.join(self.temp_dir,
                                      os.path.basename(self.env['display-name'].split(':')[-1]))
        try:
            temp_file = open(self.temp_path, "wb+")
            temp_file.write(self.file[:self.file_size])
            temp_file.flush()
            temp_file.close()
        except IOError as e:
            # Remove the file if it exists.
            if os.path.exists(self.temp_path):
                os.remove(self.temp_path)
            try:
                os.rmdir(self.temp_dir)
            except OSError:
                pass

            sublime.error_message('Failed to write to temp file! Error: %s' % str(e))

        # create new window if needed
        if len(sublime.windows()) == 0 or "new" in self.env:
            sublime.run_command("new_window")

        # Open it within sublime
        view = sublime.active_window().open_file(
            "{0}:{1}:0".format(
                self.temp_path, self.env['selection'] if 'selection' in self.env else 0),
            sublime.ENCODED_POSITION)

        # Add the file metadata to the view's settings
        # This is mostly useful to obtain the path of this file on the server
        view.settings().set('rsub', self.env)

        # Add the session to the global list
        SESSIONS[view.id()] = self

        # Bring sublime to front
        if(sublime.platform() == 'osx'):
            if(SBApplication):
                subl_window = SBApplication.applicationWithBundleIdentifier_("com.sublimetext.2")
                subl_window.activate()
            else:
                os.system("/usr/bin/osascript -e '%s'" %
                          'tell app "Finder" to set frontmost of process "Sublime Text" to true')
        elif(sublime.platform() == 'linux'):
            import subprocess
            subprocess.call("wmctrl -xa 'sublime_text.sublime-text-2'", shell=True)
Exemplo n.º 14
0
 def openTerminal_(self, sender):
     """ Open a Terminal.app window running bpython,
         with the PlotDevice.app environment pre-loaded """
     TerminalApp = SBApplication.applicationWithBundleIdentifier_("com.apple.Terminal")
     scriptPythonPath = ":".join(sys.path)
     scriptBPythonExecutable = bundle_path(shared='bplotdevice')
     scriptBPythonSetup = bundle_path(rsrc='plotdevice-term.py')
     scriptCommand = '''cd %s && PYTHONPATH="%s" %s -i %s && exit''' % (
         bundle_path(), scriptPythonPath, scriptBPythonExecutable, scriptBPythonSetup)
     TerminalApp.activate()
     TerminalApp.doScript_in_(scriptCommand, None)
Exemplo n.º 15
0
 def cast_process_to_class(self, class_type):
     app = SBApplication.applicationWithBundleIdentifier_(
         class_type.bundle_id)
     started = bool(app.valueForKey_('running'))
     if not started:
         app.activate()
     for process in self.get_processes_by_bundle(class_type.bundle_id):
         t = class_type(self, process)
         if not started:
             t.hide()
         yield t
Exemplo n.º 16
0
 def __init__(self,
              event_system: SystemEvent,
              process: Optional[SBObject] = None):
     assert self.bundle_id is not None, 'Requires a bundle_id to be in class type!'
     self.app = SBApplication.applicationWithBundleIdentifier_(
         self.bundle_id)
     self.app_props = list_unique_properties(self.app)
     self._events: ReferenceType[SystemEvent] = weakref.ref(event_system)
     self._process = process
     self._caffeine_fh = None
     super().__init__()
Exemplo n.º 17
0
Arquivo: rsub.py Projeto: KES777/rsub
def bring_to_front():
    global WINDOW_HANDLE
    if(sublime.platform() == 'osx'):
        if(SBApplication):
            subl_window = SBApplication.applicationWithBundleIdentifier_("com.sublimetext.2")
            subl_window.activate()
        else:
            os.system("/usr/bin/osascript -e '%s'" %
                      'tell app "Finder" to set frontmost of process "Sublime Text" to true')
    elif(sublime.platform() == 'linux'):
        import subprocess
        subprocess.call("wmctrl -xa '%s'" % WINDOW_HANDLE, shell=True)
Exemplo n.º 18
0
def get_display_profile_path():
    if not hasattr(get_display_profile_path, 'profile_path'):
        import objc
        from ScriptingBridge import SBApplication
        ImageEvents = SBApplication.applicationWithBundleIdentifier_('com.apple.ImageEvents')
        #ImageEvents.activate()
        displays = ImageEvents.displays()
        if len(displays) < 1:
            get_display_profile_path.profile_path = None
        get_display_profile_path.profile_path = displays[0].displayProfile().location().properties()['POSIXPath']
        ImageEvents.quitSaving_(objc.NO)
    return get_display_profile_path.profile_path
Exemplo n.º 19
0
def bring_to_front():
    global WINDOW_HANDLE
    if (sublime.platform() == 'osx'):
        if (SBApplication):
            subl_window = SBApplication.applicationWithBundleIdentifier_(
                "com.sublimetext.2")
            subl_window.activate()
        else:
            os.system(
                "/usr/bin/osascript -e '%s'" %
                'tell app "Finder" to set frontmost of process "Sublime Text" to true'
            )
    elif (sublime.platform() == 'linux'):
        import subprocess
        subprocess.call("wmctrl -xa '%s'" % WINDOW_HANDLE, shell=True)
Exemplo n.º 20
0
 def POST(self):
     
     iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
     track = iTunes.currentTrack()
     
     i = web.input(submit = None)
     
     if i.submit == "play":
         iTunes.playpause()
     elif i.submit == "next":
         iTunes.nextTrack()
     elif i.submit == "prev":
         iTunes.previousTrack()
     
     web.header('Content-Type','text/html; charset=utf-8') 
     return render.nowplaying(track=track, iTunes=iTunes, len=len)
Exemplo n.º 21
0
 def enableshortcuts(self):
     self.apply()
     # popup System Preferences dialog
     try:
         # http://stackoverflow.com/questions/6652598/cocoa-button-opens-a-system-preference-page/6658201
         from ScriptingBridge import SBApplication
         sysprefs = 'com.apple.systempreferences'
         prefs = SBApplication.applicationWithBundleIdentifier_(sysprefs)
         pane = [x for x in prefs.panes() if x.id() == 'com.apple.preference.security'][0]
         prefs.setCurrentPane_(pane)
         anchor = [x for x in pane.anchors() if x.name() == 'Privacy_Accessibility'][0]
         anchor.reveal()
         prefs.activate()
     except:
         AXIsProcessTrustedWithOptions({kAXTrustedCheckOptionPrompt: True})
     self.parent.event_generate('<<Quit>>', when="tail")
Exemplo n.º 22
0
 def enableshortcuts(self):
     self.apply()
     # popup System Preferences dialog
     try:
         # http://stackoverflow.com/questions/6652598/cocoa-button-opens-a-system-preference-page/6658201
         from ScriptingBridge import SBApplication
         sysprefs = 'com.apple.systempreferences'
         prefs = SBApplication.applicationWithBundleIdentifier_(sysprefs)
         pane = [x for x in prefs.panes() if x.id() == 'com.apple.preference.security'][0]
         prefs.setCurrentPane_(pane)
         anchor = [x for x in pane.anchors() if x.name() == 'Privacy_Accessibility'][0]
         anchor.reveal()
         prefs.activate()
     except:
         AXIsProcessTrustedWithOptions({kAXTrustedCheckOptionPrompt: True})
     self.parent.event_generate('<<Quit>>', when="tail")
Exemplo n.º 23
0
    def __init__(self) -> None:
        QtCore.QObject.__init__(self)

        # TODO: Figure out which things should be in reset_state
        self.__application_reference: ApplicationViewModel = None
        self.__is_enabled: bool = False

        self.__media_player: MediaPlayerPlugin = None
        self.__is_spotify_plugin_available = False  # This is set to true if Spotify is installed

        # Set up Discord presence
        self.__is_discord_rpc_enabled = False
        self.__is_discord_rpc_connected = False
        self.__discord_rpc = Presence('799678908819439646')

        # Settings
        # TODO: Move these properties to an App view model
        self.__is_submission_enabled: bool = None
        self.is_player_paused = False
        self.__was_last_player_event_paused: bool = False

        if os.environ.get('MOCK'):
            self.__media_player = MockPlayerPlugin()
            self.__connect_media_player_signals()
        else:
            # Initialize media player plugins
            self.__spotify_plugin = SpotifyPlugin()
            self.__music_app_plugin = MusicAppPlugin()

            use_spotify = False
            spotify_app = SBApplication.applicationWithBundleIdentifier_(
                'com.spotify.client')

            # Use Music app plugin by default since every Mac has it (this will be changed when the user preference is loaded from the database)
            # TODO: Make it possible for no media player to be set during onboarding so we don't need to have this temporary value?
            self.switchToMediaPlugin('musicApp',
                                     should_update_in_database=False)

        self.media_player_name_changed.emit()

        # Start polling interval to check for new media player position
        self.__timer = QtCore.QTimer(self)
        self.__timer.timeout.connect(self.__fetch_new_media_player_position)

        self.reset_state()
Exemplo n.º 24
0
def delete_file(fpath):
    """On OS X: Trashes a path using the Finder, via OS X's Scripting Bridge.

    On other platforms: unlinks file.
    """

    try:
        from AppKit import NSURL
        from ScriptingBridge import SBApplication
    except ImportError:
        log().debug("Deleting %r" % fpath)
        os.unlink(fpath)
    else:
        log().debug("Trashing %r" % fpath)
        targetfile = NSURL.fileURLWithPath_(fpath)
        finder = SBApplication.applicationWithBundleIdentifier_("com.apple.Finder")
        items = finder.items().objectAtLocation_(targetfile)
        items.delete()
Exemplo n.º 25
0
def delete_file(fpath):
    """On OS X: Trashes a path using the Finder, via OS X's Scripting Bridge.

    On other platforms: unlinks file.
    """

    try:
        from AppKit import NSURL
        from ScriptingBridge import SBApplication
    except ImportError:
        log().debug("Deleting %r" % fpath)
        os.unlink(fpath)
    else:
        log().debug("Trashing %r" % fpath)
        targetfile = NSURL.fileURLWithPath_(fpath)
        finder = SBApplication.applicationWithBundleIdentifier_("com.apple.Finder")
        items = finder.items().objectAtLocation_(targetfile)
        items.delete()
Exemplo n.º 26
0
Arquivo: HQ.py Projeto: sbwrrn/HQ
def get_window_image():
    """ Generates black and white image of text area within HQ game window """

    #Grab Quicktime Window
    app = SBApplication.applicationWithBundleIdentifier_(
        "com.apple.QuicktimePlayerX")
    finderWin = app.windows()[0]

    #Reposition and resize Quicktime window
    x, y, x_len, y_len = 50, 50, 400, 800
    finderWin.setBounds_([[x, y], [x_len, y_len]])

    #Grab text area of Quicktime window and convert image to B&W
    im = ImageGrab.grab(bbox=(x, y + 150, x_len + x, y_len + y - 200))
    im = im.convert('L')
    im = im.point(lambda x: 0 if x < 200 else 255, '1')
    #im.save('BW.PNG')

    return im
Exemplo n.º 27
0
    def on_done(self):
        # Create a secure temporary directory, both for privacy and to allow
        # multiple files with the same basename to be edited at once without
        # overwriting each other.
        try:
            self.temp_dir = tempfile.mkdtemp(prefix='rsub-')
        except OSError as e:
            sublime.error_message('Failed to create rsub temporary directory! Error: %s' % e)
            return
        self.temp_path = os.path.join(self.temp_dir, os.path.basename(self.env['display-name']))
        try:
            temp_file = open(self.temp_path, "w+")
            temp_file.write(self.file[:self.file_size])
            temp_file.flush()
            temp_file.close()
        except IOError as e:
            # Remove the file if it exists.
            if os.path.exists(self.temp_path):
                os.remove(self.temp_path)
            try:
                os.rmdir(self.temp_dir)
            except OSError:
                pass

            sublime.error_message('Failed to write to temp file! Error: %s' % str(e))

        # create new window if needed
        if len(sublime.windows()) == 0:
            sublime.run_command("new_window")

        # Open it within sublime
        view = sublime.active_window().open_file(self.temp_path)
        SESSIONS[view.id()] = self

        # Bring sublime to front
        if(sublime.platform() == 'osx' and SBApplication):
            subl_window = SBApplication.applicationWithBundleIdentifier_("com.sublimetext.2")
            subl_window.activate()
        elif(sublime.platform() == 'linux'):
            import subprocess
            subprocess.call("wmctrl -xa 'sublime_text.sublime-text-2'", shell=True)
Exemplo n.º 28
0
  def __init__(self) -> None:
    # Store reference to Music app in AppleScript
    self.__applescript_app = SBApplication.applicationWithBundleIdentifier_('com.apple.Music')
    
    super().__init__(self.__applescript_app)

    # Set up NSNotificationCenter (refer to https://lethain.com/how-to-use-selectors-in-pyobjc)
    self.__default_center = NSDistributedNotificationCenter.defaultCenter()
    self.__default_center.addObserver_selector_name_object_(
      self,
      '__handleNotificationFromMusic:',
      'com.apple.Music.playerInfo',
      None
    )

    # Store latest state
    self.__state: MediaPlayerState = None

    # Store whether the last notification failed was missing data to notify when it's been fixed
    self.__last_notification_had_error = False
    self.__last_state_with_error: MediaPlayerState = None
Exemplo n.º 29
0
    def __init__(self) -> None:
        # Store reference to Spotify app in AppleScript
        self.__applescript_app = SBApplication.applicationWithBundleIdentifier_(
            'com.spotify.client')

        super().__init__(self.__applescript_app)

        self.is_plugin_available = False

        # Store the current media player state
        self.__state: MediaPlayerState = None

        if self.__applescript_app:
            self.is_plugin_available = True

            # Set up NSNotificationCenter (refer to https://lethain.com/how-to-use-selectors-in-pyobjc)
            self.__default_center = NSDistributedNotificationCenter.defaultCenter(
            )

            self.__default_center.addObserver_selector_name_object_(
                self, '__handleNotificationFromSpotify:',
                'com.spotify.client.PlaybackStateChanged', None)
Exemplo n.º 30
0
    def reset_state(self) -> None:
        # Store Scrobble objects that have been submitted
        self.scrobble_history: List[Scrobble] = []

        # Keep track of whether the history view is loading data
        self.__is_loading = False

        # Hold a Scrobble object for currently playing track (will later be submitted)
        self.__current_scrobble: Scrobble = None

        # Hold the index of the selected scrobble in the sidebar
        self.__selected_scrobble_index: int = None

        # Hold the Scrobble object at the __selected_scrobble_index
        # This can either be a copy of the current scrobble or one in the history
        self.selected_scrobble: Scrobble = None

        # Keep track of whether the current scrobble has hit the threshold for submission
        self.__current_scrobble_percentage: float = None
        self.__should_submit_current_scrobble = False

        # Keep track of furthest position reached in a song
        self.__furthest_player_position_reached: float = None

        # Keep track of how many poll ticks have passed since the playback position changed
        self.__cached_playback_position: float = None
        self.__ticks_since_position_change: int = None

        # Store the current track's crop values since they aren't part of the scrobble object
        self.__current_track_crop: TrackCrop = None

        if (self.__is_enabled):
            self.__is_spotify_plugin_available = False

            # Load preferences from database
            media_player_preference = db_helper.get_preference('media_player')
            is_rich_presence_enabled = db_helper.get_preference(
                'rich_presence_enabled')

            # Check if Spotify is installed; show option to switch media player in status bar menu if it's installed
            spotify_app = SBApplication.applicationWithBundleIdentifier_(
                'com.spotify.client')

            if spotify_app:
                self.__is_spotify_plugin_available = True
                self.is_spotify_plugin_available_changed.emit()

            if media_player_preference == 'spotify':
                # If Spotify is not installed, reset media player preference back to Music.app
                # TODO: Use better method to figure out if Spotify is installed without logged error
                if self.__is_spotify_plugin_available:
                    self.switchToMediaPlugin('spotify',
                                             should_update_in_database=False)
                else:
                    logging.info(
                        'Spotify not detected on device; switching back to Music.app as media player'
                    )
                    db_helper.set_preference('media_player', 'musicApp')
                    media_player_preference = 'musicApp'

            if media_player_preference == 'musicApp':
                self.switchToMediaPlugin('musicApp',
                                         should_update_in_database=False)

            self.media_player_name_changed.emit()

            # Try connecting to Discord rich presence if enabled
            self.__is_discord_rpc_enabled = db_helper.get_preference(
                'rich_presence_enabled')
            self.is_discord_rich_presence_enabled_changed.emit()

            if self.__is_discord_rpc_enabled and helpers.is_discord_open():
                self.__connect_discord_rpc_if_open()
Exemplo n.º 31
0
app = Flask(__name__)

CONTINUATION_STRING = "CONTINUE"
DISCONTINUATION_STRING = "STOP"
MAX_ITERATION_COUNT = 3
MESSAGE_SET_SIZE = 5
LAST_ROW_NUMBER = 1363
BEGINNING_STRING = "You have signed up to receive the lines of the bee movie script line by line. At any point you " \
                   f"can opt out of this program by sending a message containing the string: {DISCONTINUATION_STRING}. " \
                   f"In an interest to your time and my CPU, I will only send lines {MESSAGE_SET_SIZE} at a time in " \
                   f"the beginning. There will be {MAX_ITERATION_COUNT} of message sets before I SPAM you with " \
                   f"the rest of the bee movie script. The entire bee movie script is {LAST_ROW_NUMBER} lines long. " \
                   f"Meaning you will receive {LAST_ROW_NUMBER} messages. MESSAGE AND DATA RATES DO APPLY. " \
                   f"If you would like to continue please send us a message containing the string: {CONTINUATION_STRING}"
Messages = SBApplication.applicationWithBundleIdentifier_("com.apple.iChat")
most_recent_date = 0
first_message_que = []
phone_number_iteration = {}
BEE_MOVIE_PATH = 'static/bee movie script.txt'


@app.route('/', methods=['POST', 'GET'])
def add_phone_number():
    if request.method == 'POST':
        data = request.get_json()
        phone_number = data.get('phone number')
        phone_number_iteration.update({phone_number: 0})
        first_message_que.append(phone_number)
        return jsonify(f"I have started communication with {phone_number}")
    if request.method == 'GET':
Exemplo n.º 32
0
def find_existing_yaybu_terminals():
    term = SBApplication.applicationWithBundleIdentifier_("com.apple.Terminal")
    for window in term.windows():
        for tab in window.tabs():
            if CUSTOM_WINDOW_TITLE == tab.customTitle():
                yield window, tab
Exemplo n.º 33
0
#!/usr/bin/python

from ScriptingBridge import SBApplication

iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")

print iTunes.currentTrack().name()
Exemplo n.º 34
0
 def __init__(self):
     self._itunes_app = SBApplication.applicationWithBundleIdentifier_(
         'com.apple.iTunes')
     self._system_events = SBApplication.applicationWithBundleIdentifier_(
         'com.apple.systemevents')
Exemplo n.º 35
0
 def __init__(self):
     self._itunes_app = SBApplication.applicationWithBundleIdentifier_('com.apple.iTunes')
     self._system_events = SBApplication.applicationWithBundleIdentifier_('com.apple.systemevents')
Exemplo n.º 36
0
from ScriptingBridge import SBApplication

iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")

def song():
  song = ['Now Playing: '+iTunes.currentTrack().name()]
  if iTunes.currentTrack().artist():
    song.append('- '+iTunes.currentTrack().artist())
  if iTunes.currentTrack().album():
    song.append('['+iTunes.currentTrack().album()+']')
  if iTunes.currentTrack().rating():
    rating = int(iTunes.currentTrack().rating())
    str_rating = ''.join(['*' for x in range(rating/20)])
    song.append('Rating: '+str_rating)

  return ' '.join(song);
Exemplo n.º 37
0
from ScriptingBridge import SBApplication
app = SBApplication.applicationWithBundleIdentifier_('com.apple.iTunes')

import logging
logger = logging.getLogger(__name__)

ITunesPlaylist = app.classForScriptingClass_('playlist')

library_special_kinds = {
    1800630337: 'Audiobooks',
    1800630345: 'Movies',
    1800630348: 'Library',
    1800630349: 'Purchased',
    1800630352: 'Podcasts',
    1800630362: 'Music',
}


class SBWrapper(object):
    objc = None

    def __init__(self, objc):
        '''
        Initialize SBWrapper around raw object
        '''
        if objc is None:
            raise NotImplementedError('Cannot create a new SB object directly')
        self.objc = objc


def memoize(func):
Exemplo n.º 38
0
from ScriptingBridge import SBApplication
app = SBApplication.applicationWithBundleIdentifier_('com.apple.iTunes')

import logging
logger = logging.getLogger(__name__)


ITunesPlaylist = app.classForScriptingClass_('playlist')

library_special_kinds = {
    1800630337: 'Audiobooks',
    1800630345: 'Movies',
    1800630348: 'Library',
    1800630349: 'Purchased',
    1800630352: 'Podcasts',
    1800630362: 'Music',
}


class SBWrapper(object):
    objc = None

    def __init__(self, objc):
        '''
        Initialize SBWrapper around raw object
        '''
        if objc is None:
            raise NotImplementedError('Cannot create a new SB object directly')
        self.objc = objc

Exemplo n.º 39
0
 def __init__(self):
     self.driver = SBApplication.applicationWithBundleIdentifier_(
         "com.google.Chrome")
     self.queue = Queue(max_workers=4)
Exemplo n.º 40
0
 def __init__(self):
     self.client = SBApplication.applicationWithBundleIdentifier_(
         "com.spotify.client")
Exemplo n.º 41
0
 def __init__(self):
     self.app = app = SBApplication.applicationWithBundleIdentifier_(
         'com.apple.iTunes')
     self.app.setFixedIndexing_(True)
     self.source = first(app.sources(), lambda x: x.name() == 'Library')
Exemplo n.º 42
0
 def __init__(self):
     self.app = SBApplication.applicationWithBundleIdentifier_(
         'com.apple.systemevents')
     super().__init__()
 def __init__(self):
     self.chrome = SBApplication.applicationWithBundleIdentifier_(
         "com.google.Chrome")
Exemplo n.º 44
0
from ScriptingBridge import SBApplication


app = SBApplication.applicationWithBundleIdentifier_('com.googlecode.iterm2')
win = app.createWindowWithDefaultProfileCommand_('/bin/bash')
ses = win.currentSession()
ses.setName_('foo')
ses.writeContentsOfFile_text_newline_(None, 'pwd', True)

tab = win.createTabWithDefaultProfileCommand_('/bin/bash')
ses = tab.currentSession()
ses.setName_('bar')
ses.writeContentsOfFile_text_newline_(None, 'ls', True)

tab = win.createTabWithDefaultProfileCommand_('/bin/bash')
ses = tab.currentSession()
ses.setName_('baz 1')
ses.writeContentsOfFile_text_newline_(None, 'echo 1', False)

# Split into 5 panes.
for i in range(2, 6):
    ses = ses.splitHorizontallyWithDefaultProfileCommand_('/bin/bash')
    ses.setName_('baz {}'.format(i))
    ses.writeContentsOfFile_text_newline_(None, 'echo {}'.format(i), False)
Exemplo n.º 45
0
#!/usr/bin/python
import sys
from AppKit import NSScreen
from ScriptingBridge import SBApplication
from math import fabs

if not len(sys.argv) == 2 or not sys.argv[1] in ['s', 'm', 'b', 'c']:
    raise ValueError("""Invalid argument. 
	Proper options are:
	s - small
	m - medium
	b - large
	c - center""")

terminal = SBApplication.applicationWithBundleIdentifier_("com.apple.Terminal")
t_window = terminal.windows()[0]
toPrint = ""

# Finds current screen and sets its frame to pFrame
for screen in NSScreen.screens():
    # Check if corner is further left than the left border
    # if so this may be the leftmost screen
    if (t_window.position().x < screen.frame().origin.x):
        pFrame = screen.frame()

    # If not too far left (checked above) and not too far right
    # (checked below) it must be this screen, so break searching
    elif (t_window.position().x <
          screen.frame().origin.x + screen.frame().size.width):
        pFrame = screen.frame()
        break
Exemplo n.º 46
0
    'KxPH': 0x4B785048, # password hint
}

if len(sys.argv) < 2:
    print "usage: %s <keynote-file>" % sys.argv[0]
    sys.exit(-1)

# Export options
keynote_file = sys.argv[1]
to_file = NSURL.fileURLWithPath_(keynote_file.split('.key')[0] + '.pdf')
as_format = EXPORT_FORMAT['Kpdf']
with_properties = NSMutableDictionary.dictionaryWithDictionary_({
})

if DEBUG:
    print("   KEYNOTE_FILE: %s" % keynote_file)
    print("        TO_FILE: %s" % to_file)
    print("      AS_FORMAT: %s" % as_format)
    print("WITH_PROPERTIES: %s" % with_properties)

# Open Keynote file
keynote = SBApplication.applicationWithBundleIdentifier_(BUNDLE)
doc = keynote.open_(keynote_file)

# Export to format
doc.exportTo_as_withProperties_(to_file, as_format, with_properties)

# Close keynote
doc.closeSaving_savingIn_(SAVING_OPTIONS['no'], None)
keynote.quitSaving_(SAVING_OPTIONS['no'])
Exemplo n.º 47
0
 def __init__(self):
     self.itunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
Exemplo n.º 48
0
    def __init__(self):
        """ opens the iTunes library """

        self.itunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
	def applicationWithBundleIdentifier(self, bundleID):
		from ScriptingBridge import SBApplication
		return SBApplication.applicationWithBundleIdentifier_(bundleID)
Exemplo n.º 50
0
	def __init__(self, library = 'Library', playlist = 'Rate Me Im Famous'):
		logging.info('ITunesBridge creation...')
		self.__iTunes = SBApplication.applicationWithBundleIdentifier_('com.apple.iTunes')
		self.__library = self.__iTunes.sources().objectWithName_(library)
		self.__playlist = self.__library.playlists().objectWithName_(playlist)
		logging.info('ITunesBridge created.')
Exemplo n.º 51
0
 def __init__(self, delegate):
     self.paused = False
     self.last_volume = 0
     self.delegate = delegate
     self.application = SBApplication.applicationWithBundleIdentifier_(self.application_id)
Exemplo n.º 52
0
#!/usr/bin/env python
import sys
from ScriptingBridge import SBApplication

if sys.stdin.isatty():
    print "usage: pebble logs 2>&1 | ./peynote.py"
    exit(1)

keynote = SBApplication.applicationWithBundleIdentifier_("com.apple.iWork.Keynote")
deckset = SBApplication.applicationWithBundleIdentifier_("com.unsignedinteger.Deckset")

echo = True
while True:
    # use readline() to work around strange buffer problems with pebble command
    line = sys.stdin.readline()
    if len(line) == 0:
        exit(0)

    deckset_doc = deckset.documents()[0] if deckset and deckset.isRunning() else None

    if echo:
        print line.strip()

    if "Displaying logs" in line:
        print "Connected to watch!"
        print "Start the peynote app on your Pebble and use UP/DOWN to go previous/next slide in Keynote."
        print "Press CTRL+C to quit."
        echo = False
    elif "UP" in line:
        if keynote and keynote.isRunning(): keynote.showPrevious()
        if deckset_doc: deckset_doc.setSlideIndex_(deckset_doc.slideIndex()-1)
Exemplo n.º 53
0
 def __init__(self, delegate):
     self.paused = False
     self.last_volume = 0
     self.delegate = delegate
     self.application = SBApplication.applicationWithBundleIdentifier_(
         self.application_id)