Code Sample – The AppleScript Studio Workshop http://foolsworkshop.com/applescript AppleScript Studio blog with tips, scripts, and tutorials Sun, 28 Apr 2013 21:38:50 +0000 en-US hourly 1 https://wordpress.org/?v=4.5.3 Adding a Check Updates Feature http://foolsworkshop.com/applescript/2008/05/adding-a-check-updates-feature/ http://foolsworkshop.com/applescript/2008/05/adding-a-check-updates-feature/#comments Fri, 30 May 2008 03:28:12 +0000 http://foolsworkshop.com/applescript/?p=43 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.

1. First download the Sparkle module from its homepage. This tutorial uses Sparkle 1.1 and XCode 3.1.

2. Drag the Sparkle.framework into your XCode application into the folder “Linked Frameworks” of the “Frameworks” folder.

XcodeScreenSnapz004.jpg

You should now see it in your linked frameworks folder.

XcodeScreenSnapz005.jpg

Now, from the “Project” menu of XCode, choose “New Copy Files Build Phase” from the “New Build Phase” menu item.

XcodeScreenSnapz006.jpg

A new window will appear looking like this:

XcodeScreenSnapz008.jpg

Now, drag the Sparkle.framework from the “Linked Frameworks” folder and drop it onto the newly created “Copy Files” build phase listed under your application in the “Targets” section of your project.

XcodeScreenSnapz009.jpg

Now in the Info.plist file of your project in XCode, you need to add a new key. This will designate a link to the RSS file you will eventually create, called an “AppCast” which will contain the information about updates to the application. For example:

SUFeedURL
http://foolsworkshop.com/downloads/sparklesample.xml

