Scripting Cocoa with F-Script
Subject:   Good work (better formated answer)
Date:   2001-12-13 10:53:56
From:   pmougin
Response to: Good work

> How do you draw in a window using NSBezierPath? > (My drawings always end up in the fs main window.)

See the method "lockFocus" in class NSView. It allows designating the context in which drawings are done. In the following example, we open a new window and draw a rectangle inside it, using NSBezierPath:

"Instantiate and configure a window"window := NSWindow alloc initWithContentRect:(100<>400 extent:300<>300)
styleMask:NSTitledWindowMask + NSClosableWindowMask + NSResizableWindowMask

"Put the window on screen"
window orderFront:nil.

"Get the content view of the window"
view := window contentView.

"Draw in the context of the view"
view lockFocus.
(NSBezierPath bezierPathWithRect:(50<>50 extent:200<>200)) fill.
view unlockFocus.

"Ensure our drawing is actually displayed on screen"
window flushWindow.

Note that when the system will ask the view to redraw itself (for instance, this will happens if the window is resized), our drawing will disappear. This is because the view doesn't know about it. With the AppKit, the way to view objects redraw themselves is determined by the code in their drawRect: method, not by what has been drawn inside them in the past.

> can you execute a text file as a script or block?

From F-Script, you can load a text file inside a string, build a block from that string and execute the block. For instance, suppose we have a text file at path '/myscript.txt' whose content is an F-Script block literal:

"Loads the text file into a string"
text := NSString stringWithContentsOfFile:'/myscript.txt'.

"Generates a block from the string"
myBlock := sys blockFromString:text.

"Execute the block"
myBlock value.

Of course, you can combine these instructions in one line:

(sys blockFromString: (NSString stringWithContentsOfFile:'/myscript.txt')) value

If your script takes argument, just use the correct value... method.