Is there a way to get the path of the file in the front window of the active application?
My specific situation: I have a window displaying the content of an audio file in Audacity. (The window name is automatically the name of the file.) Before Keyboard Maestro starts slicing & dicing, I would like to have it save a backup copy of the file in the same folder as the file itself. To do that, it will need to figure out the path to the active file.
However, if you open only one file at a time, then the topmost item of the “Recent” menu always corresponds to the open file.
You can get the file path with this:
tell application "System Events"
tell process "Audacity"
tell menu bar 1
tell menu "File"
tell menu item "Open Recent"
tell menu "Open Recent"
set mostRecentFile to name of menu item 1
Then you can further process the mostRecentFile variable with KM or AppleScript…
(In this form the script works only if a file window is open.)
I’ll pay attention, but this is a macro for my use only & I’m only likely to be working on a single file at a time.
I’ve been digitizing my old LP collection and finding it takes me about 2 hours for every hour of music. There are some bits that have to be finagled manually, but a lot of it is just begging for automation and that should speed things up a fair bit.
OT – but if you have Hazel, this is something that Hazel can handle too: watch a folder and make a copy of anything new that shows up there. (That’s the gist, the details are a little more involved.) I’m guessing Keyboard Maestro might be able to work something along those lines too. The idea is to trigger your backup by watching for changes in the folder instead of watching for changes in the app.
Very clever it is, and it solves my problem—but it will work only in Audacity. Most other apps list only the file name in the “Recent” menu so that’s what the script will report, not the full path.
Changing to subject to a different aspect of Tom’s post, here’s one example of why I struggle with AppleScript: Why does the request for the menu item name have to go through a call to System Events & to the application as a process? If you phrase it as ‘tell application “Audacity” … end tell’, it fails.
Yes, but with most (or many) apps you can get the path from AXDocument as shown by @korm. The thing with the Recent menu is only a very clumsy workaround, and AXDocument is always preferable if it works. (Of course, even more preferable is to use the app’s AppleScript dictionary – if it has any.)
Because UI scripting is using “terms and commands from the Processes Suite in the System Events application’s scripting dictionary” (quoted from macosxautomation.com).
That means, tell application cannot work because the application simply doesn’t know about those commands.
I’m sure, the AppleScript experts here can give you more detailed explanations.