I’ve been doing a lot of work on controlling Music.app with my Stream Deck via Keyboard Maestro and/or AppleScript, but this one has been driving me moderately batty. I want to toggle the lyrics panel, but only the one in the main window — not the one in the MiniPlayer. I have both windows open all the time, and the keyboard shortcut is the same, so … it gets complicated.
I’ve come up with two methods, both of which involve focusing the main window and then sending the keyboard shortcut. Due to certain oddities, neither one works under all conditions.
One method that works — sometimes — is this:
Tell application "Music"
activate
end tell
tell application "System Events"
try
perform action "AXRaise" of (windows of process "Music" whose title is "Music")
end try
keystroke "u" using {command down, control down}
end tell
Except it doesn’t work reliably when the Music app is in a different Space: if the MiniPlayer was the last window in focus, it gets the keystroke instead. Apparently, AXRaise
is being sent while the OS is still switching Spaces and gets lost. Inserting a delay 0.4
after the activate
command fixes it, but then it feels sluggish when I’m already in the right Space.
(Side note: the existence of that Try
block is related in some strange way. If I’m in the Music app’s Space, AXRaise
works but the rest of the script fails because of a -1708 error. If I’m in a different Space, there’s no error. What the heck? So the Try
block is there just to let my script continue in spite of the error.)
Another method that does what I want — sometimes — is this:
Tell application "Music"
activate
end tell
tell application "System Events"
keystroke "0" using command down
keystroke "u" using {command down, control down}
end tell
The trouble here is that if the main window is already in front, Command-0 acts as a toggle and closes it. Not what I had in mind. I guess I need a way to know when it’s in front and then skip that step altogether.
But if I try
tell application "Music"
activate
if index of browser window "Music" is not 1 then
tell application "System Events"
keystroke "0" using command down
end tell
end if
end tell
it behaves just like the AXRaise
method, meaning it doesn’t work at all if I’m in a different Space. I have to insert delay 0.4
after activate
again, because the index of the “Music” window is always 1 — even if it wasn’t when I left that Space! I have to wonder if that’s why AXRaise
fails as well.
I could avoid all of this hassle if only UI scripting of the main window’s lyrics button worked reliably, but the button is unnamed (!!) and its index changes depending on what I’ve been doing in the app. It starts out as “button 5,” but sometimes it’s “button 3” instead. Maddening.