Adventures in Cocotron

October 27th, 2008 by glen

The Promise

The promise of Cocotron is a big one. Wrote a Cocoa app? Just add a new Xcode target, hit compile and out shoots a Windows version. Your mountains of Objective-C code now cross compiles and is no longer stranded on the Mac. You put your feet up, having just shipped a Windows app without ever touching a PC. Your cat brings you a freshly brewed cup of coffee. Read on for our journey from app to exe.

     

The Goal

Back in August, we decided that we should have a Windows version of our FileMagnet Uploader, a Mac application which connects to the iPhone via Bonjour and moves files back and forth between the desktop and our FileMagnet iPhone app. If you’ve been in this situation before, you know how much fun a line-by-line Windows port can be. Not only do you have to spend weeks hunched over Visual Studio, re-writing your entire program in a different language, but when you’re done you now have two separate code bases to manage. When a friend recommended that we check out Cocotron as an alternative, we were quite skeptical but agreed to try it out.

The Proof

Skip forward two months. We are now shipping a Windows version of our FileMagnet Uploader, built completely with Xcode from the same source files as the Mac version. Visual Studio was never opened. But wait… 2 months?

The Details

Let’s back up a bit. What is Cocotron? I’ll quote from the website:

      “The Cocotron is an open source project which aims to implement a cross-platform Objective-C API similar to that described by Apple Inc.’s Cocoa documentation. This includes the AppKit, Foundation, Objective-C runtime and support APIs such as CoreGraphics and CoreFoundation.”

In addition to this, you get a modified version of the gcc toolchain, allowing all this to be done from your Mac. The project has an MIT License.

It’s important to point out that Cocotron is targeting more than just Windows. All of the platform specific code is nicely abstracted using a bridge pattern. The Foundation project is implemented for linux too.

Cross Platform?

Let’s back up even more…

Get a couple of Mac software engineers together around a table of Chinese food and eventually they’ll start to debate the best way to do a cross-platform app. Usually, the nicest results come from using a combination of a cross-compiling core and platform specific UI code (a la Safari, Skype, PhotoShop, etc.) Anyone who’s tried to use most cross-compiling UI libraries knows that eventually what you end up with is an app that’s ugly and unruly on both platforms. At least with Cocotron, you end up with a beautiful Mac app, and hey, Windows apps are kind of ugly anyway so there’s no loss there.

Cocotron’s potential usefulness extends beyond user interface. It also includes a reimplementation of the Foundation framework. Foundation provides the powerful data structures, string handling, threading, I/O, etc., which is what makes Cocoa great for rapidly and robustly coding an app’s core logic. It would be a shame to have to use C++ for an app’s core instead of Foundation just because you need it to be cross platform. I can imagine a cross platform app which combines an Objective-C core (using Cocotron’s port of Foundation) with separate Mac and Windows native UI implementations.

Back to Cocotron

Simply follow the instructions to install Cocotron. Now, eagerly add the new Windows target to your Xcode project. Now, hit compile. Now, wait while the errors pile up like fan-boys at the Apple Store on a release day.

What’s wrong? Whoops! It turns out that your app isn’t only Cocoa after all. Okay, I’ll wait here while you go and #ifdef out all of that Mac specific code. That’s right… go find all the Carbon and other Mac-only routines (any Frameworks you’re using outside of Cocoa, such as AddressBook, CoreData, IOKit, CoreAudio, etc.) You’ll have to figure out how to port that stuff later.

Once your app is compiling, you’ll quickly realize that some methods appear at first glance to exist, but are actually just stubbed out for future implementation. Ever want to implement a Cocoa class method? Here’s your chance!

The Reality

The majority of Cocotron is spot-on brilliant, but here are some examples of the kind of things that we did to get FileMagnet up and running on Windows:

