Archive for the 'OS X Development' Category

BTLSockets Framework Version 1.1 Released

Monday, May 5th, 2008

This weekend I finished up my work on the first publicly-released version of the BTLSockets framework. It can be downloaded at its Google Code page. The BTLSockets framework is a wrapper around the BSD sockets API for Objective-C. It currently supports TCP and UDP connection over IPv4 and IPv6, but can be extended to support other transport-layer protocols and address families.

There are many other socket frameworks for Objective-C, such as AsyncSocket, OmniNetworking and EDCommon, to name a few. Some of these sockets are more simple, and some of them sport features not implemented by BTLSocket. In general, it is probably best to use the simplest solution which will meet your needs, so BTLSocket might not be the best framework for your project. However, BTLSocket offers the following features:

  • TCP and UDP support.
  • IPv4 and IPv6 support.
  • Extensibility to other protocols and address families.
  • Socket handler objects.
  • Portability to UNIX, UNIX-like and Windows systems.

Socket Handler Objects

The BTLSockets framework uses socket handler objects which sit between the socket and the application. These handlers can filter the data before it is read by the delegate or written to the network. This interface can be used, for example to implement encryption schemes (from simple XOR schemes to SSL) or to tokenize incoming network traffic. Socket handlers can be chained together in a list, passing data down the line until it reaches the last handler, and are portable across all applications using the BTLSockets framework.

Portability

The BTLSockets framework is implemented using classes from the Foundation framework. It should compile and run on UNIX, UNIX-like and Windows systems, using GNUStep or Cocotron, though it has not yet been tested on other systems. I hope to provide GNUStep makefiles and binaries for many systems in the future.

Ironcoder V Reflections

Monday, April 9th, 2007

As some of you know, I participated in Ironcoder V last weekend. It was an absolutely fantastic experience. I would have written about it sooner, but this last week was the first week of the new term, and, as it usually is, it was extremely busy.

First and foremost, I should extend my congratulations to Ben Gottlieb for his winning entry WikiPath. Although I was technically in the #macsb channel on irc.freenode.net when the winners were announced, I was also at work, and thus not able to properly congratulate Mr. Gottlieb. I would also like to congratulate the others who made it to the top five: Adam Leonard for Blurred Life, Josh Freeman for CrepuscularLife, Ian Gowen for LifeLike, and Joseph Wardell for Pixure. (I would include a link to each participant’s blog, but I could not find a link for everyone.) I would be tempted to congratulate everyone who completed an entry, as it is not a trivial task, but I do not want to appear to be tooting my own horn.

I am proud of my entry though. For this Ironcoder I submitted an application which implements Conway’s Game of Life using crudely drawn pieces of Life Cereal as cells. I called it Conway’s Game of Life Cereal. I even spent half an hour or so whipping up a custom icon which plays on the ambiguity of the name: Instead of depecting Conway’s Game of Life using cereal pieces, it depicts a box of cereal with pieces shaped like patterns from Conway’s Game of Life.

Because I had decided to use pieces of Life Cereal as cells, I ended up with a 50 x 30 grid of cells. This ended up being both a blessing and a curse. With such a small board, I could get away with a fairly simple algorithm, and do all of my drawing without the speed advantage of OpenGL. However, this put me at a disadvantage in comparison to some of the other entries which implemented Conway’s Game of Life more efficiently. However, I really liked the pun, and so I stuck with it. And after all, there are a few really great Conway’s Game of Life programs out there. I wasn’t going to be able to compete with them in 48 hours, and I have enough on my plate that I won’t get back to this project for quite a while, so I focused instead on

It took me less than 24 hours to complete the basic implementation of the program. I tried to program in stages. First I implemented the basic program, and then I added features one-by-one until the deadline. Each time I completed a feature, I made a zip archive of the program and source. The idea was that if any feature took too long to implement, then I would still have something to turn in. In the end, I finished almost everything I wanted. After completing the initial program, I added the following:

  • Adjustable Speed from 1 to 60 generations per second. I didn’t want to create something that might melt someone’s computer, so 60 seemed like a reasonable limit. Setting limits is a hard thing to do as a programmer, but sometimes, it must be done.
  • Allow the user to decide whether cells die when the leave the field or wrap to the opposite side.
  • Allow the user to choose from three different flavors of Life Cereal.
  • Create a custom icon for the application.
  • Write documentation for the application.
  • Allow the user to add or remove cells by dragging the mouse, instead of requiring the user to click each cell individually.
  • Allow the user to save and open patterns. Although there is a de facto standard for these patterns, because my field was so limited, I opted instead for just a char by char dump of the 2D array used to hold the pattern.
  • Custom rules for the death and birth of cells.

