by Philippe Mougin
Revised June 2006
Read all the articles in this series |
Thanks to Objective-C, Cocoa is built upon a highly dynamic, reflexive and open object model. Among other things, this makes it possible to build visual object graph editors, run-time monitoring tools, object browsers and numerous other programs making use of the capabilities of the Cocoa run-time. One important application of Cocoa's openness is its integration with scripting languages. This is very useful because it allows for interactive use and easy gluing of Cocoa components.
In this article I want to give you a taste of Cocoa scripting, and to show you the level of integration that you can expect. We will use F-Script, an open source scripting language for Cocoa, to build a little graphical application. Using F-Script, we will directly program against the Application Kit, which is the Cocoa object framework for graphical user interfaces. Note that one can build this kind of application using Interface Builder, but in this article we will use the Application Kit programmatically, in order to illustrate Cocoa scripting.
F-Script can be downloaded at http://www.fscript.org.
Note: This article is an updated version of Scripting Cocoa with F-Script, which is published on the O'Reilly MacDevcenter here.
Our application is a "currency converter" similar to the one found in Apple tutorials.
The currency converter we will build using F-Script and Cocoa.
F-Script is a pure object-oriented scripting language with Smalltalk-like syntax and concepts. You can interact with F-Script through the FScript.app application, which gives you an interactive shell into which you can type instructions.
Some pointers on the F-Script syntax:
:=
denotes an assignment.
'A string'
.
"A comment"
(125<>513 extent:383<>175)
denotes a rectangle. It is equivalent to NSMakeRect(125, 513, 383, 175)
in Objective-C.
The following script can be entered into the F-Script shell using a simple copy/paste. You can also enter the intructions step by step: you will then see the currency converter interface appearing bit by bit. Of course, you can change the values of arguments used in the script or omit some instructions in order to see what happens. You can even interact with the objects after you have built the currency converter.
|
We note several interesting things straight away:
[
and
]
to mark the beginning and end of a message send. This similarity doesn't come as a surprise because Objective-C syntax for message sending is borrowed from Smalltalk.
NSWindow
,
NSForm
,
NSButton
, and
NSBox
are Cocoa classes.
NSTitledWindowMask
,
NSClosableWindowMask
, or
NSRoundedBezelStyle
are symbolic names defined by Cocoa.
alloc
,
initWithFrame:
,
setTitle:
, and so on are part of the Cocoa frameworks.The actual currency conversion is computed by an object created using the following instruction:
conversionScript := [(form cellAtIndex:2) setStringValue:(form cellAtIndex:0) floatValue * (form cellAtIndex:1) floatValue].
|
The
[...]
notation creates an object of class Block which represents a block of code that can be executed later (Block is an Objective-C class provided by the F-Script framework). In our block, we simply get the values of the fields in the user interface objects, perform the computation (simply involves multiplication) and put the result in a UI element.
Further on in the code, our block object becomes the target of the form and button objects. Thus, it is evaluated when the user hits Return or clicks on the button.
Below is the second version of the currency converter. This script is shorter because we use some neat F-Script features that we avoided in the first version for simplicity's sake. We also removed some comments (the code speaks for itself) and reorganized the program a little bit: the interface is now entirely constructed and configured before being put on screen. Finally, we added support for the Cocoa memory management system to ensure that the various Cocoa objects we create will be destroyed when no longer in use.
|
One of the new things we use in this version is the ";
" notation for cascading messages. This notation enables us to send several messages to a single receiver without having to re-specify the receiver each time.
Another interesting thing is the instruction:
form addEntry:@{'Exchange Rate per $1','Dollars to Convert','Amount in Other Currency'}
|
One of the innovative features of F-Script is that it allows us to manipulate entire groups of objects at once, even with methods that have not been specifically designed to support objects collections (actually, F-Script provides a full object query language, directly usable on Cocoa objects). This is the case in this instruction, where we add a whole list of entries to the form at once. We use the "message pattern" notation (denoted by "@
") that allows us to specify potentially complex groups of message sends. A message pattern generally involves single or multiple collections of objects: in our example, we use an array of string objects, denoted by "{
" and "}
". At run-time, the instruction will trigger the generation of these three message sends:
form addEntry:'Exchange Rate per $1'
form addEntry:'Dollars to Convert'
form addEntry:'Amount in Other Currency'
The same pattern is also used in the following instruction, where we put a whole set of views into the window at once:
window contentView addSubview:@{form, button, line}
|
In these examples, we use a relatively simple pattern. F-Script provides a syntax that makes it possible to express more complex message patterns.
All the specific concepts of F-Script, like message patterns, can be used when scripting Cocoa.
As it stands, our script is not very modular: it's just a set of instructions, using global variables, that we paste into the F-Script console in order to execute them. The following version introduces modularity:
|
In this version, we put the instructions between [
and ]
in order to make the F-Script interpreter generates a block object. We also declare, on the first line of the script, the argument and the local variables. Finally, we give the name "converter" to the block object that represents our script.
A block can take an arbitrary number of arguments and can have an arbitrary number of local variables, as well as having access to variables of its enclosing environment.
We can now invoke our script by sending it a "value" message, without forgetting to provide the required argument. For instance:
converter value:'My Great Converter'
|
Each time we invoke it, a new, fully functional currency converter is created and displayed on screen.
Since our script is now a block object, we can manipulate it like any other object: put it in a collection, pass it as an argument to methods, archive it on disk etc. There are also several facilities specifically related to blocks, including a graphical code editor. We can open it by sending an inspect
message to our block.
converter inspect
|
We have several options for saving our script. One of them is to use the standard Cocoa object archiving system. To do that, we just have to send the save
message to our block. A file panel will open and let us choose a file name and location for our block.
converter save
|
To load an archived block, we send the load
message to the sys
object (the sys
object represents the F-Script interpreter; it is always defined). Upon reception of the load
message, it will open a file panel and let us locate our archived block.
converter := sys load
|
save
and load
are not limited to blocks. From F-Script, we can use them with any object that conforms to the NSCoding protocol. This includes numbers, strings, arrays, dictionaries, etc.
Finally, since F-Script comes in the form of a framework ready to be embedded into any Cocoa application, it is easy to place our script in a standard Mac OS X executable.
We have seen what scripting Cocoa with F-Script involves. Clearly, many subjects have not been tackled in this article, such as Cocoa exception handling, Interface Builder integration, usage of custom Objective-C classes or mapping of non-object types, but you can expect a very high level of integration on these aspects.
Copyright © 2006 Philippe Mougin