Wednesday, January 11, 2006

Objective-C library interface with Apple text-to-speech example

In only a couple of hours, I managed to develop an interface to Objective-C libraries. This is now included in the Factor core. Objective-C is a static language with a runtime supporting limited introspection - you can list all defined classes, list all methods defined on a class, define new methods and classes at runtime, and invoke methods on objects dynamically. While it is not a great language, what makes it interesting is that, of course, the Cocoa API for Mac OS X is written in it.

The Factor interface is slightly awkward because method selectors have to be defined with parsing words first.

What follows is an example that uses Apple's text-to-speech library to speak a string.

We start by defining classes and methods we need.
OBJC-MESSAGE: id alloc ;
: NSASCIIStringEncoding 1 ; inline
OBJC-MESSAGE: id initWithCString: char* encoding: uint ;
OBJC-CLASS: NSSpeechSynthesizer
OBJC-MESSAGE: id initWithVoice: id ;
OBJC-MESSAGE: bool startSpeakingString: id ;

Then, a utility word to create new NSStrings:
: <NSString> ( string -- alien )
NSString [alloc]
swap NSASCIIStringEncoding [initWithCString:encoding:] ;

Finally, we can use the above words to speak a string:
NSSpeechSynthesizer [alloc]
f [initWithVoice:]
dup "Hello from Factor" <NSString> [startSpeakingString:]

I'm still trying to come up with a more natural way to fit this into Factor syntax. Merging the selector into a single word name is pretty tacky.

In a future release, probably 0.81, I will write a Cocoa bindings and a Mac OS backend for Factor's UI.

In other news, I'm slowly converting the handbook from LaTeX into the Factor online help markup. I guess I'm about half-way through.

No comments: