How do I move first responder with applescript? - macos

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.

Related

How to learn Applescript

I'm new in programming. I can write some Python code and I would like to write some script on a Macbook with the Script Editor.
So what is the best way to learn AppleScript? What material do I need?
I have tried to learn AppleScript with the language guide and Window Anatomy.
But when I tried to read some code, I can't understand many of the statements.
Example:
tell application "System Preferences"
activate
set current pane to pane "com.apple.preference.sound" --I can't understand "com.apple.preference.sound".What's the rule of strings like this?
end tell
tell application "System Events"
tell application process "System Preferences"
tell tab group of window "Sound"
click radio button "output" --There,I don't exactly know what's radio button,pane,table is.
if (selected of row 1 of table 1 of scroll area 1) then
set selected of row 2 of table 1 of scroll area 1 to true
set deviceselected to "外置音响"
else if (selected of row 2 of table 1 of scroll area 1) then
set selected of row 3 of table 1 of scroll area 1 to true
set deviceselected to "LG"
else
set selected of row 1 of table 1 of scroll area 1 to true
set deviceselected to "MAC"
end if
end tell
end tell
end tell
It seems I don't know these concepts outside of the language syntax. How can I learn these things?
The string is a string (a sequence of characters; surrounded by quote marks when written in literal—code—form). The content of that particular string is a Uniform Type Identifier which is just a naming convention, much like domain names in URLs except backwards.
Knowing what the various GUI widgets are called takes a passing familiarity with GUI programming. e.g. Radio buttons are the circular buttons which come in groups where you can pick any one. There is an helpful app for GUI Scripting if you really, really need it. Also, GUI Scripting is a klunky fragile brittle pig and only used as the last resort when apps don’t provide a scripting interface of their own. Which brings us to a more general point…
Knowing what the various types of objects that exist in an AppleScriptable application are called, plus what information they contain and how they can be manipulated with commands, requires reading that application’s AppleScript dictionary (File > Open Dictionary in Script Editor) plus some intelligent guesswork (since app dictionaries are almost always famously inadequate on details). A good AppleScript book will help you to develop that skill, and will save you a lot of head-scratching and time in the long run. (I was lead author on #BernardR’s book #2, btw.)
If you are serious about learning AppleScript, I strongly recommend you get Script Debugger. It is far superior to Apple’s Script Editor not only for exploring application dictionaries but also the live objects within the running application itself. The user-to-user forum there is also good for AppleScript-specific advice.
Lastly, if you are familiar with an Object-Oriented Programming language such as Python, you will find AppleScript uses a lot of the same jargon when talking about scriptable applications: classes, objects, etc. Do not be fooled. Application scripting (Apple event IPC) is not OOP: it is remote procedure calls which pass simple queries as arguments. The queries identify the data you wish a command to operate on (e.g. size of first word of every paragraph of front document) and the command tells the application what to do with whatever data it finds (e.g. set (size of…) to 18). Thus in AppleScript you can perform operations such as:
tell application "TextEdit"
set size of first word of every paragraph of front document to 18
end tell
which is not a concept you can express in OOP; it’s a lot more powerful than that. (BTW, this is why programmers hate AppleScript: because they incorrectly assume application scripting is OOP; then when it behaves in some profoundly non-OOP way it confuses the hell out of them.)
--
p.s. Good Luck. You will need it, as it is awesome and frustrating in equal measure. (Although the awesome parts usually make it worth all the hair pulling it takes in getting there.)
The name of a preference pane is not a part of the AppleScript language.
The authority on the Sound preference pane is /System/Library/PreferencePanes/Sound.prefPane/Contents/Info.plist. There, you can notice
<key>CFBundleIdentifier</key>
<string>com.apple.preference.sound</string>
This is the name of the pane.
You can consult How to know the name of UI elements using Accessibility inspector (or any other tool) and AppleScript – How can I get UI elements' names, attributes, properties, classes programmatically without "guessing" via AccessibilityInspector? to figure out how to know about radio button "output" part.
I can recommend 2 books to learn AppleScript:
AppleScript 1-2-3, A Self-Paced Guide to Learning AppleScript, by Sal Soghoian and Bill Cheeseman
Learn AppleScript, The Comprehensive Guide to Scripting and Automation on Mac OS X (3rd Edition), by Hamish Sanderson and Hanaan Rosenthal
The first book is good for scripting beginners but both books complement each other.
There are many example scripts and the authors of both books discuss key concepts that are fundamental to scripting with AppleScript.
The author of the first book, Sal Soghoian, was for several years Product Manager for Automation Technologies at Apple.

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.

How do I add song to iTunes' "Up Next" with Applescript

I'm pretty new to Applescript (literally just started today), but I can not find out how to just play an album without having to create a playlist with only one album and play that playlist. Essentially I've figured out how to search for what I want and play something, but I can only play one song at a time.
tell application "iTunes"
set search_results to (search playlist "Library" for "Monument Valley (Original Soundtrack)")
repeat with i in search_results
play i
end repeat
end tell
If I do this, it runs through every song until it hits the last one and the last one is played. I believe you can use next track in order to add something to the "Up Next", but I haven't gotten it to work. Is there a way to actually do this or do I have to succumb to playing a playlist?
Sadly, the iTunes AppleScript dictionary has no "terminology" for the Up Next queue. Even Doug's AppleScripts for iTunes, the iTunes scripting authority, has no scripts for Up Next. The next track command is just to "advance to the next track in the current playlist"— equivalent to pressing the "next" button. It seems the only way to script Up Next would be to use GUI scripting, meaning you would tell AppleScript which buttons in the Graphical User Interface to click instead of using an API. This can be quite difficult, so I think you'll have better luck if you just succumb to using playlists. Fortunately, the iTunes dictionary does include plenty of controls for creating and manipulating playlists.

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.

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:

Resources