Exemple #1
0
def setupAppleScript():
    global scptExport
    global scptLaunch
    global scptQuit

    # Compile apple script that exports one image
    scptExport = applescript.AppleScript('''
        on run {arg}
          set thepath to "%s"
          tell application "Photos"
            set theitem to media item id arg
            set thelist to {theitem}
            export thelist to POSIX file thepath
          end tell
        end run
        ''' % (tmppath))

    # Compile apple script that launches Photos.App
    scptLaunch = applescript.AppleScript('''
        on run
          tell application "Photos"
            activate
          end tell
        end run
        ''')

    # Compile apple script that quits Photos.App
    scptQuit = applescript.AppleScript('''
        on run
          tell application "Photos"
            quit
          end tell
        end run
        ''')
Exemple #2
0
def stowe_Desktop(dst=False, save_positions=True):
    if dst == False:
        dst = opjh('Desktop_' + time_str())
    print(dst)
    a = """
    tell application "Finder"
        tell every item of desktop
            get name
        end tell
    end tell
    """
    b = """
    tell application "Finder"
        
        get {desktop position, name} of item ITEM_NUM of desktop
        
    end tell"""

    w = applescript.AppleScript(a).run()
    y = []
    for x in range(len(w)):
        c = b.replace('ITEM_NUM', str(x + 1))
        y.append(applescript.AppleScript(c).run())
    pprint(y)
    unix('mkdir -p ' + dst)
    _, l = dir_as_dic_and_list(opjD(''))
    for i in l:
        shutil.move(opjD(i), dst)
    if save_positions:
        save_obj(y, opj(dst, '.item_positions'))
Exemple #3
0
def change_volume():
    chars = T.get("1.0", 'end-1c')
    if len(chars) > 1000:
        applescript.AppleScript(f"set volume output volume 100").run()
        print(f"Debug: Textbox contained text: {chars}")
        print(f"Debug: Volume changed to: 100")
        return
    applescript.AppleScript(
        f"set volume output volume {len(chars) * 0.1}").run()
    print(f"Debug: Textbox contained text: {chars}")
    print(f"Debug: Volume changed to: {len(chars) * 0.1}")
    def get_hearthstone_window():
        # todo adjust for window bar on top -- about 20 pixels

        script_contents = '''
        tell application "System Events" to tell application process "Hearthstone"
            get %s of window 1
        end tell
        '''
        position_script = applescript.AppleScript(script_contents % 'position')
        x, y = position_script.run()

        size_script = applescript.AppleScript(script_contents % 'size')
        width, height = size_script.run()

        return ImageGrab.grab((x, y, x + width, y + height))
Exemple #5
0
def setWindowSize(appName, w, h):
    cmd_str = '''
    tell application "System Events" to tell process "%s"
        set visible to true
        set size of window 1 to {%d, %d}
    end tell''' % (appName, w, h)
    return applescript.AppleScript(cmd_str).run()
Exemple #6
0
def get_active_window():
    '''Returns the window id and title of the active window.'''

    script = applescript.AppleScript('''
        global frontApp, frontAppName, windowTitle

        set windowTitle to ""
        tell application "System Events"
            set frontApp to first application process whose frontmost is true
            set frontAppName to name of frontApp
            tell process frontAppName
                tell (1st window whose value of attribute "AXMain" is true)
                    set windowTitle to value of attribute "AXTitle"
                end tell
            end tell
        end tell

        return {frontAppName, windowTitle}
    ''')
    # window_id isn't really a unique id, instead it's just the app name -- but
    # still useful for automating through applescript
    window_id, window_title = script.run()
    if window_id:
        return window_id.encode('utf-8'), window_title.encode('utf-8')
    else:
        return None, None