• Added unicode path support to the NSFileManager class.
• Added support for displaying truncated strings.
• Added support for drawing unicode strings. (Not very pretty support.)
• Fixed some issues with the NSSocket implementation.
• Worked around or fixed a number of UI bugs. (It was similar to trying to get a Cocoa UI to look right in both OS X 10.4 and 10.5.)
• Since Cocotron is not a complete implementation, we had to implement some methods ourselves, filling in the Windows implementation of the required Cocoa routines. A few examples:
– [NSPropertyList dataFromPropertyList:] (for binary property lists)
– [NSImage TIFFRepresentation]
– [NSFileManager subpathsAtPath:]
– [NSWorkspace iconForFile:]
– [NSMutableString replaceOccurrencesOfString:withString:option:]
• Additionally, Ken posted a few issues/requests to the Cocotron Google Group, and the team responded amazingly fast; they even implemented some functionality that we needed.

Now that the app has shipped, we’ll be merging our additions and fixes back into the Cocotron project as soon as possible.

The primary shortcoming of the Cocotron project may be the lack of a flagship product to drive the effort. It became apparent once we started the port, that the creators weren’t actively using it to create a shipping application. For comparison, take the Cappuccino project. They’re drinking their own Cocoa by using their new framework to make the awesome 280 Slides presentation tool. Cocotron desperately needs something in this vein to flush out bugs and unearth crucial but missing functionality.

I’m a PC

It’s true that we do build our app from Xcode, but we still needed to have Windows around for actually running, debugging and testing the app. However, in this day and age you don’t need to hop to a different machine. We simply used VMware Fusion.

One unexpected bonus was the ability to do source-level debugging of our Cocotron app. The website provides detailed step-by-step instructions for installing Insight-GDB. Once it’s all set up, just one click has you stepping through your Objective-C code on the Windows system. You can even step into the Cocotron framework’s source. (Don’t you wish you could do that with Cocoa?)

Also, I should point out that Windows users expect an installer, so you still do have to sit down on Windows and figure out how Windows installers and code signing work. Finally, don’t forget to struggle through Vista compatibility. Our app didn’t exactly work like a dream the first time we tried Vista. In fact, it didn’t even install.

Cocotron Evolution

Today we asked Cocotron co-creator Chris Lloyd about what the team has in store for us:

      “Cocotron development going forward will continue to focus on the needs of developers who use the project. This will revolve around completion of the existing frameworks and the addition of more frameworks. Some of the larger pieces under active development are a complete high quality Quartz 2D (CoreGraphics) rasterizer, AppKit support on Linux via X11 and a Windows cross-debugger which works with Xcode. There has been interest and some work on CoreData so hopefully we can expand on that component too. The more people use it, report bugs and submit patches the better it will become.”

It’s amazing what this team has been able to accomplish, and it sounds like they’ll continue to crank out new goodness.

In Conclusion

Good stuff, but be prepared to roll up your sleeves and join in the fun! But as Geordi La Forge would say, you don’t have to take our word for it. Try it out yourself! Our next Cocotron adventure will be a breeze now that we’ve fought through the jungle and know just what to expect. Expect it to work, but don’t expect it to be super fun.

Iron Coder Live: PoorLocation!

September 8th, 2008 by glen

We’re just back from C4[2]. Fantastic speakers and loads of Mac nerdery made for an amazing weekend trip to Chicago. The most unexpected part of the weekend for us was winning the Sunday contest. Having won Iron Coder Live last year, we weren’t planning on entering again—that is, until we found out about the amazing prize package. If there’s anything you can never have enough of, it’s Macs… and software to load onto them. If you weren’t there to watch, the entry is a bit difficult to describe but here goes.

In the spirit of the contest, we procrastinated until late Thursday afternoon and hatched a plan in a Starbucks-fueled brainstorm. (The employees at Starbucks are thoroughly convinced that we have no job.)

We had some Core Location-related ideas, but they would have involved lots of running around Chicago with iPhones, and since Wolf had given explicit permission to deviate from the theme “if the hack was cool enough”, we decided not to go the Core Location route. Once we came up with the stupidest idea on the planet, we headed out to buy Radio Shack’s last four remaining infrared LEDs and some tiny calculator batteries.

