Deselecting a file from a selection in Finder via AppleScript - macos

I've been searching everywhere for around 6 hours to find a way to deselect file items from a previously selected array of items in Finder via AppleScript via Automator with a Quick Action. I've seen deselect all items, I've seen add items to a selection/list for process, but not remove items from a selection...
The goal: I usually have to process a lot of images and get them approved by supervisors before providing them on our servers for use. All of which come in a set of a transparent PNG and an opaque JPG. I only need to upload the JPG files over for approval. So, let's say I have 30 images. 15 of which are JPGs, 15 of which are PNGs. I would love to be able to select all 30 images, and deselect the 15 of which are PNGs (via the script), left with a selection of all the JPGs.
There are other ways to achieve this, but it would be exceptionally helpful if I could just select the images, run the script, and then move them over for upload (website upload). That appears to be the fastest (by hand) way to go about achieving the end result.
What I know: The selection property. Through my research, I've seen the selection property called in a small amount of different ways, but am unsure how to properly manipulate it. I've tried converting the selection to a string and splitting that by detecting a word to split from (like "Macintosh HD") allowing them to be manipulated in a list, and then potentially removing them from a selection...? I'm also very unsure how to just properly manipulate a property as-is...
I've also attempted to just use the given files via input through Automator AppleScript. But alas, that still leads to knowing how to remove/deselect a file from the current selection.
Anybody know how to achieve this?
I appreciate all the time spend and information in advance. Thank you.

There are two approaches you can use for this, one in pure AppleScript, the other using Automator actions.
The pure AppleScript solution is take the selection as a list of files, copy the JPG files to another list, and set the selection to that new list, like so:
set new_selection_list to {}
tell application "Finder"
set selection_list to selection
repeat with this_item in selection_list
if name extension of this_item is "jpg" then
copy this_item to end of new_selection_list
end if
end repeat
set selection to new_selection_list
end tell
Of course, if you're passing these files in through the input variable in automator, you'd use that rather than testing the selection again, but the principle still stands.
Alternately, you can set up your workflow with a Filter Finder Items action, like so:
I'd recommend the second approach. It's likely significantly faster, and takes less programming.

Although not really deselecting items per se, the Finder has a reveal command that will show the specified items. One approach would be to edit the list of selected items, and then reveal the result.
Note that the sorting of selected items varies depending on whether it is from an Automator action (sorted by name) or a Finder tell statement (the order selected), and items mixed from multiple folders (as can happen in an Automator workflow), will result in multiple Finder windows.
The following Automator Quick Action example will remove the first two items from the input items and reveal the rest of the items in the Finder window:
Workflow receives current files or folders in Finder.app
Run AppleScript:
on run {input, parameters}
set newSelection to input
if (count input) > 2 then -- guard for following statement(s)
set newSelection to items 3 thru -1 of input -- or whatever keep/remove criteria
end if
tell application "Finder" to reveal newSelection
return newSelection
end run

Related

AppleScript - Get the Bounds of Every open Window