My application was the only Conway’s Game of Life submission which allowed the user to draw their own pattern and save it for later, but it did not, as the other implementations did, have a random pattern generator. This is probably because mine was the only non-screensaver, and the screensavers required random patterns to be interesting. I thought I could be clever by making an application instead of a screen saver, but when you look at the screensaver framework, all it contains a custom subclass of NSView with methods to set the delay between frames, a class to handle reading and writing preferences, and some functions for getting random numbers. When all is said and done, the equivalent of ScreenSaverView can be achieved with a regular NSView and an NSTimer, applications can just use NSUserDefaults, and there are plenty of ways to get random numbers. However, ScreenSaverViews can be easily made into screensavers, and since NSUserDefaults doesn’t automatically read and write defaults to the screensaver’s bundle identifier, these classes are useful to screensavers. Still, I did find it easier to use ScreenSaverView than to implement my own equivalent with NSTimer.

There were also a few things I didn’t have time for. All of the code for Conway’s Game of Life Cereal is inside a custom subclass of ScreenSaverView. I actually had a separate controller class early on, but scrapped it for efficiency reasons. I planned to later re-factor the code, but did not have time. I also wanted to implement a networking feature which would allow everyone to draw on their own screen, and when everyone was finished, the cells would animate, and if they left one player’s screen, they arrived on the next player’s. Unfortunately, I was running out of time, had only one computer to test with, and no prior experience with distributed objects in Cocoa.

But for all the small drawbacks, I feel good about my entry. I last entered Ironcoder during the Ironcoder 2/3 competition, having just begun Cocoa programming. I approached everything from a C perspective, and had no familiarity with the Cocoa classes. The result was a very embarrassing application accompanied by a text file apologizing for its lack of quality. In contrast, this was a complete application with a custom icon, extensive documentation and quite a few features for something coded up in less than two days. It was very rewarding to create and submit, as I gained more familiarity with Cocoa, and felt proud to submit an entry that didn’t look like a complete joke next to the entries of the professional Cocoa programmers.

Weekly Cocoa App Challenge #4

Saturday, February 10th, 2007

Download here.

It’s the weekend; that means it’s time to code. I was pleased to see that Chris Forsythe’s Weekly Cocoa App challenge came back this Wednesday, and I started work on it as soon as I got home today. Unfortunately, it was not as challenging as the last two were, but I still learned how to implement an NSToolbar in two different ways, so it was definitely a worthwhile experience.

I have to say, doing it in by code was not difficult at all. It took maybe 10 to 15 minutes to look up the required delegate methods and implement them. It ended up consisting of three, simple methods. Still, it was not the most obvious thing in the world.

Implementing the toolbar with GenericToolbar was even easier, and took only a few seconds. This is definitely the way to go for toolbar development, and I am excited at the prospect of Interface Builder 3.0 having this built-in.

Of course, since there are no original toolbar items in this project, I can’t go into details about the difficulty of each method. If I were to hazard a guess, that’s probably where GenericToolbar really shines. Still, it is not without a price. To use GenericToolbar, you must either include its framework, library, or classes. And from my experience with the previous challenge, it seems that UI elements created pragmatically use less space than UI elements represented in a nib file. The nib is infinitely more convenient, so I’m not advocating that developers do everything by hand, and in the end, GenericToolbar added only about 60 or 70 KB to the application when compiled as a universal binary.

Mr. Forsythe’s original application was called “TwilightToolbar”, and had an icon featuring Link from The Legend of Zelda: Twilight Princess. The application itself displayed the lyrics to the Johnny Cash song, When the Man Comes Around I put a little different spin on it, instead including lyrics from the anime series .hack//SIGN. Since I have included two different versions of the application, one which uses GenericToolbar and one which does not, I included two different songs: In the Land of Twilight, Under the Moon and Key of the Twilight, mainly because I found myself humming these songs whenever anyone mentioned the twilight in the Zelda game.

Weekly Cocoa App Challenge #3

Monday, January 29th, 2007

Download here.

It seems that despite being behind, I’ve been given a break: There was no fourth challenge this week. I’m not criticizing Mr. Forsythe as he did say that he might miss a week or two here and there, and it has allowed me to catch up.

The first thing that I noticed when I went back to re-read the NSBundle documentation was that I should have given it a more through reading last time. I’ve greatly simplified my code for loading resources.

Secondly, when I went into Mr. Forsythe’s bundle to get the image for the menu, I noticed that there was no nib file. This came as a bit of a shock because I didn’t know you could use the Cocoa frameworks without a nib file. Since Mr. Forsythe had listed the menu APIs on the list of APIs to use, I had already created the menu programmatically, but I was unsure to go about removing the nib file from my project.

I first tried simply deleting the nib file and blanking the “Main Nib File” field in the target properties. When I recompiled and ran the program, the console helpfully told me that NSApplication could not load a nib file because there was none specified. So I looked up the documentation for NSApplication. I found this little gem right near the top:

The main() function Xcode creates begins by calling a function named NSApplicationMain(), which is functionally similar to the following:

void NSApplicationMain(int argc, char *argv[]) {
    [NSApplication sharedApplication];
    [NSBundle loadNibNamed:@"myMain" owner:NSApp];
    [NSApp run];
}

Sweet, it looked like if I replaced the call to NSApplicationMain with the above code, but without the second line, I could avoid loading a nib file. And indeed, that is the case. But first I had to make the controller a subclass of NSApplication, make it the principal class, and replace [NSApplication sharedApplication] with [Controller sharedApplication]. However, NSApplicationMain is supposed to return something, so the code above is not truly “functionally equivalent.” I first tried returning [NSApp run], but that method returns void. I was worried about the application exiting if I returned 0, but I gave it a shot since I was short on time. It worked.