Now switch to the “Interface Builder” application and your “MainMenu.nib” file (open it from the “Resources” folder of your XCode project if it is not open.

From the File menu choose “Read Class Files”

Interface BuilderScreenSnapz004.jpg

Navigate to your folder and you should see the Sparkle.framework folder and inside that the “Headers” folder (or actually an alias to the folder, which is deep in the “Versions” folder). Select all the files in the “Headers” folder and add them.

Interface BuilderScreenSnapz005.jpg

Once you have added the class header files from Sparkle, add an “NSObject” which looks like a blue box from the library panel into the list of files in your MainMenu.nib.

Interface BuilderScreenSnapz006.jpg

Click on this object and in the “Information” tab looking like a white “I” on a blue circle, type “SUUpdater” into the “Class” field (it should auto complete if you read the class files correctly) and press enter. This will add the required Class Actions in the panel below it.

Interface BuilderScreenSnapz007.jpg

Now create your “Check for Updates…” menu item in the application menu by dragging an NSMenuItem into the appropriate place. After you add it, you can change the “Title” of your menu in the inspector in the first tab.

Interface BuilderScreenSnapz008.jpg

Now, you need to connect this menu to the new Sparkle object you created. Control-click on the menu item and a blue line will appear. Drag this line and drop it on the “Updater” object.

Interface BuilderScreenSnapz010.jpg

See Max Karreth’s tutorial for a bit more on how to add a preference for automatic checks for updates.

Everything you need to do in the project is set up. However, you still need to set up an AppCast RSS file. There is a sample of one in the Sparkle documentation PDF and also you can download the test file used found in the Demo application. I created my AppCast RSS file using the RSS application Feeder which actually has a template for creating Sparkle RSS files (if you use this, consider editing the template and turning on the extra field for “Release info”). The important things that must be included in your AppCast RSS feed are a link to the Sparkle namespace:

xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle"

You then add a new RSS item each time you make a new update, and include an enclosure linking to your new release, which the documentation says should be named something like “Application Name App_2.0.zip”

Here is what my RSS feed looks like after I created it with the Sparkle template in Feeder. Some of these things are optional lines or extra information added by Feeder itself, but it should give you an idea of how this works:


http://foolsworkshop.com/downloads/sparklesample.xml
    A simple example AppCast for Sparkle
    Feeder 1.5.3(378) http://reinventedsoftware.com/feeder/
    http://blogs.law.harvard.edu/tech/rss
    en
Fri, 30 May 2008 11:35:15 +0900
    Fri, 30 May 2008 11:35:15 +0900

Sun, 01 Jun 2008 11:24:54 +0900

      version-20-no-useful-changes-upgrade-for-$100
      http://foolsworkshop.com/downloads/sparklesample.html

In addition to the RSS file, you might also want to post some release notes on the new version, which you can see in the above RSS is linked with the “sparkle:releaseNotesLink” tag. If such a file exists, Sparkle will display this file, which is regular HTML, when a new update is found.

You can try all this and play with a sample application here:

Sparkle Sample Project

Note: Max Karreth has already been nice enough to create a similar sample application but I had some trouble running the application.

Building this application and running should give you a chance to see how Sparkle works, as I have posted a “fake” 2.0 update. Note that the built application is labelled as “2.0” in the Finder if you choose “Get Info” after downloading the update.

Sparkle SampleScreenSnapz001.jpg
]]>
http://foolsworkshop.com/applescript/2008/05/adding-a-check-updates-feature/feed/ 3
The First Responder: Setting it to a Table Cell http://foolsworkshop.com/applescript/2008/05/the-first-responder-setting-it-to-a-table-cell/ Wed, 28 May 2008 01:58:52 +0000 http://foolsworkshop.com/applescript/2008/05/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 http://foolsworkshop.com/applescript/2008/05/using-the-first-responder-placing-the-cursor-in-a-text-field/ Tue, 27 May 2008 08:52:19 +0000 http://foolsworkshop.com/applescript/2008/05/using-the-first-responder-placing-the-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 http://foolsworkshop.com/applescript/2008/05/adding-a-help-book-to-your-applescript-studio-application/ http://foolsworkshop.com/applescript/2008/05/adding-a-help-book-to-your-applescript-studio-application/#comments Tue, 27 May 2008 05:43:55 +0000 http://foolsworkshop.com/applescript/2008/05/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.

    1. Create your files using your favorite HTML application. You can have images and CSS files as well. Put all these files into a folder and give it a name. For my example, I will call the folder “Help Folder Example Help” since my application will be called “Help Folder Example”

    2. Each file must have an additional META tag added inside the HEAD tag near the top of your HTML files with the title of your application and “Help”:

    
    

    3. After you have finished making all your help files, open the application “Help Indexer” found in your Developer/Utilities folder. Navigate and choose the folder containing all your HTML, CSS, and images. This will create an “index” for your help files which can be used to search your files in the help browser.

    4. Back in XCode, right-click on your “Resources” folder on the left and choose Add – “Existing Files…” choosing your folder with the help files and the newly created index. When you are given some more options, this seems to work for me:

    XcodeScreenSnapz001.jpg

    This should result in the files being added to your project, looking something like this:

    XcodeScreenSnapz003.jpg

    You then need to add two keys to your “Info.plist” plist file, one indicating the name of your application’s help book, and the other the name of your help folder. In my example, here is what I needed to add:

    CFBundleHelpBookName
    Help Book Example Help
    CFBundleHelpBookFolder
    Help Book Example Help
    

    5. Finally, you probably want to change the “Title” of the help menu item in “Interface Builder” to something like “Help Book Example Help” (in my case) so that it doesn’t say “NewApplication Help” when it is run. You can find the help menu item in the “1” menu under “2”

    Interface BuilderScreenSnapz003.jpg

    Now try compiling and running your application and the help book’s index.html home page should appear. My biggest complaint with the Help Book browser in OS X is that even simple files seem to load relatively slow; slower than running files directly in Safari for example. I am often reluctant to read help files since the help book takes one or two seconds longer to load than I am willing to wait for an answer. In the same time I can google a question online rather than risk the possibility that the help files are sorely lacking in documentation.

    You can download the sample XCode project demonstrating the above here: Help Book Example

    In order to write this posting and learn the techniques described here, I depended on these useful websites: a MacScripter posting on the topic and this excellent tutorial in French (I just looked at the pictures and guessed what I could from the accompanying text but the author recommends using Google to translate the site).

    ]]>
    http://foolsworkshop.com/applescript/2008/05/adding-a-help-book-to-your-applescript-studio-application/feed/ 1
    Reacting to Keyboard Input http://foolsworkshop.com/applescript/2008/05/reacting-to-keyboard-input/ http://foolsworkshop.com/applescript/2008/05/reacting-to-keyboard-input/#comments Mon, 26 May 2008 15:00:51 +0000 http://foolsworkshop.com/applescript/2008/05/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.

    ]]>
    http://foolsworkshop.com/applescript/2008/05/reacting-to-keyboard-input/feed/ 1
    Calling Cocoa String Methods in Applescript Studio http://foolsworkshop.com/applescript/2008/05/calling-cocoa-string-methods-in-applescript-studio/ Mon, 26 May 2008 10:52:10 +0000 http://foolsworkshop.com/applescript/2008/05/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 http://foolsworkshop.com/applescript/2008/05/an-applescript-replace-text-method/ http://foolsworkshop.com/applescript/2008/05/an-applescript-replace-text-method/#comments Fri, 23 May 2008 07:31:09 +0000 http://foolsworkshop.com/applescript/2008/05/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.

    ]]>
    http://foolsworkshop.com/applescript/2008/05/an-applescript-replace-text-method/feed/ 4
    Tell a Button to Trigger a Menu http://foolsworkshop.com/applescript/2008/05/tell-a-button-to-trigger-a-menu/ Wed, 21 May 2008 12:40:37 +0000 http://foolsworkshop.com/applescript/2008/05/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
    
    ]]>
    Search a String: Offset http://foolsworkshop.com/applescript/2008/05/search-a-string-offset/ http://foolsworkshop.com/applescript/2008/05/search-a-string-offset/#comments Tue, 20 May 2008 08:11:07 +0000 http://foolsworkshop.com/applescript/2008/05/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.

    ]]>
    http://foolsworkshop.com/applescript/2008/05/search-a-string-offset/feed/ 4
    For Loops in AppleScript: Repeat http://foolsworkshop.com/applescript/2008/05/for-loops-in-applescript-repeat/ http://foolsworkshop.com/applescript/2008/05/for-loops-in-applescript-repeat/#comments Tue, 20 May 2008 06:56:11 +0000 http://foolsworkshop.com/applescript/2008/05/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
    
    ]]>
    http://foolsworkshop.com/applescript/2008/05/for-loops-in-applescript-repeat/feed/ 3
    Responding to a Chosen Menu Item http://foolsworkshop.com/applescript/2008/05/responding-to-a-chosen-menu-item/ Tue, 20 May 2008 04:19:00 +0000 http://foolsworkshop.com/applescript/2008/05/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 http://foolsworkshop.com/applescript/2008/05/responding-to-a-clicked-button/ http://foolsworkshop.com/applescript/2008/05/responding-to-a-clicked-button/#comments Tue, 20 May 2008 04:15:41 +0000 http://foolsworkshop.com/applescript/2008/05/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
    
    ]]>
    http://foolsworkshop.com/applescript/2008/05/responding-to-a-clicked-button/feed/ 1
    Change the Contents of Text Fields http://foolsworkshop.com/applescript/2008/05/change-the-contents-of-text-fields/ Tue, 20 May 2008 04:12:32 +0000 http://foolsworkshop.com/applescript/2008/05/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.

    ]]>
    Center a Window http://foolsworkshop.com/applescript/2008/05/center-a-window/ Tue, 20 May 2008 03:55:01 +0000 http://foolsworkshop.com/applescript/2008/05/center-a-window/ Found a useful posting at Coding AppleScript on centering windows in AppleScript Studio.

     
    tell every window to center
    

    I used this tip to figure out how to automatically center my splash window when the application first opens:

     
    on will open theObject
    	if the name of theObject is "homeWindow" then
    		tell theObject to center
    	end if
    end will open
    

    This gets called before the window displays.

    ]]>