Exemple #7
0
	def run_applescript (self, action):
		"""
		Run an AppleScript from Actions.
		"""
		
		if not os.path.exists (u"{}/{}.scpt".format(self.CONFIGDIR, action.props['script'])):
			self.logger.error(u"Action to run AppleScript '{}' failed because that script does not exist in the folder".format(action.props['script']))
			return None
		
		self.logger.info (u"Running AppleScript '{}'".format(action.props['script']))
		script = applescript.AppleScript(path=u"{}/{}.scpt".format(self.CONFIGDIR, action.props['script']))
		response = script.run()
		
		if "extra" in action.props and action.props["extra"]:
			try:
				if action.props["extraAction"] == "storeNewVariable": 
					self.store_to_variable (action.props["name"], response)
				elif action.props["extraAction"] == "storeExistingVariable": 
					self.store_to_variable (action.props["variable"], response)
				elif action.props["extraAction"] == "storePlugin": 
					self.store_to_plugin (action.props["name"], response)
			except:
				pass
		
		return response
Exemple #8
0
    def get_foreground(cls):
        script = '''
        global frontApp, frontAppName
        tell application "System Events"
            set frontApp to first application process whose frontmost is true
            set frontAppName to name of frontApp
            tell process frontAppName
                set mainWindow to missing value
                repeat with win in windows
                    if attribute "AXMain" of win is true then
                        set mainWindow to win
                        exit repeat
                    end if
                end repeat
            end tell
        end tell
        return frontAppName
        '''

        # window_id isn't really a unique id, instead it's just the app name
        # -- but still useful for automating through applescript
        window_id = applescript.AppleScript(script).run()
        if isinstance(window_id, binary_type):
            window_id = window_id.decode(locale.getpreferredencoding())

        return cls.get_window(id=window_id)
Exemple #9
0
 def set_foreground(self):
     script = '''
     tell application "%s"
         activate window 1
     end tell
     ''' % self._id
     applescript.AppleScript(script).run()
Exemple #10
0
def save_monitor_app_data(output_folder, filename):
    scpt1 = ('''
        tell application "System Events"
            tell process "Monitor"
                set frontmost to true
                -- activate
                delay 1
                key code 1 using {shift down, command down} -- Save As
        ''')
    scpt2 = ('''
                -- delay 0.5
                -- keystroke "/"
                delay 0.5
                keystroke "{}"
                delay 0.5
                key code 36 -- Enter
                delay 1
                keystroke "{}"
                delay 0.5
                key code 36 -- Enter
            end tell
        end tell
        '''.format(output_folder, filename))
    scpt = applescript.AppleScript(scpt1 + scpt2)
    scpt.run()
Exemple #11
0
def get_currently_playing_song():
    tell_spotify = applescript.AppleScript('''
    on is_running(appName)
    	tell application "System Events" to (name of processes) contains appName
    end is_running
    on Playing()
    	set SpotifyRunning to is_running("Spotify")
    	if SpotifyRunning then
    		tell application "Spotify"
    			set songTitle to the name of the current track
    			set songArtist to the artist of the current track
    			set songAlbum to the album of the current track
                set player to "Spotify"
    			set result to songArtist & "%-%" & songTitle & "%-%" & songAlbum & "%-%" & player
    			if player state is playing then
    				return result
    			else
    				return "None" & "%-%" & "None" & "%-%" & "None"
    			end if
    		end tell
    	end if
    end Playing
    ''')

    try:
        output = tell_spotify.call('Playing').split('%-%')

        song = dict()
        song['artist'] = output[0]
        song['name'] = output[1]
        song['album'] = output[2]
        song['player'] = output[3]
        get_song_artwork(song)
    except AttributeError:
        print("Spotify is most likely not running. Start it and play some music then run the script again.")
Exemple #12
0
def setTopWindow(appName):
    print('setwindow')
    cmd_str = '''
    tell application "System Events"
        tell process "%s"
            set frontmost to true
            set visible to true
        end tell
    end tell
    ''' % appName
    try:
        applescript.AppleScript(cmd_str).run()
    except:
        return False
    return True
    win = dsp.create_resource_object('window', winID)
    #win.set_input_focus(X.RevertToParent, X.CurrentTime)
    #win.configure(stack_mode=X.TopIf)
    clientmessage = protocol.event.ClientMessage(
        window=win,
        client_type=dsp.intern_atom('_NET_ACTIVE_WINDOW'),
        data=(32, (2, X.CurrentTime, 0, 0, 0))
    )
    mask = (X.SubstructureRedirectMask|X.SubstructureNotifyMask)
    root.send_event(clientmessage, event_mask=mask) 
    dsp.flush()
    return True
