Extending NSBezierPath

Yesterday I wrote about how to extend NSImage so it can save to a file. Today we’ll tackle NSBezierPath. NSBezierPath is pretty cool for drawing, but it doesn’t support arbitrary regular polygons, just rects and ovals (and lines and arcs). And there’s not an easy way to extract the points that make up a path. And if you could extract the points, there isn’t a way to draw dots for the points instead of stroking or filling the path. OK, enough already, let’s look at some code.

First thing in the code, we’ll define some basic trigonometry routines to calculate the points for a polygon. Then we’ll create the class itself.

from objc import Category
from AppKit import NSBezierPath
import math
def poly_point(center, r, degrees):
    x = r * math.cos(degrees) + center[0]
    y = r * math.sin(degrees) + center[1]
    return x,y
def polypoints(center, r, numPoints, degreesRotation=0):
    if numPoints < 3:
        raise ValueError, 'Must have at least 3 points in a polygon'
    rotation = math.radians(degreesRotation)
    theta = (math.pi * 2) / numPoints
    return [poly_point(center, r, i*theta+rotation)
        for i in range(numPoints)]
class NSBezierPath(Category(NSBezierPath)):
    def points(self):
        points = []
        for i in range(self.elementCount()):
        elem, pts = self.elementAtIndex_associatedPoints_(i)
        points += pts
        return points
def appendBezierPathWithPolygonWithCenter_radius_numberOfPoints_(self, center, radius, numberOfPoints):
	''' Creates a regular polygon '''
	pts = polypoints(center, radius, numberOfPoints) self.moveToPoint_(pts[0])
	for pt in pts[1:]:
    def dot(self):
        Similar to stroke: and fill:, but draws dots for each point in the
        path. Dot size is based on linewidth. Not as efficient, because it
        creates a separate NSBezierPath each time it is called.
        tmp_path = NSBezierPath.alloc().init()
        width = self.lineWidth()
        offset = width / 2
        for point in self.points():
            rect = (point[0] - offset, point[1] - offset),(width, width)

OK, hopefully the above is reasonably clear. You can follow along with any calls which are unfamiliar by firing up AppKiDo or the Apple documentation for NSBezierPath. If you’re going to use the dot: method a lot you might want to cache the path so you’re not creating a new NSBezierPath every time, it depends on what you need.

Here’s a short script you can run on the command line to create a hexagon and demonstrate fill:, stroke: and dot:

from AppKit import NSApplication, NSBezierPath, NSColor, NSImage
from Foundation import NSInsetRect, NSMakeRect
import image_ext, bezier_path_ext

app = NSApplication.sharedApplication()
image = NSImage.alloc().initWithSize_((64,64))
hex = NSBezierPath.alloc().init()
hex.appendBezierPathWithPolygonWithCenter_radius_numberOfPoints_((32,32), 26, 6)

Which results in this: 

Why am I so interested in points and dots? Well, they let me visualize control points for arcs for one thing. Perhaps tomorrow we can explore more along those lines.

Extending NSImage

I’m going to try to post smaller snippets and experiments, more frequently. I’ve been struggling with creating images in code for a game I’m working on and had some successes lately that I wanted to share. Along the way we get to play with Categories, which allow existing Cocoa classes to be extended with new methods at runtime without access to the source code. Categories are in the latest release of PyObJC, but the example I’m giving uses a fresh checkout from the Subversion repository because I turned up a bug which Ronald Oussoren was kind enough to identify and immediately fix. Since this example is already on the bleeding edge, I’ll also dabble with Python2.4 descriptors.

The specific problem I was faced with is that it is easy enough to create images programmatically, or to read them in from a file, but there was no obvious way to save them to a file. A bit of googling led me to Mark Dalrymple’s quickies which has lots of tips and tricks for programming Cocoa in Objective-C and which I got the basics for writing to an image to a file from. I pythonified it and turned it into a method of NSImage through the magic of Categories, adding a bit more along the way.