Compiling and running the code resulted in no complaints about loading the nib file, but nothing happened. I quickly realized that all of my code was still in awakeFromNib. My first guess was put it in applicationDidFinishLaunching:, but again the code did not execute. However, creating an init method for the controller, and using it to call a createMenu method worked like a charm.

All in all, while the information gained from the APIs was beneficial. I think that the most beneficial knowledge I gained from this week’s challenge was how to make a Cocoa application without a nib, and how to run a program in the background, but with a GUI (I’ll admit that I peeked into Mr. Forsythe’s Info.plist to see how this was done).

Weekly Cocoa App Challenges for the First Two Weeks

Tuesday, January 23rd, 2007

I’m apparently very much behind on this, but Chris Forsythe, project manager for the open-source gems Adium X and Growl has been posting weekly Cocoa challenges for the past few weeks. Unlike competitions like Ironcoder, these challenges are aimed towards beginners looking to brush up on the Cocoa frameworks. Mr. Forsythe himself is learning Cocoa and is hoping that these challenges will not only help others, but increase his own understanding of the Cocoa frameworks. Ever week, Mr. Forsythe posts a small Cocoa application with a list of classes used to create it. The challenge is to then re-implement the application using those classes.

(With all of the links in that last paragraph, this is going to look like blog spam. In a way, it is. Linking to others is a good way to increase traffic to a blog, and this blog certainly could use the traffic. However, I do like to start my posts with an introductory paragraph or two laying out the background, and often this calls for many links. I don’t put too links many in the later paragraphs, except to specific articles for the purposes of backing up my claims. Unfortunately, I’m going to throw a few more links at you.)

I was alerted to the presence of these challenges by the Late Night Cocoa podcast. I have been programming in Objective-C for over a year now, but had made minimal use of the Cocoa frameworks, instead doing most things the C way. I have delved into Cocoa some, but the sheer size of the framework is daunting, and my spare time is limited. This seemed like a good way to slowly but surely learn the ins and outs of the Cocoa framework. Unfortunately, I have missed the first two weeks of the challenge and have some catching up to do. The solution to the third challenge is due to be posted soon, along with the fourth challenge. I figure that if I can do two challenges a week, then I shall finish the fourth in time to participate in the fifth. So without further exposition, here are my solutions to the first two challenges.

Week 1: TrackingButtons

Download here.

The first challenge was relatively simple. The application contains four buttons, with titles corresponding to various shipping companies, which, when clicked, open your default Web browser to the package tracking page for that company. When the user closes the window, the application exits.

There are two obvious ways to do this. One could either create a method in the application’s controller for each button, or create a single method to open the page based on the title of the button. However, since this was such a simple challenge, I wanted to come up with a more unique way of implementing the application.

I looked through NSButton’s documentation for any NSStrings I could use to hold the URL of the page. The only two NSString fields in NSButton were the title and the alternate title. I couldn’t use the title, so I decided to try the alternate title. For some types of buttons, the alternate title is displayed when the button is pressed. It may also be used for other purposes, but I could not find any documentation to that effect. Because I used this field for something other than its intended purposes, it may have unintended side effects, either now or in the future. I would never dream of doing anything like this in production code, but I thought it was a rather unique solution to a simple (by design) challenge.

It is possible that someone else has already done the same thing. In that case, I relinquish all claims of uniqueness. However, this solution does have two benefits beyond the traditional approach. First, the size of the code is extremely small. The controller contains only two methods, each only one line long. One is responsible for opening the Web pages, and the other quitting the application. Second, the URLs of the Web sites are connected to the Buttons through Interface Builder. Any user could change the URL connected to a button, as well as the title of the button, or even add a new button, through Interface Builder.

Of course, I could have made a custom subclass of NSButton with a field dedicated to the URL, and created a custom Interface Builder Palette with it, but it seemed a little much for what is intended to be a simple challenge.

Week 2: iTunesController

Download here.

With this challenge, I did not want to use the same gimmick twice, so I did this one by the book. One thing I noticed that I did by habit was to avoid naming temporary objects which would be automatically released. This is an optimization I picked up from C++ programming. By avoiding aiming temporary objects, some compilers can preform an optimization called Return Value Optimization. I wouldn’t be surprised if the objective-c compiler does not do this, but I left it in anyway.

Also of note is the AppleScript used. My intention was to avoid an error being displayed at all costs. In that regard, my resulting script was very similar to Mr. Forsythe’s. It first checks if iTunes is running, then attempts to change the track within a try block. However, we used a different method for checking whether iTunes was running. I am tempted to proclaim that my method is more efficient, as the code is shorter, and while in the worst case, it has to check every process in the list, Mr. Forsythe’s code must check every process in the list.

Mr. Forsythe’s code also reminded me that global constants can be created using the preprocessor, and thus do not need to be an instance variable. It’s a basic technique that all to often I think of last.


Bad Behavior has blocked 11 access attempts in the last 7 days.