Exemple #13
0
def getWindowRect(appName):
    cmd_str = '''
    activate application "%s"
    tell application "System Events" to tell process "%s"
        set visible to true
        get position of window 1
    end tell''' % (appName, appName)
    pos = applescript.AppleScript(cmd_str).run()

    cmd_str = '''
    tell application "System Events" to tell process "%s"
        set visible to true
        get size of window 1
    end tell''' % appName
    size = applescript.AppleScript(cmd_str).run()
    return [pos[0], pos[1], size[0], size[1]]
Exemple #14
0
def getScreenSize():
    cmd_str = '''
    tell application "Finder"
      set _b to bounds of window of desktop
      set _width to item 3 of _b
    end tell'''
    w = applescript.AppleScript(cmd_str).run()

    cmd_str = '''
    tell application "Finder"
      set _b to bounds of window of desktop
      set _height to item 4 of _b
    end tell'''
    h = applescript.AppleScript(cmd_str).run()
    
    return w,h
Exemple #15
0
def read_papers_entries():
    scpt = applescript.AppleScript('''
        tell application "Papers"
            set t to {%s} of every publication item
            return t
        end tell
    ''' % (', '.join(FIELDS)))

    t = scpt.run()
    result = [dict(zip(FIELDS, k)) for k in zip(*t)]
    # result[i] : {'citekey' : ..., 'title' : ..., ...}

    entries = []
    for entry in result:
        title = entry['title']
        if title == applescript.kMissingValue:
            title = ''
        if len(title) > 1 and title[0] == '{' and title[-1] == '}':
            title = title[1:-1]
        entry['title'] = title

        for k in ('publication year', 'author names'):
            if entry[k] == applescript.kMissingValue:
                entry[k] = ''

        if entry['keyword names']:
            keywords = entry['keyword names'].split(',')
            keywords = ['#' + unicode(k).strip() for k in keywords]
            entry['keyword names'] = ' '.join(keywords)

        entries.append(entry)
    return entries
Exemple #16
0
    def get_properties(self):
        """
        Method to get the properties of a macOS window.

        :rtype: dict
        :returns: window properties
        """
        script = '''
        tell application "System Events" to tell application process id "%s"
            try
                get properties of window 1
            on error errmess
                log errmess
            end try
        end tell
        ''' % self._id
        properties = applescript.AppleScript(script).run()
        if not properties:
            return {}

        result = {}
        encoding = locale.getpreferredencoding()
        for key, value in properties.items():
            key = key.code
            if isinstance(key, binary_type):
                key = key.decode(encoding)
            if isinstance(value, applescript.AEType):
                value = value.code
                if isinstance(value, binary_type):
                    value = value.decode(encoding)
            result[key] = value
        return result
Exemple #17
0
def start_ae(application):
    """
    start_ae this function will use applescript to tell AE to startup
    the reason there is a parameter is because this can be used with
    different versions of AE(hence different applescript name)
    :param application:  the application to start
    :return: True or False
    """

    script_command = """

        set appName to \"%s\"
        if application appName is running then
            tell application appName to activate
        end if
        """ % application

    try:

        scpt = applescript.AppleScript(script_command)
        scpt.run()
        return True

    except applescript.ScriptError:
        logging.error("start_ae error thrown")
        logging.error("ScriptError: {}".format(
            applescript.ScriptError.message))
        print("ScriptError: {}".format(applescript.ScriptError.message))
        logging.info(script_command)

        return False