from objc import Category
from AppKit import *
from os.path import splitext
_fileRepresentationMapping = { '.png': NSPNGFileType,
                               '.gif': NSGIFFileType,
                               '.jpg': NSJPEGFileType,
                               '.jpeg': NSJPEGFileType,
                               '.bmp': NSBMPFileType,
                               '.tif': NSTIFFFileType,
                               '.tiff': NSTIFFFileType, }
def _getFileRepresentationType(filepath):
    base, ext = splitext(filepath)
    return _fileRepresentationMapping[ext.lower()]
class NSImage(Category(NSImage)):

    def rect(self):
        return (0,0),self.size()

    # If you're using the current release of PyObjC and don't feel like grabbing the fix
    # from the repository, remove this method altogether and read in from files as
    # usual (reading isn't so tricky)
    @classmethod # If you're using Python 2.3 comment this line and uncomment below
    def imageWithFilePath_(cls, filepath):
        return NSImage.alloc().initWithContentsOfFile_(filepath)
    #imageWithFilePath_ = classmethod(imageWithFilePath_)

    def writeToFilePath_(self, filepath):
        image_rep = NSBitmapImageRep.alloc().initWithFocusedViewRect_(self.rect())
        representation = _getFileRepresentationType(filepath)
        data = image_rep.representationUsingType_properties_(representation, None)
        data.writeToFile_atomically_(filepath, False)
    def fillWithColor_(self, color):

I probably should have just elided the imageWithFilePath: method, since it is the only part which is really bleeding-edge, but I was so happy to get it working that I couldn’t bring myself to drop it. In any case, it’s the writeToFilePath: method which I was looking for. In case its not obvious, this will grab the extension of the path you pass in and determine the right type of file to save. The key to saving images in Cocoa is that they have to pass through a subclass of NSImageRep and of NSData before they’re ready to write. This just encapsulates is all in one place.

While I was at it I added fillWithColor: because I thought and image should be able to do that %-)

Next up: Teaching NSBezierPath new tricks.

Oblique Strategies

Today’s Example is a simple, but full application. Our setup file is getting more complicated as we give the app a custom icon and a name which isn’t taken from the main python file. We’re finally using the menus for more than just default behaviors. We’re loading in resources at runtime. We’re adding a custom About box. And we’re taking advantage of Python standard libraries from within a Cocoa program. One icon file + 224 lines of python, XML, and HTML.

Some years ago Brian Eno and Peter Schmidt created a deck of cards for brainstorming your way through artistic blocks. Each card had one idea, and they were called Oblique Strategies. The Whole Earth Review published a list of some of the strategies, the decks went through several editions, and there were quite a number of programs written to simulate drawing a card from the deck. The Oblique Strategies Web Site has more details. You can buy the deck from Brian Eno’s site. And a group called curvedspace created a nice OS X version which you can download for free from their site.

The curvedspace app is so nice, in fact, that we’re going to slavishly imitate it. There are only a couple of problems with it. First, you can’t add your own quotes and sayings to the mix. Second, it’s free, but not open source, so you can’t patch it to allow you to add your own quotes. Tonight’s example will build a version identical to the curvedspace tool, but which allows you to choose from among several quote files, not just the Oblique Strategies. A future exercise will be to allow the user to customize it with new quotes from within the running application.

Since there’s quite a bit more code, and by reader request, this example is contained on a downloadable .dmg file. The file contains both the finished, runnable application, and all the source code. I’ll just be describing highlights of what’s different from earlier examples. You can download it all here.

