Skip to content

Adding a Check Updates Feature

One handy feature many Mac applications have these days is the ability to check for updates. There is a free Cocoa module out there called Sparkle which allows Mac developers to easily add this capability to their applications. Fortunately, it is also relatively easy for AppleScript Studio developers to incorporate Sparkle update capabilities to their own applications. This posting provides a tutorial and sample application for adding Sparkle to an AppleScript Studio application.

I first read about this on a MacScripter posting asking about this, and then found this excellent tutorial at Guimkie. There are very few differences between my tutorial below and his, but in my own tutorial I have created somewhat more zoomed in screenshots and a bit more information on the creation of appcasts. You might also want to consult the documentation on the Sparkle homepage and the PDF that comes with the download.

(Continued)

The Development of this Weblog

I changed the name of this weblog from “Fool’s Applescript Workshop” to simply “The AppleScript Studio Workshop” since I have decided to welcome other skilled AppleScript Studio coders in the scripting community to join as contributors to this weblog. The majority of postings on this weblog will try to stick closely to the following guidelines:

1) To post relatively short but lucid explanations of how to solve practical problems a developer might face in creating an AppleScript Studio application, especially if one is a beginner and not that familiar with XCode, Cocoa classes, or even the AppleScript language.

2) Whenever possible, these explanations should be accompanied by a snippet of well-commented sample code, and if the posting author’s time allows, a sample XCode project which demonstrates the solution.

3) Whenever possible, links to forum/list postings, tutorials, Apple documentation, etc. which provide the same/similar or completely different solutions to similar problems should be provided so there are other sources the beginner can turn to if they need more information.

4) Any original content created for postings be Creative Commons
licensed so it may be shared and spread easily among interested parties.

The First Responder: Setting it to a Table Cell

One of the problems I have had with using the first responder is the difficulty of setting the first responder (see this earlier posting for more on this) to a single cell in a table. After posting a question about this to both MacSripter and the official Apple email list for AppleScript Studio, a Philip Buckley was very nice to respond with a solution. You can find his explanation of how to do this here.

I have not been able to find any way accomplish this task in AppleScript. Philip Buckley’s solution uses the Cocoa method “editColumn:row:withEvent:select:” and the “call method” command to get at it (see this earlier posting for more on this)