Exemple #18
0
    def close_task(self, _id, name):
        try:
            of_task_name, rep_rule = self.get_task_details(_id)
            already_closed = Omnifocus.task_completed(_id)

            if already_closed:
                self.log.debug(u"Ignoring {0}{1} ({2}), already completed in Omnifocus".format(URI_PREFIX, _id, name))
                return 0

            if name != of_task_name:
                self.log.debug(
                    u"Ignoring {0}{1} ({2}), names don't match ({3})".format(URI_PREFIX, _id, name, of_task_name))
                return 0

            rep_type = 1

            if rep_rule is None:
                self.log.debug(u"Closing {0}{1} ({2})".format(URI_PREFIX, _id, name))
            else:
                self.log.debug(u"Closing repeating task {0}{1} ({2})".format(URI_PREFIX, _id, name))
                rep_type = 2

            scpt = applescript.AppleScript(CLOSE_TASK)
            scpt.call('close_task', _id)

            return rep_type
        except ValueError as e:
            self.log.debug(u"Ignoring {0}{1} ({2}), not found in Omnifocus".format(URI_PREFIX, _id, name))
            self.log.debug(e)
            return 0
Exemple #19
0
    def _paste_keep_source_formatting(self, insert_location):
        """_paste_keep_source_formatting() uses System Events to paste the copied slides in the clipboard.
        The pastes slides will be inserted after the selection set by "select slide insert_location".
        So, the logic needs to take care of that.

        For clicking "Paste with Keep Source Formatting", it doesn't work with AppleScript,
        because it's using AXPopupMenu.

        So, cliclick utility is used below, but can be replaced by other Python module like pyautogui.
        """

        insert_location_1 = insert_location - 1
        prs_name = get_KeyData(self.prs)
        cmd = f"""
set insert_location to {insert_location_1}

tell application "Microsoft PowerPoint"
	tell presentation "{prs_name}"
		activate
		select slide insert_location
	end tell
end tell

set keep_source_formatting to "Keep Source Formatting"

tell application "System Events"
	set arrow_x to 0
	set arrow_y to 0

	tell process "Microsoft PowerPoint"
		set frontmost to true

		set btn_pos to {0, 0}
		set btn_sz to {0, 0}
		tell menu button "Paste" of group 1 of scroll area 1 of tab group 1 of window 1
			set btn_pos to position
			set btn_sz to size

			set arrow_x to (item 1 of btn_pos) + (item 1 of btn_sz) - 6
			set arrow_y to (item 2 of btn_pos) + 10
		end tell

		# Use cliclick utility to generate physical click at the position.
		set cmd to "/usr/local/bin/cliclick c:" & (arrow_x as string) & "," & (arrow_y as string)
		do shell script cmd

		delay 1

		tell group 1 of window "Paste"
			click menu button keep_source_formatting
			delay 1
		end tell
	end tell
end tell
"""
        try:
            scpt = applescript.AppleScript(cmd)
            scpt.run()
        except applescript.ScriptError:
            raise
Exemple #20
0
def main():
    q = sys.argv[1]
    (title, area, tag, day, note) = util.parse(q[1:])

    if not title: return;

    script = """tell application id "com.culturedcode.ThingsMac"
        activate
        set newToDo to make new to do   
        set name of newToDo to "%s"
    """ % title

    if q[0] == 'm' and not note:
        note = getClipboardText()
    
    if note:
        note = note.replace('"', '\\\"')
        note = note.replace('\n', '\\\n')
        script += '    set notes of newToDo to "%s"\n'%(note)
    if day:
        today = date.today()
        delta = day - today
        script += '    set due date of newToDo to (current date)+%d*days\n'% (delta.days)
    if tag:
        script += 'set tag names of newToDo to "%s"\n'%(tag)
    script += 'show newTodo\nmove newTodo to list id "%s"\nend tell' % area

    # print script
    applescript.AppleScript(script).run()
Exemple #21
0
    def copyall_and_close(self):
        self.activate()

        cmd = f"""
tell application "System Events"
	tell process "Microsoft PowerPoint"
		set frontmost to true

		# click View -> Slide Sorter menu
		click menu item "Slide Sorter" of menu "View" of menu bar 1
		delay 1

		# Command + A to select all slides.
		# Command + C to copy slides.
		keystroke "ac" using {{command down}}
		delay 1

		# Command + W to close the window.
		keystroke "w" using {{command down}}
		delay 1
	end tell
end tell
"""
        try:
            scpt = applescript.AppleScript(cmd)
            scpt.run()
        except applescript.ScriptError:
            raise