Six hours later, we had our hack ready: Using the WiiRemote.framework and some Apple sample code, we created a Mac app which could track infrared light sources using a Bluetooth link to a Wii Remote to draw colorful lines on the Mac screen. We also added an HTTP server using Cultured Code’s Simple HTTP Server Cocoa project. We then created an iPhone application to send HTTP requests to the Mac via Wifi. These requests controlled what kind of “artwork” would be generated by the Mac application. (Line color, thickness, etc.) As a finishing touch, we taped the infrared LEDs and batteries to the front of the iPhone. This allowed for a “digital whiteboard” effect. By pressing button on the iPhone’s cool UI and waving it around in a drawing motion, we were able to paint designs in the Mac program.

Friday was something of a blur and no work happened on the hack. I think I signed up for Twitter at some point. Tweet.

Saturday afternoon, we decided that we needed a “clincher” feature. A new mode was added to the application (using a UITabBarController of course) which allowed for the positioning and stamping of image files. We also added iPhone X-axis accelerometer data to the mix to allow for rotating of the stamped images by simply twisting the iPhone.

The next 24 hours was spent trying to decide what images we would use. We finally decided on Ken and Glen heads, tinfoil hats, nose glasses and fake moustaches, inspired by Josh and Dave’s Mr. Shuffle app, and the “paranoia” theme.

After spending Sunday morning in Photoshop lassoing fake moustaches, the live demo was a complete disaster. We positioned the Wii remote too far away from the Mac for the Bluetooth link to function, and our iPhones randomly jumped from out of our ad-hoc network to the conference network midway through the demo. Much awkwardness was twittered.

In the end, we somehow managed to take first place. Thanks for your votes, and thanks to all of the companies who donated software and t-shirts!

Here’s the source (875k) for our hack including Mac and iPhone projects. You’ll need Xcode 3.1, iPhone SDK and the WiiRemote.framework if you would like to build it. You’ll also need infrared LEDs… and tape…

Known issues: HTTP did not prove to be the best way to send rapid-fire requests from the iPhone to the Mac. The iPhone’s HTTP request system seems to freeze up if we send requests too quickly. Also, the IP address of the Mac server is hardcoded into the iPhone app for extra credit laziness.

One more thing: This code was mashed together in a few hours, and just barely. It contains some nasty bits and should not be used as an example of proper or efficient Cocoa programming!

So will anyone actually try this themselves? Let us know if you do!

Actual Program Output

Actual Program Output

App Store Gems Launched!

August 25th, 2008 by glen

As most of you probably don’t know, the Ecamm team has been busy working with our friends at Magnetism on FileMagnet, the original file viewer for iPhone. Today we’re excited to be participating in the App Store Gems co-operative promotion. Magnetism is teaming up with the cream of the App Store crop: Where To, Pennies, Kineo, Sketches and Groceries. What’s more, in true Mac promotion style, we’ll be donating 100% of today’s FileMagnet earnings to the following charities:

So, if you were planning on picking up some of these great iPhone apps, today is the perfect day to tap in your iTunes password! Please help us to spread the word about App Store Gems.

The Infinite Loop

June 15th, 2008 by ken

You can separate the OS X feature engineering work done by Apple into two categories. There’s the features that are exciting to the typical Mac user, and then there’s the features that are only exciting to software developers. When Apple says that they’re “hitting the pause button on new features”, they’re talking about that first category of features. From a developer’s perspective, Snow Leopard is overflowing with exciting system enhancements, tantalizing new goodies to allow for faster development and huge performance improvements.

The tradeoff triangle.
Image credit: Microsoft

Pausing to focus on stability and performance is every large software company’s fantasy. The typical process of software development is a cycle: New feature requirements are handed down from on high, developers work furiously on the new features, cut corners to get them just to the point where they’re (mostly) working, and then rush them out the door on a slipped deadline. Fixes to critical bugs come iteratively as point release updates, but the majority of the engineering team has already moved on to the next batch of new features. There’s never any time to go back and improve on things.