I have been playing all day with getting this down. The goal being to generate an AppleScript which generates yet more AppleScript. I'll explain in more detail.
THE DESIRED END RESULT: After arranging your windows how you like them follow up with launching this script. This will copy to your clipboard the necessary script to automatically launch, position, and resize the application windows to the current configuration. This would be so that I could send the script to other people who could then, upon launching this script, design their own custom layouts which could then be either pasted into Script Editor or possibly made into a service and bound to a hotkey using Automator.
WHAT I'M CURRENTLY TRYING TO OVERCOME: I can't seem to get it to list the bounds for each window. I am currently running this script.
tell application "System Events"
set openApps to name of every process whose background only is false
repeat with theItem in openApps
set checkApp to theItem
tell application checkApp to get the bounds of the front window
end repeat
end tell
This spits out the following error every time without exception:
error "System Events got an error: Can’t get application \"Finder\"." number -1728 from application "Finder"
I'm not asking that someone solve the entire problem for me. Though any advice on the matter is always appreciated. The current hurtle is just to get the bounds of each window set to variables for use elsewhere in the script.
This answer focusses on the issue stated under What I'm Currently Trying To Overcome. I've interpreted The Desired End Result to be background information that provides context to your immediately-pressing issue (and this is really interesting/useful to provide, so thank you).
TL;DR
tell application "System Events"
set _P to a reference to (processes whose background only = false)
set _W to a reference to windows of _P
[_P's name, _W's size, _W's position]
end tell
This will get you the list of size and position properties for each application process. Below is a rather verbose deconstruction of where and why your script went wrong; followed by a proposed solution after considering other equally viable solutions before settling on the base code above. I will try and trim the wordiness of this answer another day when I'm a bit less tired, but for now, I hope the deeper insight helps.
The Issues
▸ Starting with the specific error your script is throwing out, it's necessary to point out that, generally speaking, tell application blocks don't often nor should rarely need to be nested. You opened a tell block to target System Events, which was necessary to get the process names; that's the point when you should have either closed the tell block, or used a simple tell command on a single line:
tell application "System Events" to set openApps to the name of every process...
(no need for end tell in this case).
However, as your tell block remains opens, the commands that come next are also directed to System Events. The first application process that your script evidently finds belongs to Finder, and when your script (inside the repeat loop) is instructed to tell application "Finder" (by way of the checkApp variable), the error is thrown because you've actually told System Events to tell Finder to do something, and System Events has no understanding of how to do interact with an application object.
▸ This leads us onto the following line, with which are a couple of problems pertinent to your script (plus a more general noteworthy aside† about which I have left a footnote):
tell application checkApp to get the bounds of the front window
This line will only work for applications that are (Apple)scriptable. Not all applications can be controlled by AppleScript—it's a feature app makers choose to implement (or choose not to, as is ever more frequently the case) when developing their software for macOS.
Those that are scriptable will (if they follow Apple's guidelines) have defined window objects that each contain a bounds property. Those that aren't scriptable won't have either of these. That's when another error will be thrown.
Another "minor" issue is that not all of the processes which are background only necessarily have windows, and thus a front window. Finder is never background only, but sometimes has no open windows. Therefore, even once the error you're getting has been fixed, this is the next error that crops up if there are no open Finder windows.
A Solution
Although you can't obtain a bounds property of a window belonging to a non-scriptable application, System Events can retrieve some properties that belong to objects of an application process. This is independent of whether an application to which the process belongs it itself scriptable or not, because System Events is the application we are targeting, which is scriptable, and happens to have access to similar information pertaining to each process's window objects (NB. see the footnote below, but the window object belonging to a process is not the same as the window object belonging to an application, so cannot be used interchangeably, and nor can their properties).
Although there is no bounds property for the window objects owned by processes of System Events, there are two other properties, which, together, are equivalent to bounds: position and size. The position gives the {X, Y} coordinate of the top-left corner of the window relative to the top-left corner of the screen (which is defined in this context as being the origin at {0, 0}); the size gives the {X, Y} pair of dimensions that represent the window's width and height, respectively.
Thus, given an hypothetical bounds property value of {𝑎, 𝑏, 𝑐, 𝑑} for a specific window, the relationship to size: {𝑥, 𝑦} and position: {𝑤, ℎ} can be expressed thus:
{𝑎, 𝑏, 𝑐, 𝑑} = {𝑥, 𝑦, 𝑥 + 𝑤, 𝑦 + ℎ}
The other consideration is getting a list of processes that actually have windows. There are various ways to go about doing this, each with advantages and disadvantages, which include brevity of code, execution time, and accuracy of the retrieved list of windows.
Your original method of retrieving a process list discriminated by background only is one of the fastest and there are only a few situations where false negatives lead to omissions from the list (namely, menubar applications that register as background only yet clearly have a window; the Instagram app Flume is an example).
You can instead discriminate by the visible property, which is just as fast, but I feel less apt in situations where an application is hidden and would need to be unhidden before recording its window properties; or, again, some menubar apps that register as background only, not visible, yet clearly are visible_ with a window in the foreground.
The method that is most reliable in retrieving all windows in any circumstance is, sadly, quite slow, but does produce a list a that's easy to work with and doesn't need further processing.
In our current situation, however, I think it's sensible to choose the option that gives speed and will work for most applications, which is your background only filter. As the list produced from this yields some false positives (Finder, for example), we need to process the list a bit before it's reliable to utilise.
Here's the code to retrieve a nested list containing a) a list of named processes; b) a list of window sizes for each of the named processes; and c) a list of window positions for each of the named processes:
tell application "System Events"
set _P to a reference to (processes whose background only = false)
set _W to a reference to windows of _P
[_P's name, _W's size, _W's position]
end tell
If you close your Finder windows, you'll see it still appears in the first list by name, but the second and third lists have an empty list {} where its windows' sizes and positions would otherwise be. So just be sure to do some checking before you try and reference the items of each sublist.
Compare and contrast it with this slower, but more accurate solution:
tell application "System Events"
set _P to a reference to (processes whose class of window 1 is window)
set _W to a reference to windows of _P
[_P's name, _W's size, _W's position]
end tell
It takes twenty times as long to run on my system, yielding an albeit solution that can identify menu bar apps, regular apps, and hidden apps that have windows, which might end up being essential for your ultimate goal. But if you work most often with the more regular apps, then it's fairly clear which method is more suitable.
†The more generalised, potential problem—that doesn't really apply to your script as it stands, but is useful to know for future scripts if you attempt to use a similar technique—is the use of a variable as a means of referencing an application that has an undetermined name at compile time (before the script is run).
bounds is a fairly ubiquitous property of all scriptable applications's windows, which is why you (almost) get away this technique here. However, if you picked a property or object class that Script Editor specifically does not contain, AppleScript won't recognise the terminology and assume it's simply a variable name. In order for application-specific terminology to be recognised, a reference to that specific application needs to be made in some form, either by way of a tell application "Finder" to... or enclosing the relevant lines inside a using terms from application "Finder" block.
A good rule-of-thumb is that applications generally need to be known and specified at compile time in order to receive AppleScript commands. There's no easy way to cater for varying options without using an if...then...else if... series of conditional blocks for each possible application.
This is a source of frustration particularly when it comes to applications that are seemingly similar in nature and, moreover, have a similar AppleScript dictionary, yet still don't share their terminology with one another for general use. I'm thinking specifically of Safari and Chrome, both of which have objects referred to as tabs, making it easy to forget that a Safari tab is still a different class of object to a Chrome tab, and any attempt to write generalised code to script either or both will meet with failure.

Detect order of applications, windows, tabs

I'm using AppleScript to find all tabs in multiple browsers (testing on Safari first) with certain criteria in it's title and give it to stdout for another script.
So I have the basic information I need;
window id
tab index
tab name
tab visible
So from this point I know which of my Safari screens are matching my criteria and I log their window id and their tab index. Besides that with tab visible I can know which is the foremost one.
Now I still have one issue. I really want to be able to know which window and tab was the last one active. Even if I can only know the window id that was used last by the user it would automatically mean that inside that window the tab with visible true is the last one.
But there is one more thing. If the visible tab is not meeting my criteria, then I would still need to know the order of the last active one too.
So what I'm looking for is an counter/order value of the last active windows and tabs. I can't find something in the documentation that could give me that counter. For example; the TAB-logic in OS X knows which apps were last used. I was wondering if that logic would be available as some kind of system variable and then also on it's window/tab sub level.
My code (slimmed down does this):
tell application "Safari"
...
repeat with win in winlist
...
repeat with t in tablets
# win.id
# t.index
# t.name
# t.visible
end repeat
end repeat
end tell
And so I'm looking for something that emulates win.lastUsedOrderIndex and t.lastUsedOrderIndex.
The simple answer is that if you do not find the properties you need in the application's dictionary, then you are out of luck. Window and Document lists in AppleScript are normally in a front-to-back ordering, since they are based on the orderedWindows and orderedDocuments NSArrays. Tabs in a browser are probably ordered left-to-right or right-to-left, based on the language localization, but I would be surprised if any browser had a reason to return tabs ordered by when they were "last used", whatever that means.

applescript - how to access the clipboard as an iTunes track or file track object

I'm trying to dev a custom paste script for iTunes. After 'copy'' of some playlist tracks, the user should call the script in stead of standard paste, to paste the tracks into another playlist. The script will do some extra stuff apart from pasting the tracks.
Question: To paste the clipboard as tracks an iTunes playlist I need to find the clipboard contents as Track class objects, not the file names, furl's or whatever.
clipboard info
says it has the following in the clipboard:
{
{Unicode text, 776},
{string, 388},
{«class itun», 4036},
{«class furl», 118},
{«class ut16», 778}
}
Now, the class furl objects might point me to the files, but that still doesn't get me an iTunes "File Track" or a "Track".
Is there anyone who can shed some light on what the class "itun" things are which are on the clipboard? (Tried for a day to find out myself, but didn't get anywhere) And, whether itun class objects might be usable to get to the copied-to-the-clipboard tracks?
I don't know how to do what you're asking using the clipboard. But why use the clipboard at all? If someone wants to "copy" the tracks this assumes that they have first selected the tracks. And if they have the tracks selected then there is no need to perform the copy step. A simple applescript can get the selection from iTunes so why not just use that approach? You get the selection as tracks and then do whatever you need in the rest of the applescript.
tell application "iTunes"
set selectedTracks to the selection
-- do whatever else you need
end tell

OSX Lion AppleScript : How to get current space # from mission control?

I'm trying to figure out how to get the current space # from mission control. Source would be helpful, but more helpful would be info on how to figure this out myself. I've written a few applescripts, but more often than not it seems like any time I need to do something new (that I can't find dictionary documentation for) it falls under the category of "tell this specific app (e.g. "System Events") this very specific thing" and I've no clue how I would actually figure that out.
Specifically what I am trying to do:
I hate the new mission control in OSX 10.7. I want my spaces "grid" back since I used it all the time. I used to navigate between spaces using arrow keys (e.g. ALT+↑) every few seconds. Now I'm stuck with this clunky 1x9 array of spaces instead of an elegant 3x3 grid. I've re-mapped all my spaces to use the number pad, which partially takes care of the problem (since it is a 3x3 grid), but only when I have an external keyboard attached.
Basically, I want to be able to use ALT+↑ and ↓ again, but to do so I need to detect the current space # so that I can switch from space 5-->2, for example.
Dave's answer below, although far more detailed than I expected, requires writing an app to do this (plus it still doesn't fully answer the question). If it's at all possible, I'd rather just bind a few keys to an applescript.
I'm trying to figure this out myself. Not there yet, but in the right direction:
Each Mission Control "space" gets a uuid assigned to it...
...except for the very first one (AFAIK), and the Dashboard one.
You can read them here:
$ defaults read com.apple.spaces
$ defaults read com.apple.desktop
File locations:
~/Library/Preferences/com.apple.spaces.plist
~/Library/Preferences/com.apple.desktop.plist
Here's mine. I have four spaces enabled, and three entries show up:
$ defaults read com.apple.spaces
{
spaces = (
{
type = 0;
uuid = "9F552977-3DB0-43E5-8753-E45AC4C61973";
},
{
type = 0;
uuid = "44C8072A-7DC9-4E83-94DD-BDEAF333C924";
},
{
type = 0;
uuid = "6FADBDFE-4CE8-4FC9-B535-40D7CC3C4C58";
}
);
}
If you delete a space, that entry will get removed from the file. If you add a space, an entry will be added. Again, there's never an entry for Desktop 1 or Dashboard.
I'm not sure if there's a public API to figure out what space uuid is being displayed on a display. I'd assume that no uuid means Display 1, and the others' mean Display 1+n.
I took a quick glance through the AppleScript Editor Library (Window ---> Library) and didn't see any entries under System Events for spaces. This is probably something that can be done with Cocoa, perhaps via private API, but I'm not sure about AppleScript.
UPDATE - July 23, 2011
It looks like Dock controls Mission Control. You can grab its header files like so:
Go to: /System/Library/CoreServices/Dock
Right-Click and Show Package Contents
Navigate: /Contents/MacOS/
Copy and paste the Dock binary to your desktop.
Run: $class-dump ~/Desktop/Dock
That'll spit out all of its header files (it's long; almost 7,500 lines). You can see the spaceUUID strings appearing in there. There's a class called WVSpace which appears to represent a single Space in Mission Control, and a lot of other WV* classes.
I'll keep looking at it tomorrow; too tired now. :)
UPDATE - July 24, 2011
Inside Dock there's a class called WVSpaces. It has a number of attributes including:
WVSpace *currentSpace;
unsigned int currentWorkspace;
WVSpace *nextSpace; // Space on the right???
WVSpace *previousSpace; // Space on the left???
BOOL currentSpaceIsDashboard;
BOOL dashboardIsCurrent;
...lots more...
Each WVSpace class has an NSString *_uuid; attribute, which is likely its SpaceUUID. So theoretically you can get the current space number like so:
WVSpace *currentSpace = [[WVSpaces sharedInstance] currentSpace];
NSString *currentSpaceUUID = [currentSpace _uuid]; // Empty string if main space???
The trick is, how to get access to the private WVSpaces class buried inside of Dock? I'm assuming it's Singleton as it has an NSMutableArray *_spaces; attribute, probably with every space listed in it. Only one space gets displayed at a time (this holds true if you're using multiple monitors; the space spans across both of them), so it makes sense to only have one WVSpaces instance.
So it looks like it'll require some SIMBL hacking of Dock to gain access to WVSpaces.
I've been poking around, and I came up with this: https://gist.github.com/1129406
Spaces have a nonsequential ID and a sequential index (0-based). You can get the ID in two ways:
from public APIs (see get_space_id)
from the private CGS API CGSGetWorkspace
You can set the current space by index using public APIs (though the notifications themselves are not publicly documented): see set_space_by_index
You can set the current space by ID using private the CGS API CGSSetWorkspace.
You cannot get the current space index directly. However, if you're always using the same set of nine spaces, you can rotate through them once using set_space_by_index, collect their IDs, and build a mapping. Then you will be able to get the current index from the ID.
... also been working on this :)
You say that you "need to to detect the current space #". This is not strictly true: To move down one row, you just move 3 spaces right, so in principle you could just bind something like
tell application "System Events" to tell process "WindowServer"
key code {124, 124, 124} using control down
end tell
to Alt-down (with FastScripts, Alfred or some other fast method that avoids the overhead of Automator). This approach will fail if you ever hit down in the bottom row, of course -- but if you are truly hard-wired, you never do :)
You have to "Enable access for assistive devices" in the Universal Access preference pane for the key code approach to work.
Caveat: This doesn't work. When I launch the script above, I nicely jump three spaces. The problem is that afterwards my keyboard goes unresponsive: It seems that only the window manager is receiving events: I can close windows and switch space, but I cannot interact with any applications.
My theory is that this happens when the jump causes the current application to change during the execution of the script -- but I have no idea how to fix this.
A related observation: The Mission Control (i.e. /Applications/Mission Control.app/Contents/MacOS/Mission\ Control) seems to react to some command line arguments:
Mission\ Control: show mission control
Mission\ Control 1: show desktop
Mission\ Control 2: show current application windows
I tried putting in some of the UUID's from defaults read com.apple.spaces, but that didn't do much. So much for fumbling in the dark.
I wrote an app - does it work for you?
Change Space.app
The keys to make it work are control-shift and the arrow keys, although this may be fixable if you are stuck on ALT.
Make sure you have 9 spaces (desktops) set up before you start, and you'll need to change the default ctrl-up and ctrl-down key bindings in System Preferences to something else (in Keyboard -> Keyboard Shortcuts -> Mission Control : Mission Control and Show Desktop).
On the first run it it will cycle through your desktops to enumerate them when you first change space.
Then you should be able to change between desktops like in a 3x3 grid.
There may be a few wrinkles, but it's basically functional, at least for me.
http://switchstep.com/ReSpaceApp
This works, is free (right now) and is awesome.
Just be sure to manually create as many spaces as your layout (in preferences) is expecting.
I'm on Mountain Lion and this seems to work for me.
defaults read com.apple.spaces
Look for "Current Space". You'll notice that running this command with different active spaces doesn't change the current space BUT if you check and uncheck a checkbox button in "System Preferences" and run it again, you'll see it updated.
Hopefully this helps someone else!
EDIT: It's ugly, but I'm using this:
killall Dock && sleep 0.2 && defaults read com.apple.spaces | grep -A1 "Current Space" | tail -1 | awk '{print $NF }' | cut -f1 -d';'
on openNewSpace()
tell application "System Events"
—start mission control
do shell script "/Applications/Mission\\ Control.app/Contents/MacOS/Mission\\ Control"
tell process "Dock"
set countSpaces to count buttons of list 1 of group 1
--new space
click button 1 of group 1
--switch to new space
repeat until (count buttons of list 1 of group 1) = (countSpaces + 1)
end repeat
click button (countSpaces + 1) of list 1 of group 1
end tell
end tell
end openNewSpace
I have come up with a workaround for this for myself in macOS Catalina, though I expect this should work for multiple macOS versions. This solution solves my problems, namely:
The inability to identify which desktop contains which project, because desktops cannot be named. (I usually am splitting time on work on multiple projects at once and each desktop is dedicated to work on a different project [and they all use the same apps])
The inability to programmatically(/easily) determine which desktop I'm on at any one time
The lack of tools to track time spent on each desktop
I solved item 1 quite some time back using Stickies.app. I put the project name in a huge enough font that it's easily legible in the desktop thumbnails in Mission Control and I hide the stickie window behind my Dock, assigned specifically to the corresponding project's desktop. (I also duplicate the desktop name in small superscripted text that pokes out from under the left side of the dock so that I can identify the current desktop outside of mission control.)
I just solved item 2 via applescript just now. In the stickie, I add a tiny, unobtrustive font string that identifies the stickie as the desktop name, e.g. 'dtop'. E.g. "small_superscripted_name LARGE_NAME tiny_dtop_string" or "project1 PROJECT1 dtop". Note, this script assumes that the project name contains no spaces (i.e. it's just one word). You can split on a different charcter/string, if you wish. Here is the applescript that, when run, results in the desktop name:
tell application "System Events"
--obtain the stickie with the desktop name
set dstr to name of first item of (windows of application process "Stickies" of application "System Events" whose name contains "dtop")
--Parse the desktop name from the stickie
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to " "
set dname to first item of (dstr's text items)
set AppleScript's text item delimiters to astid
--Show the result in a dialog window
display dialog "Desktop: " & dname
end tell
And as far as item 3 goes, I have yet to implement it, but I could easily poll via a cron job by calling the script using osascript. However, I may explore the possibility of mapping the desktop keyboard shortcuts I use to trigger the script, say, after a delay like 1 second after a control-right/left-arrow, 10 seconds after F3 or control-up-arrow. (It wouldn't catch window-drags that trigger desktop changes, but that hasn't worked anyway since I started using 2 monitors.)
Once I have that set up, I'll likely output the desktop name and a timestamp to a log so I can track time spent on each desktop.
UPDATE: I did eventually solve item 3 with an Applescript run once a minute in a cron job. I also wrote a perl script to generate a bar plot of both: how much time spent on each project (i.e. desktop) over a period of time (e.g. the past week), and a per day plot showing how much time I spent on what projects each day. Here's an example:

How do I move first responder with applescript?

I want to address the following annoyance with iTunes: After I have searched for a track (by pressing cmd+opt+f to move to the search field) I want to be able to play the first track in the songs list. Ideally I would like cmd+enter to start playing the first track in the song list and also move the focus to the song list. For example I enter 'Highway 61' in the search box, press cmd+enter and 'Like a Rolling Stone' starts playing.
My initial idea is for an applescript that moves the focus from the search field to the song list, selects the first song and plays it.
Here's what I have:
tell application "iTunes"
set first responder of (window 1) to outline "songs"
end tell
When I try to run this script Applescript Editor throws a syntax error "Expected class name found identifier" and highlights responder. This script follows the same form as many of the applescripts I've found on the web. What am I doing wrong?
Aside/rant: Applescript is the most frustrating and confusing technology I've ever had the stupidity to inflict upon myself. I hate it. I hate it. I hate it. I hate it.
Applescript's syntax is idiosyncratic, but it's not bad in the sense that you have a uniform scripting language for GUI. This was (and still is) something amazing. The strange sytanx is also not that strange once you go through Apple's language definition which can be found here.
That said, you need to open the AppleScript Dictionary of each app to see what kind of nouns and verbs are defined.
Think of an app as a library of classes and methods from the point of view of the AppleScript. Of course you can't call a method which is not defined in a library, right?
Launch AppleScript Editor, go File→Open Dictionary, and choose iTunes. You soon find that there's no such noun as first responder is defined.
The point is, the app usually only exposes its internal object structure, not every element of the UI. But usually that's enough.
If what you want to do cannot be done using the proper Applescript interface an app exposes, as a last resort, you can directly manipulate the UI elements, using a helper app called "System Events".
So, go File→Open Dictionary again, and this time choose "System Events", and check the content of "Processes Suite." It allows you to manipulate the UI. For example, to get the list of all UI elements, use
tell application "System Events"
tell application process "iTunes"
get UI elements of window 1
end tell
end tell
Have fun! Applescript looked horrible to me for a while, but it's not a bad thing once I learned I need to always refer to the dictionary.
Mac OS X Automation is a great source of tutorials.
If I understand correctly, you don't need an AppleScript to do that. Just press the Tab key to move the focus between elements. In my case, for example, pressing Tab moves the focus from the search box to the left-side selection bar then to the main list of songs then back to the search box again.
EDIT Addressing your further refinement of the question: you can get from searching to playing with two key strokes - TAB to move the focus out of the search box to the song list, then SPACE to play the first track in the selection. You can also use the arrow keys to pick a different selection.
Just for fun, though, here's one way you could do the whole sequence in AppleScript:
tell application "iTunes"
play first item of (search first library playlist for "Highway 61")
end tell
AFAIK, iTunes doesn't implement the command set first responder of. Applescript studio implements such command.

Resources