What’s new? First of all, the setup.py defines a plist resource inline to map some of the application features. This gives the application a name (”Oblique Strategies” rather than picking up “oblique” from the python file, and sets up some info for the About box. The setup call is a little more complex too, including English.lproj (which holds our icon) and Credits.html (which is the content of our About box), and passing in the plist we defined.

In the MainMenu.gsmarkup we have added a bunch of menu items to the File menu, to allow the user to pick a quotation file. What’s interesting is that we’ve implemented ‘About Oblique Strategies’ and Edit->Copy, but those menu items didn’t have to change.

In oblique.py, the main script, we implement a subclass of NSWindow called TexturedWindow. This is to work around a limitation of the current version of Renaissance, which doesn’t support so-called Metal windows (because GNUstep doesn’t have them). Nicola has fixed this in CVS, so it will be in the next release, but in the meantime it is a simple class (4 lines of code) and we use the instanceOf attribute of <window /> to call our subclass in the MainWindow.gsmarkup.

Our AppDelegate is similar to earlier examples, but has grown a couple of methods. The change() method is called by our one button to select another quotation at random from the selected file (or a random file if you like). The chooseFile_() method checks to see which menu item called it, and based on the menu item, selects the file for future calls to change(). There is one support function, getQuote(filename) which uses Python standard file manipulation and the random module to pick a quote (much less verbose than doing this from Objective-C).

All that’s left are the quote files. These are simple text files with short quotations, one to a line. If a quote requires newlines, they can be embedded with ‘\n‘. The included files have quotes from Martin Fowler’s book “Refactoring,” the book “The Pragmatic Programmer,” the Magic 8-Ball, Jenny Holzer’s Truisms, and more. Enjoy!


Various small improvements. Switched the template so code doesn’t run off the edge so easily. Fixed whitespace, which I forgot to do after switching the template (thanks, Xavier, for pointing that out!). All the code for the renaissance examples is available via cvs from the SourceForge Living Code project, in the somewhat predictable cvs module, renaissance_examples. As some of the examples grow, I may only publish the highlights in the blog, and put the remainder in CVS. We’ll se how it goes.

Coming attractions. I’m researching how to build the Renaissance projects so they can be distributed (I haven’t forgotten you, Jorjun, I’m just still figuring it out myself). I can do it now (thanks, Bob!), but I want something more straightforward to build. Hopefully later tonight.

Now that we’ve got a brower for Renaissance files (see previous post), I wanted to create a markup file to show off most of the widgets and options, but realized there is no markup for tabbed views, so I’m going to try creating new tags from Python, and show how to do that. When I’ve got the tags which represent Cocoa widgets that do not yet have Renaissance representations working, then I’ll put together the demo gsmarkup file.

Then back to the Small Nerd examples and a couple of other applications (ports of existing tools, nothing terribly original yet).

It’s been nice to hear from people who are enjoying this series. If there are specific things you’d like to see, let me know, either in the comments, or at dethe(at)livingcode.org

A New Renaissance

Yesterday I laid out the issues I have with using Interface Builder to create Cocoa applications (whether in Objective-C or Python), and my requirements for a replacement. To sum up, here are the requirements again:

  • Declarative
  • Simple and powerful
  • Able to replace NIB files and Interface Builder
  • Text-based, not binary
  • Agile for rapid development, adapts to rapidly changing code
  • Able to specify simple apps completely, in code, without resorting to pictures or talking the user through mouse gestures

As I hinted at previously, I think I’ve found the tool I was looking for in GNUstep Renaissance, and as an added bonus, it can be used to create applications for Linux, unix, and Windows using the GNUstep framework. So although I’m interested mainly in building applications for OS X, there is still a chance for cross-platform compatibility.

So what does Renaissance look like? It’s and XML format, similar to HTML and Mozilla XUL (but simpler than XUL). Today I will cover how to install Renaissance and set it up to use from PyObjC.

Prerequisites (this is my setup, others may work, but I haven’t tested them).

  1. A Mac
  2. OS X (10.3)
  3. PyObjC (1.1), available from http://pyobjc.sourceforge.net/
  4. py2app (0.1.4), available from http://pythonmac.org/wiki/py2app (we’ll use this to build our double-clickable applications)
  5. Renaissance framework (0.8), available from http://www.gnustep.it/Renaissance/Download.html (this is the secret sauce)

Once you have the prerequisites installed, you need to make Renaissance available from Python. In your site-packages directory (on my machine this is /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages) add a Renaissance directory containing the following file:


import objc, AppKit, Foundation
objc.loadBundle('Renaissance', globals(),
del objc, AppKit, Foundation

Well, that was easy enough. Next up, a Hello World application.

« Previous entries Next Page » Next Page »