Exemple #22
0
 def set_foreground(self):
     script = '''
     tell application "System Events" to tell application process id "%s"
         set frontmost to true
     end tell
     ''' % self._id
     applescript.AppleScript(script).run()
Exemple #23
0
def sendTextAndSpacesAsKeyCodes(text):
    if len(text) == 0:
        return
    text = "\nkeystroke \"" + string.replace(
        text.strip(), " ", "\"\nkey code 49\nkeystroke \"") + "\"\n"
    content = "tell application \"System Events\"" + text + "end tell"
    script = applescript.AppleScript(content)
    script.run()
    def get_focused_window_name(self):
        focused_window_id = applescript.AppleScript('''
            tell application "System Events"
                return title of first application process whose frontmost is true
            end tell
        ''').run()

        return focused_window_id
Exemple #25
0
def main():
    # Config Facebook ID and Tokens (using for testing - in process of implementing browser OAuth for long life tokens)
    fbConfig = {"page_id": page_id, "access_token": access_token}

    # Mac
    # AppleScript to get currently playing artist and song from Spotify (no auth req)
    scpt = applescript.AppleScript('''
        on run
            set appName to \"Spotify\"
            set isRunning to false
            tell application \"System Events\"
                if exists process appName then
                    set isRunning to true
                end if
            end tell
            
            if isRunning is true then
                tell application \"Spotify\"
                    set artistName to artist of current track as string
                    set songName to name of current track as string 
                    set currentSong to artistName & \" - \" & songName
                end tell
            end if
        return currentSong
        end run
    ''')

    nowPlaying = scpt.run()

    # Search for video of currently playing song
    # Telling urllib what the query text will be
    query = urllib.parse.quote(nowPlaying)

    # Get video URL for nowPlaying
    url = "https://www.youtube.com/results?search_query=" + query
    response = urllib.request.urlopen(url)
    html = response.read()
    soup = BeautifulSoup(html, "html.parser")
    video = soup.find(attrs={'class': 'yt-uix-tile-link'})
    videoURL = 'https://www.youtube.com' + video['href']

    Notifier.notify(title='LazySearch',
                    message='Successfully Shared: ' + nowPlaying,
                    open='https://www.facebook.com/?sk=h_chr')

    # Post video for currently playing song
    graph = facebook.GraphAPI(fbConfig['access_token'])

    attachment = {
        'name': nowPlaying,
        'link': videoURL,
        'caption': '',
        'description': '',
        'picture': ''
    }

    # Post to wall
    graph.put_wall_post(message='', attachment=attachment)
    def is_window_focused(self, window_id):
        focused_window_id = applescript.AppleScript('''
            tell application "System Events"
                set focusedWindow to name of first application process whose frontmost is true
                return focusedWindow
            end tell
        ''').run()

        return focused_window_id == window_id
Exemple #27
0
def getClipboardText():
    s = """
    tell application "System Events"    
      Set aText to the clipboard
      return aText
    end tell
    """

    return applescript.AppleScript(s).run()    
Exemple #28
0
def quit_monitor_app():
    scpt = applescript.AppleScript('''
        tell application "Monitor"
            delay 1
            activate
            quit
        end tell
        ''')
    scpt.run()
Exemple #29
0
 def _get_window_module(self):
     script = '''
     global module
     tell application "System Events" to tell application process id %s
         set module to name
     end tell
     return module
     ''' % (self._id)
     return applescript.AppleScript(script).run()
Exemple #30
0
 def _get_window_pid(self):
     script = '''
     global pid
     tell application "System Events" to tell application process id %s
         set pid to unix id
     end tell
     return pid
     ''' % (self._id)
     return applescript.AppleScript(script).run()