Tuesday, October 5, 2010

Applescript GUI Scripting Tips and Tricks...

Hi, I found some new tips and tricks for applescript GUI scripting that I think everyone should be able to figure out. I searched google everywhere and finally found some hints here and there but very difficult to find.

The first thing I wanted to do was to check to see if GUI Scripting (aka assistive devices) was enabled in the system. This is required if you want to use any gui scripting (ie, everyone doing automation) so here's the code I ended up using. This function will check to see if assistive devices is enabled, and loop to enable it asking the user. If the setting doesn't take (due to user typing in their password incorrectly, or other reason) it will reloop until either success or until you click cancel:

    on enableGUIScripting()
        tell application "System Events"
            set currentstate to UI elements enabled
            repeat while currentstate = false
                tell application "Finder"
                    activate
                    display dialog "Assistive devices must be enabled: enable now?"
                    delay 0.5
                end tell
                activate
                set UI elements enabled to true
                set currentstate to UI elements enabled
            end repeat
        end tell
        return currentstate
    end enableGUIScripting

Another thing I wanted to do and you will need to be able to do if your programming automation routines in applescript is to enable full keyboard control. This allows the "TAB" key to access all controls on a page rather than just text input fields. This is located under System Preferences -> Keyboard -> Keyboard Shortcuts -> Full Keyboard Access :
    on enableFullKeyboardControl()
        set currentstate to ""
        do shell script "defaults read .GlobalPreferences AppleKeyboardUIMode"
        set currentstate to the result
        repeat while currentstate is not 2
            tell application "Finder"
                activate
                display dialog "Full Keyboard Access must be enabled: enable now?"
                delay 0.5
            end tell
            do shell script "defaults write .GlobalPreferences AppleKeyboardUIMode -int 2"
            do shell script "defaults read .GlobalPreferences AppleKeyboardUIMode"
            set currentstate to the result
        end repeat
        return currentstate
    end enableFullKeyboardControl

Thanks to a couple websites for their help:
Assistive devices enable:
http://www.peachpit.com/blogs/blog.aspx?uk=Using-AppleScript-to-enable-GUI-Scripting-Five-AppleScript-Tips-in-Five-Days

Full Keyboard Control info:
https://secure.macscripter.net/viewtopic.php?id=25417

1 comment:

  1. Thanks for the work you put into this; very helpful. One small addition; the line "repeat while currentstate is not 2" loops forever unless the "2" is in quotes. Cheers!

    -Phin

    ReplyDelete