Archive for May, 2005

Part 3 - Using py2app to Apple-fy the app

py2app provides a few more things than just packaging up the code into a bundle. To make the app more of a first class citizen in the Apple world, I’m going to add nice things like an icon, an About box and a proper name.

Apple provides quite a nice way of specifying all of this information in a .plist file and py2app is quite happy to make use of it. As the example, I’m going to take the list of birthdays made in parts 1 and 2 and improve it without changing the code, well not too much.

First step is to let py2app know where to find our .plist file. This involves a change to setup.py by creating an options entry to give the name of the .plist file:


setup(
    data_files=['English.lproj'],
    app=['main.py'],
    options=dict(py2app=dict(plist='Info.plist'))
)

Everything else is accomplished by adding in entries to the Info.plist file. According to the Mac OS X ‘Runtime Configuration: Guidelines For Configuring Applications’ guide, there are a bunch of keys that need to be set as a minimum. I’m going to go through each key and what they actually do for your app.

To give my application a name, other than main.app, it is a matter of setting the CFBundleName property in the Info.plist file. There is a bit of boilerplate required which does nice XML things about specifying schemas and encodings. I’ve also added the package type in for now, with APPL representing an Application.


<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE plist PUBLIC '-//Apple Computer//DTD PLIST 1.0//EN'
'http://www.apple.com/DTDs/PropertyList-1.0.dtd'>
<plist version='1.0'>
<dict>
    <!-- Used by py2app to generate application bundle -->
    <key>CFBundleName</key>
    <string>Date List</string>

    <!-- Package type is an Application -->
    <key>CFBundlePackageType</key>
    <string>APPL</string>
</dict>
</plist>

At this point, building the application will result in the name of the application bundle being set correctly. Additionally, the application name will appear in the menu bar and in the About box. If you do a Get Info on the application bundle, it also shows up as an Application.

There are some other fields that Mac OS X will set for you in the About box if you fill in the appropriate properties. For example:


    <!-- Version number - appears in About box -->
    <key>CFBundleShortVersionString</key>
    <string>1.2</string>

    <!-- Build number - appears in About box -->
    <key>CFBundleVersion</key>
    <string>12</string>

    <!-- Copyright notice - apears in About box -->
    <key>NSHumanReadableCopyright</key>
    <string>© Geoff Wilson 2005</string>

The About box is looking pretty good at this point, but for one key thing. That default icon simply has to go. Fortunately, it is as simple as specifying the appropriate property, and putting the icon file in the English.lproj directory.


    <key>CFBundleIconFile</key>
    <string>DateList</string>

All well and good, but I had absolutely no idea how to create an icon for Mac OS X. I’d gone through enough pain trying to get the favicon working for this site. Mac OS X icons looked much tricker. Fortunately, Mac OS X comes with its own tool for building icons, called Icon Composer. It lives under /Developer/Applications/Utilities

Icon development is something that you should take some time to consider for a real application. There is a good article at the O’Reilly site, and also some information from Apple. The short version is to drag an image into Icon Composer and save the results.

The icon file will be saved with an .icns extension, but there doesn’t seem to be a need to worry about that in the property file. In the interests of avoiding graphic design for a minute, I used the banner image from this site. This has the downside of making a solid square, but it means I can avoid Photoshop for a bit longer.

After re-building the application (to copy the icon file to the bundle), my icon turns up in all sorts of useful places like the About box, the Dock and the Finder.

About box

There are a few more properties that are required to be set in the property file. The CFBundleIdentifier property is used to uniquely identify your application. The remaining properties, I’m not too sure as to where they are used, but they seem obvious enough to set values for. English is my development environment and the executable and bundle display name are set to the bundle name so that everything matches.


    <!-- Globally unique identifier -->
    <key>CFBundleIdentifier</key>
    <string>com.pseudofish.DateList</string>

    <key>CFBundleDevelopmentRegion</key>
    <string>English</string>

    <key>CFBundleExecutable</key>
    <string>Date List</string>

    <key>CFBundleDisplayName</key>
    <string>Date List</string>

The complete Info.plist is included with the updated example. Now replete with a proper name, dock icon and an About box.

How to install Oracle on Mac OS X 10.4 (Tiger)

Install instructions are now available for getting Oracle to work on Mac OS X 10.4. I’m happily able to type sqlplus in Terminal and not have link errors. It is even nicer to have my database restored so that it has something to connect to!

