Search code examples
osx-lionapplescriptservicehidden-files

Why doesn't this applescript seem to work as expected?


I'm writing a service using automator. It receives no input in any application.

All it does is run this simple script:

on run {input, parameters}
--FIRST BLOCK
    tell application "System Events"
        set app_name to name of the first process whose frontmost is true
    end tell
--SECOND BLOCK
    if (do shell script "defaults read com.apple.finder AppleShowAllFiles") is equal to "0" then
        do shell script "defaults write com.apple.finder AppleShowAllFiles 1"
    else
        do shell script "defaults write com.apple.finder AppleShowAllFiles 0"
    end if
--THIRD BLOCK
    do shell script "killall Finder"
    delay 0.5
--FOURTH BLOCK
    if (app_name is equal to "Finder") then
        tell application "Finder"
            activate
        end tell
    end if
end run

I'll walk you trough it step by step:

first block: get the name of the current frontmost app and store it in a variable app_name.

second block: toggle the hidden files variable on or of, depending on its value.

third block: run killall Finder to relaunch Finder, taking the toggle from the second block into effect. Pause 0.5 sec, somehow this is necessary (don't know why, but without this the next instruction will be ignored).

fourth block: Check what the variable app_name was. If it equals Finder this means finder was active when the script was initiated, thus activate Finder once more (killall Finder leaves it in the background).

Problem: Everything works as expected but for one thing: when using this service in the Finder, Finder doesn't get activated again.

One might argue that there must be something wrong with the code in the fourth block, yet I've experimented a bit to show everything works as expected:

When I replace equal by not equal and run the script from any app that is not the Finder, Finder DOES get activated as should be.

So it seems that there only is a problem when the script is fired when Finder is in front.

(This is what the service should do: from within any app, toggle the visibility of the hidden files in Finder. When Finder was in front, it should be in front after execution of the cript, when another app was in front, this app should still be in front.)

I'm on Lion.


Solution

  • A slight modification of @regulus6633’s script works on my machine:

    -- restart the Finder
    tell application "Finder" to launch      # always launch
    if (app_name is equal to "Finder") then
      tell application "Finder" to activate  # activate separately
    end if
    

    I must admit I am not entirely sure of the why and how – the AppleScript documentation for the launch and activate commands does not seem to be adequate in Finder’s case…