This method takes four parameters, as his email outlines:

  • the column index — NB this is zero-based, so first column is 0, second column is 1 etc
  • the row index – NB this is zero-based, so first row is 0, second row is 1 etc
  • an NSEvent — should be nil I think, but for this purpose it seems it will accept pretty much anything, so in the example below, which I have tested, I have pased 0
  • a boolean — 1 for true
  • I created a sample XCode Project which implements his solution for others to play with. You can download it here:

    First Responder in Table Cell

    The project creates a data source for the main window’s table, fills it with some text in 10 rows, and then provides a button which, when clicked, will select the column and row indicated by the user in two separate text fields.

    The key code for the button is below:

    set theWindow to main window
    set theRow to (the contents of text field "selectRow" of theWindow) - 1
    (* I subtract one because the parameters in the Cocoa method used below is a 0-based index *)
    set theColumn to (the contents of text field "selectColumn" of theWindow) - 1
    (* I subtract one because the parameters in the Cocoa method used below is a 0-based index *)
    set theTable to table view 1 of scroll view 1 of theWindow
    set first responder of theWindow to theTable
    (* If you want the row to also be selected, uncomment the next line *)
    (* set selected row of theTable to (theRow + 1) *)
    call method "editColumn:row:withEvent:select:" of object theTable with parameters {theColumn, theRow, 0, 1}
    (* This example does not error check to see if the inputted row 
    and column numbers are greater than the total number of rows/columns *)
    

    Many thanks to Philip Buckley who responded to my posting about this problem.

    The First Responder: Put a Cursor in a Text Field

    One thing you might want to do in an application is to set the cursor to be active in (to blink in) a text field of your choosing. This is done through the “first responder” property which can be set for windows in your application. I have had a lot of trouble with this. I haven’t had a lot of success in making something useful out of reading the property, even though you can set it. If you have a reference to your window in the variable “myWindow” then you could set the cursor to be active in a field called “secondField” with a line of code like this:

    set the first responder of myWindow to text field "secondField" of myWindow
    

    You can download a very simple sample application which shows you how you can respond to the “return” key to move to the next text field. It also has some code to show you a button that, when pressed, will move the first responder to the second field on the screen.

    Download the sample XCode project here: First Responder Example

    Here is are the key lines of code involved:

    on clicked theObject
    	if the name of theObject is "switchField" then
    		set myWindow to the window of theObject
    		set the first responder of myWindow ¬
               to text field "secondField" of myWindow
    	end if
    end clicked
    
    on keyboard up theObject event theEvent
    	set myWindow to the window of theObject
    	if the name of theObject is "firstField" then
    		if the character of theEvent is return then
    			set the first responder of myWindow to ¬
                    text field "secondField" of myWindow
    		end if
    	else if the name of theObject is "secondField" then
    		if the character of theEvent is return then
    			set the first responder of myWindow to ¬
                     text field "firstField" of myWindow
    		end if
    	end if
    end keyboard up
    

    Adding a Help Book to your AppleScript Studio Application

    Once you make some progress in your application you might want to add some offline help files that can be displayed by choosing “Your_Application_Name Help” from the Help menu. Below are some instructions on how you can do this, along with an XCode project you can download to work with.
    (Continued)

    Reacting to Keyboard Input

    Another simple but useful task when developing an application in AppleScript Studio is the ability to respond to keyboard input. For example, I want my application to respond to the “return” key, in certain fields, the same way that it does when one presses the “tab” key, ie. it moves the cursor to the next field.

    Activate the “keyboard up” handler for the text field you wish to detect keyboard entries for and add some code.

    When a key is pressed, a numerical Apple “key code” is generated that can be accessed by AppleScript. However, according to AppleScript Studio documentation:

    KEY CODE: the hardware-dependent value of the key pressed; you aren’t likely to work with the key code and no constants are currently provided to specify key codes; however, you may want to experiment with possible values; (for example, for at least one keyboard, the key code for delete is 51 and for backspace is 117)

    This is not very reassuring and I don’t know how standard the numbers are from keyboard to keyboard.

    You can also access the “character” of the keyboard event which is just the literal character. Check the AppleScript document for other properties of the “event” class that may be useful to you, including booleans (true/false values) for things like: “command key down” “option key down” and “shift key down.”

    Here is some code that will detect many of the possible keys typed into an input field and then show which numeric Apple key code corresponds to that key.

    on keyboard up theObject event theEvent
    	if the name of theObject is "inputField" then
    		(* Is this the input field we are typing in?  *)
    		set theKeyPressed to (key code of theEvent)
    		(* Save the key code into a variable *)
    		set theCharacterTyped to (character of theEvent)
    		(* Save the character that was typed *)
    		if theCharacterTyped is return then set theCharacterTyped to "RET"
    		(* The return key doesn't show up nicely in the result, so let's
                    replace it with "RET" *)
    		
    		if theKeyPressed is not 76 then
    			(* 76 is the Apple key code for the "Enter" key 
                            - at least on my keyboard *)
    			set the contents of text field "showResult" of window "sampleWindow" to ¬
    				theCharacterTyped & "=" & theKeyPressed
    			return false
    			(* Returning false will allow the typing to continue without disruption *)
    		else
    			(* The "Enter" key was pressed *)
    			display dialog "You pressed the enter key, I think."
    			return false
    		end if
    	end if
    end keyboard up

    After checking to see if the user is typing into the input field (which they obviously are in a window that has only one text field receiving this handler), the key code and character of the event are put into a variable for later use (some will simply refer to this directly rather than putting it into a variable first). It then checks to see if the character typed is the return key and changes the variable to “RET” so it will show up easier in the output. The code then checks to see if the enter key was pressed (on my keyboard at least) and if not, displays the character pressed, an equals sign, and the corresponding key code. If it thinks the enter key was pressed (if your keyboard also has 76 set to “enter”) then it will display a dialog to that effect. Returning false allows the user to type undisturbed by the events. Set this to “true”, if you like, in order to see what happens to the typed text.

    You can download the sample code to try this out here: Keyboard Input Sample

    In the case of my own application, I’m looking for the user to press the “return” (key code 36 on my keyboard) or “enter” keys (key code 76) and if this is caught, I will “set the first responder” (see upcoming posting) to the next field I want the user to type into, as if they had pressed the “tab” key.

    Activate an Event Handler

    This is really basic, and explained in most tutorials for AppleScript Studio out there, but since I haven’t explained it very eloquently, here is what I mean when I say in various postings that one must activate an event handler before one adds some code.

    When you want to write some code for a button press, a menu selection, respond to a keyboard event, etc. in Interface Builder you must explicitly lay out your intentions by activating the event handler in question. For example, if you want to do something in response to the user pressing a key in a text field (see next posting), then:

    1. Click on the text field in Interface Builder.
    2. Open the AppleScript tab of the inspector.
    3. It is good practice to give your object a name here, which can be used to refer to the object in your script.
    4. Choose your applescript that you want to attach to this object in the “Script” pop-up menu here.
    5. Activate the check mark next to “keyboard up” in the “Key” section of the “Event Handlers” pane.

    Interface BuilderScreenSnapz001.jpg

    Forgetting to give an object a name, forgetting to assign it to a script and activate the correct event handler are common mistakes I have made that prevented me from getting any results.

    A handy shortcut: You can directly jump to the empty method created by activating the handler by double-clicking the relevant handler.

    Calling Cocoa String Methods in Applescript Studio

    HAS, the devleoper of appscript left a useful comment in response to my earlier posting on the offset method. He offered an example of how one might easily and usefully call Cocoa methods to manipulate strings in AppleScript Studio that aren’t available directly in the AppleScript language.

    If, for example, you wanted to use the existing Cocoa method to make a string all uppercase you could write code for a button that contains something like this:

    on clicked theObject
    	if the name of theObject is "makeUppercase" then
    		set contents of text field "inputField" of window "myWindow" to call method "uppercaseString" of (contents of text field "inputField" of window "myWindow")
    	end if
    end clicked
    

    If, instead, you wanted to have a string only capitalize the first letter of each word, then you would use the Cocoa function “capitalizedString” instead.

    set contents of text field "inputField" of window "myWindow" to call method "capitalizedString" of (contents of text field "inputField" of window "myWindow")

    You can download an example project with this example here: Call Method Example.

    A full list of the Cocoa methods for the NSString class in Cocoa can be found in Apple document NSString Class Reference. Some of these methods need to be handled differently as they may require parameters etc. There is more detail on the call method command in the AppleScript Studio documentation to be found where you can learn more about how to include parameters.

    Strings are only a simple beginning, this command opens up a lot of possibilities for using Cocoa methods that may not have equivalents in AppleScript, if done with care.

    An AppleScript Replace Text Method

    Bruce Phillips, one of the leading posters at MacScripter, posted a very useful method on his blog which you can use to find and replace text in a variable. Below is the code he created and an example so you can test it in the Script Editor.

    on replaceText(find, replace, subject)
    	set prevTIDs to text item delimiters of AppleScript
    	set text item delimiters of AppleScript to find
    	set subject to text items of subject
    	
    	set text item delimiters of AppleScript to replace
    	set subject to "" & subject
    	set text item delimiters of AppleScript to prevTIDs
    	
    	return subject
    end replaceText
    
    get replaceText("Windows", "the Mac OS", "I love Windows and I will always love Windows and I have always loved Windows.")
    

    Mr. Phillips has over 2500 postings at MacScripter and one can learn a lot from browsing through them to see the various solutions he has proposed to people’s problems.

    Matt Neuburg’s Advice on Declaring Variables

    As I fiddle with AppleScript Studio, I have been reading AppleScript: The Definitive Guide, 2nd Edition by Matt Neuburg.

    Here is a piece of advice he offers after he explains the complexities of scope for properties, global, and local variables in chapter 10:

    The ideal way to manage scope, in my view, would be to declare everything. If you need a variable to be visible in this scope and deeper scopes, then declare a property. (In a handler, merely declaring a local will do.) Otherwise, declare a local. Use global declarations sparingly, only for special occasions when separate regions of scope need shared access to a value. If you follow these rules, then any undeclared variable must be a free variable (see the next section). Thus you always know what everything is. Unfortunately, as I’ve said, AppleScript doesn’t help, so you can’t easily and reliably follow these rules, even if you want to. (( Quote from section 10.7 ))

    FaceSpan 5 and the HyperCard Dream

    I admit it. I’m one of those lost HyperCard fans, sulkily roaming through the world awaiting the return of the Messiah. That is why I’m playing with AppleScript Studio, which, for an amateur like me is incredibly unsatisfying and nowhere near the ease and intuitive beauty of the old HyperCard or SuperCard environment (though SuperCard is still lurking around in undead form, with a full Scottish resistance being waged out of Edinburgh with Revolution, I’m tired of paying so much money for solutions that always seem on the verge of disappearing from the market).

    I’m hoping that FaceSpan 5 will bring back the dream, greatly surpass the failures of alternatives like SuperCard, Revolution, overcome some of the problems of pure AppleScript and avoid the complexities of AppleScript Studio. And…is this asking for too much?…I hope the price will be reasonable.

    Read more about the development of FaceSpan 5, which is currently in alpha, on their official blog. I’m just a little concerned that the last posting was in September of 2007, as of this posting.

    The Facespan mailing list offers a bit more news.
    (Continued)

    Ruby for Scriptable Applications

    I don’t like AppleScript, to be perfectly honest. However, its deceptively English-like language was something that reminded me of the HyperCard glory days of my childhood, which where the only reason a non-programming historian like myself every made me want to tinker with coding.

    I would love to really get good at languages like Python and Ruby, especially after a few years of playing with a muddy language like PHP. However, I just haven’t ever gotten around to it.

    A number of sites I have come across mention rb-appscript. This will allow you to write Ruby scripts that can script applications normally only scriptable by AppleScript. While I haven’t tried it and it doesn’t seem to be too useful for AppleScript Studio, it may be worth a look for people who are frustrated by the limitations of AppleScript and want the power and beauty of Ruby.

    The homepage can be found here:

    rb-appscript

    Here is information on how to install it. If you have the developer tools installed, this may amount to nothing more than the command:

    sudo gem install rb-appscript

    If you want a solution to help you use Ruby for developing Cocoa applications, there is something called Ruby Cocoa, which provides a bridge to Cocoa. I’m reluctant to go out and learn Ruby only to find that the frustrations I already have with an official Apple supported environment like AppleScript Studio in XCode might be compounded when working through this kind of bridge environment. If Ruby Cocoa continues to mature and grow wider in support, I may eventually jump the AppleScript wagon and study the Ruby Way.

    AppleScript-Studio Mailing List

    Another resource for AppleScript Studio that I have found really useful (through its archives page) is the official Apple mailing list for ASS.

    Apple’s Mailing List for AppleScript Studio:

    AppleScript-Studio Home
    AppleScript-Studio Archives

    It is also great to see interesting interventions from people such as the author Matt Neuburg and many other experienced scripters that I have seen replying with some of the best posts at MacScripter.

    Tell a Button to Trigger a Menu

    One of the first things I went poking around for on MacScripter forums was simply how to get a button to trigger a menu. I was looking for a simple “do menu item” kind of command. I don’t remember where I found it but this was apparently all I needed to do is activate the click handler for the button and assign it the correct script in Interface Builder and then add a script such as the one below:

    on clicked theObject
        if the name of theObject is "doMenuItem" then
    	   tell menu item "menuItemName" of menu "menuFile" of main menu to perform action
        end if
    end clicked
    

    Add a Toolbar

    There is a sample project that comes with installations of XCode which will show you how to create a toolbar at the top of windows. This method appears to be the only way of creating a standard window toolbar if you are designing an application for OS X 10.4 or earlier versions. You can find this example code here on your hard drive here:

    /Developer/Examples/AppleScript Studio/Simple Toolbar

    For Leopard users who don’t mind building applications that require OS X 10.5 or higher, you can now create toolbars directly in Interface Builder with the NSToolbar class.

    NSToolbar

    Add the class to your window, and you will get a series of default buttons. You can add buttons to the toolbar by adding NSToolbarItem (the item to the right with the “?” image in it) and can add images for the toolbar via a popup menu in the inspector.

    The Simple Toolbar sample scripts controlled the toolbar buttons through the “clicked toolbar item” handler of the window containing the toolbar, which confused me when I tried to use NSToolbar without generating the toolbar directly in the applescript. After much frustration, I discovered that the toolbar buttons were scripted through the “clicked” handler as any other button in the window might be. There appears to be no need to necessarily use “clicked toolbar item” at all.

    UPDATE: I posted to MacScripter on a problem I had with buttons that are added or re-added when the toolbar is customized: NSToolbar error when customizing the toolbar

    UPDATE: Another MacSripter posting by regulus6633 points to problems using the new toolbar. Apparently there are problems when referring to any non-button objects on the toolbar (such as pop-up menu or a search field). My own tinkering confirms this.

    Search a String: Offset

    There are a lot of handy string functions in most languages. You can find a list of equivalents for various Python string functions here. One commonly used string function is offset, which can find a string. If you are searching for the word “needle” in a string variable called “haystack” then doing this:

    offset of "needle" in haystack
    

    will return the start position of “needle” and if it doesn’t find needle at all, will return 0.

    For Loops in AppleScript: Repeat

    This article on MacTech summarizes the loop flow control structures in AppleScript which apparently amounts to the “repeat” command.

    repeat
       -- code
    end repeat

    this will repeat indefinitely but you can exit the repeat within such a block by adding something like this:

    if stopMe = true then
       exit repeat
    end if
    

    You can also repeat a fixed number of times:

    repeat 5 times
       -- code
    end repeat
    

    You can also repeat until some condition:

    repeat while keepGoing = true
       -- code
    end repeat
    
    repeat until stopMe = true
       -- code
    end repeat
    

    Finally there is a kind of repeat which is familiar to anyone who has used increments in for loops in other programming languages:

    repeat with x from 1 to 10
       -- code which can refer to the number x which increases with each repeat
    end repeat
    

    Responding to a Chosen Menu Item

    More basics. After you create a menu and a menu item in Interface Builder, in the last tab of the inspector give it a name, select the applescript in your project where you will be adding the script for the menu item, and then give it an event handler by checking Menu: Choose Menu Item in the list of possible Event Handlers listed below.

    on choose menu item theObject
    	if the name of theObject is "myMenuItem" then
    		display dialog "You chose my new menu item."
    	end if
    end choose menu item
    

    Responding to a Clicked Button

    More basics. After you create an button in Interface Builder, in the last tab of the inspector give it a name, select the applescript in your project where you will be adding the script for the button, and then give it an event handler by checking Action: Clicked in the list of possible Event Handlers listed below.

    Then go back to your script and you can begin scripting the button in XCode. For example:

    on clicked theObject
    	if the name of theObject is "myButton" then
    		display dialog "You pushed a button."
    	end if
    end clicked
    

    Change the Contents of Text Fields

    This is pretty basic, but we all need to start somewhere. To change the contents of a text field (any NSTextField, including Labels), simple issue this kind of command:

    set contents of text field "myTextField" of window "myWindow" to "Hello, World."
    

    Make sure the “name” (not the “title”) of your target object (in this case “myTextField”) is correct in your NIB file in Interface Builder.