The steps are as follows.

  • Type the command
  • 
     sudo gcc_select 3.3
    
  • install oracle with oracle installer
  • The success cases have been with an Entreprise installation. Your milage may vary with the other options, but they are typically a subset of Enterprise so shouldn’t pose a problem.

    At the end of the installation, the database creation don’t work (it’s normal). You could disable database creation in the install wizard if this bothers you.

  • Type the commands
  • 
     cd $ORACLE_HOME/lib
    mv libnnz10.dylib libnnz10.dylib.ori
    relink all
    mv libnnz10.dylib.ori libnnz10.dylib
    

Now you can run dbca and create a database

Note: you must ensure that your ORACLE_HOME environment variable is set before calling the relink all script.

Part 2 - Using Address Book and making an app

Having successfully created a simple Cocoa application using Python in Part 1, the next step is to integrate data from Apple’s Address Book (AB).

The PyObjC example of Address Book usage is a good place to start, and the Apple documentation includes any other information needed. I started with the example, played around a bit and then read the documentation mainly for the constants to get the fields I wanted.

The first step is to create a separate file to include the Address Book interaction. I put this into DateList.py. For a simple start, I’ve made the interaction a function that returns the data to the Delegate class. This is called dateFields(), and it creates a connection to the Address Book and loads the fields for it.


import AddressBook

def dateFields():
    book = AddressBook.ABAddressBook.sharedAddressBook()
    return bookFields(book)

bookFields generates the actual list using a list comprehension. validPerson filters the list to only include records which have the birthday field set.


def validPerson(person):
    return person.valueForProperty_(
        AddressBook.kABBirthdayProperty) != None

def bookFields(book):
    return [ personToFields(p) 
        for p in book.people() if validPerson(p) ]

I’m still in awe over how nicely the PyObjC does the translation behind the scenes. The native python list constructs loop effortlessly across the Objective C objects.

The next part in the story is to actually create the tuple with the person’s name and birthday. If you recall, this should look something like:


{'date': 1977-08-04 12:00:00 GMT, 'name': u'Geoff Wilson'}

I’ve hidden this away in the personToFields function, with two functions to get some details, as follows:


def personToFields(person):
    return {
        'date': getBirthday(person),
        'name': getPersonName(person)
    }

def getPersonName(person):
   return person.valueForProperty_(
        AddressBook.kABFirstNameProperty
        ) + ' ' 
        + person.valueForProperty_(
        AddressBook.kABLastNameProperty)

def getBirthday(person):
    return person.valueForProperty_(
        AddressBook.kABBirthdayProperty)

At this stage you should have enough code to be able to query your Address Book. Python allows you to add the equivalent of a main function to a source file. Similar to the Java usage, I’ve used this to write quick test code to my module. Better would be to write unit test cases, but this isn’t an example of TDD.

Add the following to your code:


if __name__ == '__main__':
    print dateFields()

And then run the result:


% python DateList.py
[{'date': 2004-04-04 12:00:00 Australia/Melbourne,
'name': u'Test User'}]
%

Note: if you don’t have any records in Address Book, you won’t see any results.

The change to integrate this into the user interface is to update the delegate to request the data from the dateFields() function. You also need to add the appropriate import call:


from PyObjCTools import NibClassBuilder
from DateList import dateFields

NibClassBuilder.extractClasses('MainMenu')

class DateListDelegate(NibClassBuilder.AutoBaseClass):
    def items(self):
        return dateFields()

The magical bit is that there is no need to re-compile and no need to change the user interface. You should now see something like:

Birthday list

The source code for the sample application from this tutorial is available here.

PyObjC released for Tiger (and other stuff)

PyObjC has been officially released for Tiger. This is a big upgrade, and includes wrappers for some of the new Tiger technologies, better py2app support and a heap of bug fixes.

So if you weren’t happy following the dev release using subversion, you now have no excuses. Oh yeah, and it will still work on 10.3, with some testing done for 10.2 (if you are still using 10.2 and have issues, please use the mailing list to let the developers know of any issues).

I also found a nice article if you want to start right from the beginning of almost no development knowledge at all for creating Python based Objective C applications. Assumes no knowledge of XCode or Interface Builder (IB) or python for that matter.

For something more interesting, xml.com have a very good article, Unicode Secrets by Uche Ogbuji, which explains how to use unicode properly in Python. Essential reading if you have even vague thoughts of ever using XML in an application.

Clay Shirky on Ontologies

Clay Shirky has a great article up about the history of classifications of things (ontologies).

With movements afoot on the great Semantic Web, which seem to be way too bogged down in theory without significant practical applications, he asks the question of “Where to now?”

His theory is that the concept of tagging things (much like a blog post or a del.icio.us link) will take us to the next level of knowledge integration. Search having been the light to come out of the categorisation of old.

As an aside, it is interesting how the categorisation of things follows the Long Tail. And it is the ability of tagging to support the long tail that will help it survive.