applescriptfinderkeyboard-maestro

Show/hide Finder, and create new window if none exist via AppleScript


I'd like to create an AppleScript to trigger via key command in Keyboard Maestro that allows me to toggle showing or hiding the Finder window(s) directly. And if when toggling to show the Finder, if there are no existing windows, create one and open it up to my home directory.

The following AppleScript works. However, there seems to be a race condition between activating the finder and detecting if there are any open windows with if not (window 1 exists), hence the delay 0.5.

The problem (which I think is a race condition in detecting the presence of an existing Finder window) results in this script frequently creating new Finder windows when one already existed. The if not (window 1 exists) doesn't always get it right.

Any thoughts, tweaks, or affirmations that this is just the way it is would be appreciated!

tell application "System Events"
    set activeApp to name of application processes whose frontmost is true

    if ((activeApp as string) is equal to "Finder") then
        set visible of process "Finder" to false
    else
        tell application "Finder"
            activate
            delay 0.5
            if not (window 1 exists) then
                make new Finder window
                set thePath to POSIX file "/Users/jon"
                set the target of the front Finder window to folder thePath
            end if
        end tell
    end if
end tell

Solution

  • Please try this simpler syntax, it uses only Finder terminology

    tell application "Finder"
        if frontmost then
            set visible of process "Finder" to false
        else
            if (count windows) is 0 then reveal home
            activate
        end if
    end tell
    

    Edit:

    To run a Keyboard Maestro macro, open Keyboard Maestro Editor, select the macro and then select Copy as > Copy UUID from the Edit menu.

    Then in AppleScript write

    tell application "Keyboard Maestro Engine" to do script "<Script-UUID>"
    

    replacing <Script-UUID> with the copied real UUID