It’s unprecedented for a company to have this luxury: To be able to pause the infinite loop and concentrate entirely on making the current feature set work better. In the large part, working better means running faster. It also means adding new frameworks and paradigms to allow future features to be built on a firm foundation. They’re improving the underpinnings of the OS. You can think of it like Verizon’s FIOS project. Customers might not see a huge benefit today, but by replacing their copper infrastructure with fiber-optic, they’re enabling future technologies. Similarly, Apple is building a powerful new infrastructure for the future of the platform. Competitors are going to be left with crackly old wiring.

A winning strategy

Clearly, I’m very excited by this strategy. By taking a whole engineering cycle to focus on enhancements and create performance-improving technologies, Apple is going to move so far ahead of competition that the competition might never be able to recover. They’re going to skunk the competition.

Concentrating on performance improvements isn’t something new for Apple. I haven’t verified this scientifically, but from personal experience, upgrading to Leopard actually results in a speed boost for things like boot time and application launch time. This comes as a surprise to many people. We just assume that a newer OS will require a faster machine and say things like: “I’m not sure my old laptop can handle Leopard.” In fact, Leopard is a faster operating system than its predecessors. Upgrading will actually result in a performance increase.

The things I saw this week at WWDC made my eyes bug out. They’re determined to squeeze every last cycle out of the CPU (and the GPU for that matter), constantly asking the question “How can we make this faster?”. I imagine a big banner, a la Office Space, hanging above the cubicle farm in Cupertino. Another important focus is enabling 3rd party developers to easily (or even automatically) benefit from these new technologies.

With each normal development cycle, performance might move up by some small amount. (In the competition’s case, it might actually go down.) In the Snow Leopard release, it’s going to make a huge jump.

Putting all your cores in one basket

While every shipping Mac is now a multi-core machine, programming languages and application architectures have not kept up in a way that allows developers to easily take full advantage. Until now, efficiently and properly taking advantage of all available cores has been a tricky and error-prone process even for the most brilliant of engineers. Snow Leopard will solve this problem in many ways, with new language features, and a new operation paradigm which shifts the burden of threaded programming away from the developer and into the capable hands of the OS.

Who needs so many bits?

For developers, moving to 64-bit is a cheerless and time consuming process, made even worse by the fact that consumers will not even notice an immediate difference. Apple is going to do it in Snow Leopard because they know it will make things better over the long run. It’s like getting your wisdom teeth removed when they’re not yet causing any discomfort. It’s going to need to happen at some point, and better to do it now when you can schedule a convenient time for the procedure. You won’t feel better right afterwards. In fact, for a short period of time afterwards you’ll feel worse. But once you’re recovered, you’ll be glad you did it. Apple’s investing in a healthy future. Competitors are going to end up wearing braces.

As hip as a software engineer

I love that Apple doesn’t try to use the current buzzwords and trendy technologies. They could be trying to generate investor excitement with things like XML and social networking, but they’re not. Instead they’re putting lay-people to sleep with things like OpenCL and gigaflops. It’s as if they’ve put the developers in charge and everyone else is out to lunch.

Way to go Apple. Power to the Programmers!

WWDC: Culture Clash

June 13th, 2008 by ken

The introduction of the iPhone SDK has brought many fresh faces to WWDC. Specifically, developers who have been sent by their company to learn about the iPhone SDK are completely new to the Apple community.

It’s a little odd to look down the aisle at a session and see an uptight PC guy dutifully transcribing the presentation into his IBM Thinkpad. Meanwhile, Mac types on either side of him are busy in Xcode or Twitter on their sticker-covered MacBook Pros. For one thing, seeing a Windows laptop here is unprecedented. For another thing, us Mac guys traditionally don’t pay very close attention to the sessions. We’re too busy checking out the sample code or pinging friends using the hippest new methods.

I hope we see these guys again next year sporting MacBook Airs, and they’ll know to leave the necktie at home.

Peace.