Manual Input Sessions

April 23rd, 2008

In Computer Administrative Debris, I briefly discussed the idea of “directness” in interaction design. I described a “direct” interaction model as one where the visual representation of the content and the interface to the content are the same. A direct interaction model also implies some sort of physical interaction with content. Today, we most frequently use the mouse as an extension of our bodies to “point” at objects on the screen and to “drag” or “drop” them. With gesture and touch-based technologies entering the mainstream, these interactions will become more and more concerned with the movement and/or form of the user’s actual body.

A beautiful and extreme example of directness in an interface design can be found in the the software developed by Golan Levin and Zachary Lieberman for their 2004 audio/visual performances, Manual Input Sessions.

The Manual Input Sessions is a series of audiovisual vignettes which probe the expressive possibilities of hand gestures and finger movements.

Using a custom hardware/software setup, they developed interfaces for creating and composing audio in real-time that incorporate physical objects and the body into the interaction models. Users of this software literally mold the audio with their hands over time.

Also, when you watch the videos, notice how each interface has environmental characteristics that aid the user in creating and composing the audio. This is a clever way to add extra meaning to the input data. It also infuses the interfaces with a sense of play and exploration, so they become much more instrument-like and less tool-like.

[these videos need sound]

NSViewController, the New C in MVC - Pt. 2 of 3

April 17th, 2008

In the last post on NSViewController, I described the need for a view controller class that is part of a sound controller architecture, especially when developing an application with a single window interface. In this post, Jonathan Dann and I will share the design we came up with for integrating NSViewController into the existing Cocoa MVC application architecture using NSWindowController as the glue.

Before, we do that…

Meet Jonathan.

I’m currently training with the National Health Service in the UK, working towards becoming a state-registered Medical Physicist. I was introduced to programming during my Bachelor’s degree where I did a short course in C. During my Master’s degree I learnt some FORTRAN and then had my first experience of object-oriented programming during that year. Since then I’ve been learning as much as I could about Cocoa, design patterns, and the whole world of Mac programming. I’ve begun to write my first app, which will be available sometime around September, which really began life as a personal project when the tool I was using didn’t work right and didn’t fit properly within OS X.

As my code grew in size I soon realised that I needed a controller for some of my more complex view behaviour, NSSplitViews, NSTextViews, NSOutlineViews all need delegates to unlock their power and when all of this was in the same window controller I got the feeling it was doing work that it shouldn’t have to. I started using NSViewController and came to the conclusion that it didn’t quite fit in my design, after considering how MVC should work I asked on cocoa-dev how other people use it. Sure enough, it sparked some conversation. I think that Apple has left the use of this class up to developers intentionally, maybe they will extend it in future releases, maybe having a structured controller system seems a little abstract for smaller programs, but I think it makes things easier to maintain in the long-run.

After using the class for a while I am of the mind that each view in an app could potentially have its own controller, although this would probably be overkill; the only structure that then makes sense is a tree, just like the view hierarchy. I now use these classes extensively to inform the views, for example, how they should look: the view can then draw itself based on those options it gets from its overlord.

The XS (extra special) Controllers

Our solution includes to two classes:

  1. XSWindowController, an NSWindowController subclass
  2. XSViewController, an NSViewController subclass

You can find these classes in the example project (XCode 3.0). Dowonload it here.

The Goal of This Design

The goal of our design is simple: We want a way to manage a group of view controllers in a way that fits in nicely with the current Cocoa MVC architecture.

When building a Cocoa app, the controller layer of the architecture can be described very loosely as:

  • NSDocument contains a list of NSWindowControllers
  • Each window controller has an associated window
CocoaArchitecture.jpg

We want to extend this design so that:

  • NSDocument contains a list of NSWindowControllers*
  • Each NSWindowController conains a list of NSViewControllers
  • Each NSViewController contains a list of subcontrollers
  • Each NSViewController has an associated view
XSArch.jpg

*Our changes happen beneath the document layer, so it is also a valid design for applications that aren’t document-based.

XSViewController and XSWindowController

In order to meet our goals, we enhanced Cocoa’s NSWindowController and NSViewController classes.

In XSViewController, we added a list of subcontrollers and the necessary methods to manage that list. We also gave the view controllers a reference to the window controller.

In XSWindowController, we added a list of view controllers. The window controller is the “host” for the view controllers, so when the window controller is created and destroyed by the document, it does the same to the view controllers. The window controller also does some extra work that is necessary for the view controllers to be integrated smoothly into the existing Cocoa controller architecture. We’ll describe this work further down.

In this setup, you would use the following XSWindowController methods to add and remove view controllers,

- (void)addViewController:(XSViewController *)viewController;
- (void)removeViewController:(XSViewController *)viewController;

In XSViewController, you can nest controllers and manipulate the structure of the controller tree using several methods that will be familiar to those who have worked with mutable arrays,

- (void)addChild:(XSViewController *)child;
- (void)insertObject:(XSViewController *)child inChildrenAtIndex:(NSUInteger)index;
- (void)insertObjects:(NSArray *)children inChildrenAtIndexes:(NSIndexSet *)indexes;
- (void)insertObjects:(NSArray *)children inChildrenAtIndex:(NSUInteger)index;
- (void)removeChild:(XSViewController *)child;
- (void)removeObjectFromChildrenAtIndex:(NSUInteger)index;

As long as you use these methods to add and remove view controllers from the application, you will get all of the benefits of the design.

Quick design note:

We want to note here that we considered a design where the window controller contained one view controller that would be the root of a single view controller tree. We chose to keep a list of view controllers in the window controller because it feels redundant to have to make a second controller that represents the entire window.

In a perfect world, the view controllers and window controllers would actually be the same class, so that the window controller would be the root of a single tree of controllers. This isn’t possible, but we decided that we would design with that structure in mind anyway.

Working with Cocoa

So, after we had this system set up and running, making sure that memory management was handled properly, we had to handle some Cocoa-specific behaviors so that the view controllers were well integrated into the Cocoa application architecture. This is the “glue-code” of this design. There are two Cocoa-related issues that we had to consider.

Cocoa Consideration 1: Taking care of the Responder Chain

NSViewController is a subclass of NSResponder, but it needs to be added to the responder chain to receive action events from things like buttons and menu items. We decided that our design should patch the responder chain so that it runs through the view controllers like this:

ResponderChainSmall.jpg

We looked at two approaches to solving this problem. The first approach would be to handle the responder chain in the NSViewController class, so that when a view controller was added or removed from the tree, its super controller would make sure the responder chain was patched together correctly.

The other approach is to have the window controller do the responder chain patching whenever a view controller is added or removed.

Both of these approaches have their advantages and disadvantages.

The first approach would keep things logically clean and less glue-like. The view controllers wouldn’t have to communicate back to the window controller when they add or remove their subcontrollers. If this were the perfect design world, where the window and view controllers were in the same tree, this would be the obvious way to maintain the responder chain throughout a single hierarchy of controllers.

The second approach is just more simple in this particular setup. Since this isn’t the perfect design world, the code that adds the view controllers to the responder chain would have to be repeated in both classes anyway. Letting one class handle the responder chain keeps this code centralized.

We decided to use the second approach. We don’t feel that there is a perfect solution to this problem and that either approach works fine.

The method that patches the responder chain is in XSWindowController:

- (void)patchResponderChain;

The source code will show how simple it is to keep the responder chain looking like it does in the diagram.

Consideration 2: Bindings and Observations

Bindings and Key-Value Observing are powerful Cocoa mechanisms that help us to keep our controllers and our data models separate. Most view controllers and window controllers will have bindings or KVO set up in some way.

In NSViewController, there is the idea of a “representedObject”. According to the documentation of NSViewController:

Declaring a generic representedObject property, to make it easy to establish bindings in the nib to an object that isn’t yet known at nib-loading time or readily available to the code that’s doing the nib loading.

This is a handy feature of NSViewController, especially if you are setting up all of your bindings in Interface Builder, but in a more complex setup, the single “representedObject” may not be the best way to expose a view controller to the data in an application.

There are situations where you might want to set up several KVOs and bindings in code and then remove them when you don’t need them anymore. If you forgo the “representedObject” as a means to set up KVO with your application’s data, you might come across this message in your logs when you close the document:

An instance (so-and-so) of class (so-and-so) is being deallocated while key value observers are still registered with it. Break on _NSKVODeallocateLog to start debugging.

We decided to go ahead and handle the possibility of these situations by adding a method to XSViewController called,

- (void)removeObservations;

This gives the view controllers a chance to remove observations or bindings that they set up in code before the data is released. The window controller has to manage the timing of this. In XSWindowController, we do it right before the window closes, in an implementation of the window’s delegate method,

- (void)windowWillClose:(NSNotification *)notification;

The window controller tells its view controllers to “removeObservations” here and they pass the message on to their subcontrollers. The window controller and document can then release data as they normally would in their implementations of “dealloc”.

Quick notes on subclassing:

If an XSViewController subclass implements the “removeObservations” method, it is responsible for calling super’s implementation so that the message will continue to be propagated down its branch of the tree.

If an XSWindowController subclass needs to implement “windowWillClose”, it should be sure to call super’s implementation so that the view controllers will get the message to remove their observations. The timing of this message is important, so if you are releasing some data here, be sure to call super first.

Using “windowWillClose” for a feature like this may not be the best solution, but as far as we can tell, it seems like the most convenient place to perform this task.

That’s It.

With these few enhancements, we now have two new abstract super-classes for our controllers, XSWindowController and XSViewController. When we subclass them to build our UIs, we get the controller architecture that we illustrated at the beginning of the post and the following features built in to our view controller:

  • Automatic memory management!
  • Automatic inclusion in the responder chain!!!
  • A designated method for removing observations or bindings!
  • A relationship with the window controller and document!

This design will become more and more useful as your single window interface becomes more complex, especially as your feature set changes over the life-time of your development. With this architecture in place, you have more flexibility to try things out and change your design without worrying about breaking the responder chain (which is not that easy to debug) or causing memory leaks by accident as you’re working rapidly to test UI designs. As long as you keep to MVC design principles, it is possible to create self-contained view controllers that can be plugged in to, and unplugged from, your UI with very little hassle.

Next Time…

First, thanks so much to Jonathan for working on this post with me. It was great to have the chance to brainstorm with another developer, especially one whose applications are completely different from the ones I work on every day. Working with him on this design helped to get me out of my usual mind-set and to isolate the issues that are truly common to any Cocoa application rather than unique to my own projects. This has been an educational and super-productive experience for me – Thanks, Jonathan!

AND a another big thanks to Jonathan for setting up the Xcode 3.0 example project and the source code!

In the next and last post about NSViewController, I’m going to discuss its relationship to NSView and the view hierarchy in more detail. One of the many important jobs of a view controller is to help to build and manage the view hierarchy during runtime. This is especially important when coding a single window interface that needs to give users access to many different features that can’t all be displayed in the window at one time.

Anyone who is sick of me writing about autoresizing should just skip the next installment ; ) ( or in Japanese, ^_- )

Resources

The example project contains XSWindowController and XSViewController, which contain all the nitty-gritty implementation details. There is also an example app that shows how you could subclass these classes to build a UI based on the XS controllers.

Cocoa Event-Handling Guide: The Responder Chain

Introduction to Document-Based Applications Overview

NSViewController Class Reference

NSWindowController Class Reference

Introduction to Key-Value Observing Programming Guide

Introduction to Cocoa Bindings Programming Topics

UPDATE 04/23/08

We updated the example project today. The biggest change we made is in XSViewController. We were previously setting the “representedObject” of child controllers to be that of its parent. In the new version we don’t deal with “representedObject” in any way. You can just use NSViewControllers methods to set them case-by-case.

XCode Project

Just the Source Code

Just XSViewController and XSWindowController

NSViewController, the New C in MVC - Pt. 1 of 3

April 9th, 2008
iPhoto.jpg

Applications like iTunes and iPhoto have established a single window interface as the de-facto standard for modern Mac UI design. This design is great for end users, who no longer have to switch between several windows to be productive with their software. For developers, on the other hand, this design poses several challenges in terms of interaction design and software architecture, especially in the view and controller layers of the MVC architecture prescribed by Cocoa. This post is the first of three that will address this architectural design problem and, more specifically, examine the role of Cocoa’s new NSViewController class in this design.

There are at least two major architectural issues that have to be addressed by the interface developer when coding this kind of interface. First, a single window interface requires a software architecture that can effectively handle dynamic changes in the view hierarchy during runtime. I’ll address this issue in more detail in the third post on this topic.

The second issue that needs to be addressed is that in a single window interface design, a great deal of burden naturally falls on NSWindowController. In this type of setup, the application’s main window controller is responsible for handling a majority of the user interface. In other words, the interface code for an entire application, apart from a few dialog windows here and there, is expected to go into one single class. This code quickly becomes unmanageable and unmaintainable as the feature set changes and grows. It is natural to start to break this code up into logical groups of subcontrollers and to develop a system to manage and maintain these groups.

To accomplish this, many of us have already come up with our own “view controller” systems to extend our controller architecture. Apple has also started to address this issue by adding NSViewController to the Cocoa SDK in Leopard.

A standard view controller class is a great idea and welcome addition to Cocoa. One particular feature, the built-in memory management of objects in nib files, makes NSViewController a very attractive alternative to using a custom view controller. However, this class seems to have been left out of the controller layer of Cocoa’s MVC application architecture. Apart from being a subclass of NSResponder, there is no indication from the documentation or the class’s design that it is intended to be a part of the current controller architecture, but at the same time, it cannot be functional on its own. So where does NSViewController fit into a Cocoa app and how can developers use this class effectively to build a solid controller architecture in their applications?

NSViewController and the Cocoa MVC Architecture

AppArchitecture.jpg

For larger projects, specifically projects with single window interfaces, the view controllers form a significant portion of the software architecture and it would make sense for there to be a standard way to approach view controllers as a general design problem. Unfortunately, the Cocoa documentation doesn’t give developers any hint as to what that approach should be. There are some clues in NSViewController’s API about how you could patch a single view controller into a specific area of your current design, but nothing that suggests a holistic design strategy.

The conceptual documentation of Cocoa’s “Document-Based Application Architecture” hasn’t been updated yet to explain how the Cocoa engineers intend for us to incorporate NSViewController the current application architecture. For example, the section that describes the “Key Objects” in the architecture makes no mention of NSViewController, and because of that, the paragraphs on “Typical Usage Patterns” still suggest that:

If your document has only one window, but it is complex enough that you’d like to split up some of the logic in the controller layer, you can subclass NSWindowController as well as NSDocument. In this case, any outlets and actions and any other behavior that is specific to the management of the user interface goes into the NSWindowController subclass.

Clearly a single NSWindowController subclass isn’t going to manage the whole user interface for an application like iPhoto. This would be a perfect place to discuss the role of NSViewController.

I’ve given a lot of thought to the possibility that maybe it is better for Apple to leave this particular design decision to the developers. As I mentioned, the view controllers in an application can grow into a significant portion of the architecture and it is annoying when Cocoa’s designs clash with your own. However, if this is the case, what is the point of adding a view controller to Cocoa? Those of us that have our own view controller system design already have our own view controller class that works in that design. What is the incentive to use NSViewController instead of our own class if it doesn’t present a solution to the larger problem?

I’ve found from my own experience and from talking to other developers, that the design of a view controller system is the kind of design that tends to solve itself naturally within the current Cocoa MVC architecture. There isn’t much room for imagination when it comes to its most basic structure. If you ask developers how they organize their controllers, you’ll almost always get some variation of the same basic design: view controllers own and manage a list of subcontrollers and the window controller owns and manages the view controllers. It isn’t much different from the window and the view hierarchy. The window has a content view and the content view has a list of subviews which contain a lists of subviews, etc.

In fact, this particular relationship – the window and its views to the window controller and its view controllers – is very tight. The view controllers and the window controller build and manage the view hierarchy. The window controller has to add the view controllers’ views to the window’s content view. On top of that, the window controller needs to provide a way for the view controllers to enter the responder chain and, if there is a document, it should also give them access to that. It seems logical that the relationship between NSWindowController and NSViewController should exist by default. The view controllers are, after all, an extension of the window controller.

When programming a large, single window interface, the first enhancements a developer is likely to make to NSViewController, before they can effectively use it in their application, is to add a list of subcontrollers and implement the methods to manage the list. The next thing would be to establish some kind of relationship between this structure of view controllers and NSWindowController. These enhancements are enough to make NSViewController a key player in the current Cocoa controller archtitecture.

Taking the Plunge

The modifications to NSViewController that I mentioned above are simple enough for developers to make on their own. But there are certain caveats that come up in the implementation details that are directly related to Cocoa. These “gotchas” are not obvious until you start to test the design, but they also have to be dealt with before NSViewController can work effectively within the current controller architecture.

This is how I met Jonathan Dann on the Cocoa-dev list. Jonathan’s post was titled, “Correct use of NSViewController”. The title caught my attention because I had just finished my view controller design the week before. I was not too surprised to see that his question had to do with implementing the exact design I’ve described in this post. A few others chimed in with their solutions and it was very clear to me that this design is very obvious and that the issues in it were not unique to my implementation.

Jonathan and I continued our discussion off-list and decided that we would write about the experience we had with NSViewController. In the next post, he and I will describe the issues we came across when we tried to incorporate NSViewController into the Cocoa architecture and also provide our subclasses of NSViewController and NSWindowController as an example of how it might be accomplished.

To be continued…

Resources

Introduction to Document-Based Applications Overview

NSViewController Class Reference

NSWindowController Class Reference

NSViewController documentation bug report - rdar://problem/5794739

Sparkle And Spin

March 25th, 2008
paul_rand.jpg

I found this 1993 video of Steve Jobs being interviewed about Paul Rand over on Paul Robinson’s site. It means so much to me when I see/read/hear someone that I admire admiring someone else that I admire.

Towards the end of the interview, Jobs is asked what his favorite Paul Rand work is. His answer is also my favorite – an offshoot of his famous IBM logo. It combines the wit and playfulness of his children’s illustrations with the discipline and craftsmanship of his corporate logos. Rand’s personality shines in this image:

eye-bee-m.jpg

Here are some of the children’s illustrations that I lifted from this post. “Sparkle and Spin” is the title of one of the children’s books he created with his wife, Ann.

paul-rand-design-work-2.jpg
paul-rand-design-work-1.jpg

And some of the corporate logos we all know too well…

PaulRandLogos.jpg

There’s an article on Design Observer with a funny story about how the Enron logo got its green after Paul Rand’s death in 1997. The middle prong of the E was originally yellow. The article describes all the fanfare and celebration that surrounded the unveiling of Enron’s new corporate identity but…

Within hours, the world would laugh it off the stage. Houston faxed the logo to Enron’s offices in Europe. But in transmission the middle, yellow prong disappeared, leaving the new design meant to celebrate Enron’s triumphant ascension looking more like an electric plug. Worse, to the Italians it resembled an obscene hand gesture, one that meant about the same thing as shooting a middle finger at an American. The European executives roared with laughter: now they had a new way to win Italian customers.

Back in Houston, dismay grew: the yellow prong also vanished when run through the copying machine. Somehow, Enron had spent millions of dollars on a new business logo without bothering to check if it worked in business. Soon the hallway signs went down, the new cards and letterheads were shredded. With no fanfare, another logo was introduced, replacing the yellow prong with a green one.

The symbol meant to carry Enron into the next millennium hadn’t lasted a week.

I would love to hear Rand’s comments on this teeny graphic design mishap.

One last treat. The design company, Imaginary Forces, did a great job animating Paul Rand’s work. The animations are inter-cut with clips of Paul Rand speaking about design. They’ve really captured his spirit with these animations.

Hi, I’m Cathy

March 23rd, 2008

I’m feeling absolutely terrible because I snapped at someone on the Cocoa-dev list today. I was super bitchy and unhelpful to someone who asked a simple question. It was completely inappropriate and uncharacteristic of me. I hate it when I see people getting impatient with others who are simply reaching out to the community for guidance so I’m kind of mad at myself now.

The reason that this is bothering me so much is that I love to help people learn, especially beginners. I’ve always been this way. When I was in school, I always got jobs in the computer labs because I enjoyed helping people figure out how to use the software (getting keys to the equipment room was nice, too). When I moved to New York City years ago, with no real clue about what I was doing with my life, I got a job at the Soho Apple Store giving lessons in the theater. At the time, we gave free lessons in Final Cut Pro, After Effects, Photoshop, Shake, etc. It was great because the store let us design our own lessons for the Pro Apps. We didn’t have to give the standard Keynote presentation you see in Apple Store theaters today. We really taught people there and we had an audience that wanted to learn and engage with us. I admired the service the store was providing the community and I had a blast.

The guilt I’m feeling right now is also magnified by the growing visibility of this blog. I really had no idea that anyone, other than the few people I know personally who develop Mac software, would be interested in reading any of this. I started it so that I would be forced to articulate my thoughts and ideas in writing. It was like a school assignment for myself - an exercise to stretch my brain. But the internet is fast, especially with services like Twitter, and the numbers have been rising every day. This is good and bad. Good because I find myself in a position to help people again, just like the good old days at the Apple Store, bad because I have to take some measure of responsibility for what I say here and places like the Cocoa-dev list, and this isn’t what I was after when I started out a month ago.

But, that’s what I have so I’d like to introduce myself for real and explain my intentions a little bit. I know that the couple of sentences on my ‘About’ page aren’t very forthcoming.

My name is Cathy Shive and I’m a Cocoa developer. I work for a New York City company called Box Services, LLC. Their business is digital photography with a focus on the fashion industry. I’m part of a small software team that develops their in-house tools. I love the projects that I work on at Box and I admire my teammates. They’re incredibly talented and I learn from them every day, more than I ever let on ; )

My background is in arts and design. I’m a self-taught programmer. Basically, I was a power user until I got soooo into software that I had to learn how to make it myself. My interests have always been in interface design. My first apps were video apps centered around some kind of novel interface idea. I learned how to program on a Mac using the QuickTime API, OpenGL and C++. Once I started using Cocoa and Objective-C on a regular basis, I quickly learned to appreciate the importance of a good API and my “interface” interests grew into developing frameworks and, what I hope will be, good APIs. I’m also completely obsessed with software architecture and ‘design patterns’. I can’t quite put in words why, but it fascinates me to no end.

As I mentioned earlier, I started this blog as a way to develop my ability to articulate the thoughts and ideas that I have about my work. When I started, I didn’t have a clear plan set for what the content would be exactly or who my target audience would be, but I knew that it would involve UI design and programming UIs with Cocoa and that it should be interesting to both designers and developers. I thought that each could learn a little about the working processes of the other. I truly believe that these two fields are going to merge in a big way in the coming years. The Mac platform is a perfect place for this kind of union because it has a very rich history in both fields. We stand on the shoulders of giants like Alan Kay, Susan Kare, and Jean-Marie Hullot. I can’t think of a place I’d rather be.

My first post was a criticism of a feature in the Cocoa framework. I’m going to continue to do this because I see a specific weakness in Cocoa that I believe needs to be addressed. It’s probably obvious by now, but I’ll go ahead and name it clearly. Cocoa should be on the cutting-edge when it comes to support for interface development, but as it is, there are very important features that are barely usable – the layout and styling features. These are the most basic tools that an interface designer and developer needs to do their job. In the case of styling, there is no strategy at all and in the case of layout, there is one very broken mechanism. Imagine if something like the key-value observing mechanism sometimes forgot notify observers of changes in the values they’ve registered to observe. That’s how bad it is to an interface developer when they resize their views and they get totally messed up and stick to some seemingly arbitrary place in their superview. The work-arounds are messy, laborious and hard to maintain when the project is semi-big. I’m going to try to keep further criticism on this topic and the topic of styling constructive but I imagine there will be emotional rants every once in a while.

I want to keep exploring the Cocoa framework with tutorials. The tutorials I post on this site are as much for my own learning as they are for others, so please take it all with a grain of salt since I will be exploring some unconventional ways of doing things. In fact, maybe I’ll stop using the word ‘tutorial’. I’ll think of something else. The reason that I use this format is that there’s no better way to learn than to have to explain something to someone else. I really appreciate getting people’s feedback on these posts. I work on certain assumptions I’ve formed through my own experience and I’m glad when someone can show me a different way to look at something. I’m self-taught, so I have a very cathy-oriented way of approaching things.

I also plan on writing more design-specific posts. I want to talk about graphic design as well as interaction design and also about the products and concepts, old and new, that inspire me to do the work that I do. Since I spend so much time coding, it’s hard to get into the frame of mind necessary to write about these things, but it is important for me to keep them on the forefront of my thinking as much as possible.

So that’s me and those are my intentions. Thanks for reading and for your comments. I apologize again to Luca, who I snapped at in public today. I’m totally embarrassed about that.

NSView and Autresizing. Yes, Again.

March 20th, 2008

The first post I made on this blog had to do with NSView’s autoresizing behavior being unreliable. As a Cocoa UI developer, this is a real problem that I just have to deal with. But, that’s not the worst thing about autoresizing in NSView. The worst thing about autoresizing in NSView is that setting an autoresizing mask requires that your view controller or window controller explicitly set the size and position of the view within its superview before it can set the autoresizing mask. And whenever the view hierarchy changes, lets say that you need your layout to accommodate a new sibling view at some level of the hierarchy, you have to recalculate everyone’s frame and reset everyone’s mask at that level. Icky, dirty code.

I can see that Cocoa’s getting more sophisticated with how it approaches layout. We can use “layout managers” with CALayers that have this great “constraints” system. From the docs:

Constraint-based layout allows you to describe the position and size of a layer by specifying relationships between a layer and its sibling layers or its superlayer

Relationships. That makes more sense. I want my views to have relationships to each other and I want the views or some layout manager to have the responsibility of maintaining those relationships when the view hierarchy changes, not the controller classes. That’s not what view controllers and window controllers are for.

So I wonder why all this great layout development for layers and not views? Since layers aren’t in the responder chain, they’re not a viable view substitute and I can’t imagine that CALayer will ever become an NSResponder because of its relationship to another framework that we can’t talk about. Maybe NSView is on its way out? There are slight hints that some changes are underway, but even if that’s the case, I can’t imagine that it’ll happen any time soon. NSView does a lot. So, how about an NSViewLayoutManager class in the mean time? Or new options for autoresizing masks? Yay! We Love View!

I filed a bug report requesting a layout manager class for NSView: Bug ID# 5809928.

The Next Device

March 14th, 2008

The iPhone and its SDK inspire our imaginations. But maybe the thing in our imaginations is not this device, but the next device. There seems to be a general mood of frustration among developers stemming from the restrictions Apple is placing on third-party iPhone applications. As John Gruber points out today in his post, One App at a Time, the restrictions aren’t unreasonable considering the hardware. So maybe the angst and frustration we feel is coming from the fact that we have the tools in our hands and we finally have a real sense for this new platform and the possibilities are so clear to us but we have the wrong device. Maybe the thing that we’re all hungry for is not the iPhone, but something else. Something that’s a little less of a phone and not quite a laptop. When you read though the CocoaTouch documentation, do your imaginings end with a phone?

It’s important for us to be patient with Apple and with ourselves right now. This is something totally new and we need to take small steps to make the transition a smooth one. As developers, we have to completely re-conceptualize our idea of how an application should behave and how to engage users without a keyboard or mouse. We’ve been using the same model for software design since windowed GUIs were first introduced in the 80’s. We don’t know any different and we shouldn’t underestimate the challenges we’ll inevitably encounter. I can’t blame Apple for being so protective of their new platform. We have a lot to learn and so do they. Small steps, patience, a little bit of trust and compromise from both sides is going to be key to their and our success in this new endeavor.

But it’s hard to be patient when we’re all feeling so passionate. I look at this beautiful device and I read the documentation of its SDK and it makes me feel restless. I know that this is much more than a phone. But for now, all it is is a phone. It’s the iPhone. It’s not the next device. That will come next and there will be another after that. In the mean time, we have plenty to explore and have fun with. If you think about it, they’re giving us a lot. We’ll find out their next move soon enough.

Welcome, Designers

March 10th, 2008

My head has been reeling all weekend after watching the iPhone SDK presentation. The excitement I felt the first time I saw an iPhone has returned full-force after it was crushed by Steve Jobs during last year’s WWDC keynote address. I still think he owes all of us an apology for trying to pass off Ajax techniques as an SDK like we’re stupid. Anyway, I’m super happy and optimistic about all the new technology we get to play with and like many others, I can’t help but think about the future. There’s one thing in particular that I can’t get off my mind.

There are going to be lots of new Cocoa developers and many of them will come from the field of design, not software development. Some will have never programmed before in their life. This happened with HTML and CSS when the web became popular. It’s going to happen in the world of iPhone development and Mac desktop application development will naturally follow.

This influx of new developers means that the usability of the Cocoa’s APIs are going to be put to the test like never before. Bugs like NSView’s autoresizing not working as advertised or the fact that the methods to customize the drag and drop highlights of an NSTableView are private and not legally accessible to developers are not going to sit well with this new generation of Mac devs, who will demand control over every aspect of their visual design.

It should be possible for the Cocoa engineers to give developers complete control over the visual properties and interactive behaviors of their classes. I don’t mean in that convoluted creating a custom cell way, it should be easy — HTML and CSS easy (in fact, why don’t we use style sheets?). If there are points where this is technically impossible, it’s a design flaw of the framework and should be fixed. If it means writing a new NSTableView, so be it.

Sorry, you’re screwed

I keep thinking of an article I read about the history of CSS and this part in particular:

Meanwhile, writers of Web pages were complaining that they didn’t have enough influence over how their pages looked. One of the first questions from an author new to the Web was how to change fonts and colors of elements. HTML at that time did not provide this functionality - and rightfully so. This excerpt from a message sent to the www-talk mailing list early in 1994, gives a sense of the tensions between authors and implementors:

In fact, it has been a constant source of delight for me over the past year to get to continually tell hordes (literally) of people who want to — strap yourselves in, here it comes — control what their documents look like in ways that would be trivial in TeX, Microsoft Word, and every other common text processing environment: “Sorry, you’re screwed.”

The author of the message was Marc Andreessen, one of the programmers behind NCSA Mosaic. He later became a co-founder of Netscape and by then his views - if they ever were his views - on formatting had changed.

I doubt that any Cocoa engineer has such a flippant attitude towards designers. After all, this is OS X — the best looking operating system on the market. I just hope that they will take these types of issues into more serious consideration when mapping out their priorities. Sure, advertising “New Table Views!” in Cocoa isn’t as sexy a feature as Core Animation, but it’ll make everyone’s life easier in the long run. Imagine this question popping up on the Cocoa-dev list: “How do I customize the background color of a column in an NSTableView”. Now think of the answer…

The Knowledge Navigator

March 10th, 2008

Features from this 1987 video that have been realized:

  • Touch interface (iPhone)
  • Voice commands (Speakable items)
  • Animated views (Core Animation)
  • Video conferencing (iChat)
  • Looking at documents in a video conference (iChat Theater)

Someone needs to implement the bow-tied digital butler.

Creating a Custom Control with NSView

March 7th, 2008
AsimoControl.jpg

This tutorial is about implementing a custom control class. The goal is not to explain how to subclass NSControl or NSCell, but how to think more generally about controls, what they are and how to implement one with an NSView subclass. As with the last tutorial, it will be most useful if you download the example project and follow along in the source code. The comments will provide the implementation details. It’s also fun to give Asimo a pompadour.

The tutorial is based on a similar presentation that I gave at a New York City CocoaHeads meeting a few months ago.

What is a Control?

A control is an interface element that allows users to manipulate data in an application. It’s main responsibilities are to draw itself, handle events, and communicate its values to other parts of the application.

Cocoa’s AppKit framework comes with several controls out of the box:

Picture 43.png
Picture 45.png
Picture 46.png

All of the controls pictured above are decedents of Cocoa’s control class, NSControl. As the documentation states, NSControl works closely with NSCell to provide the basic features of a user interface object. In most cases, you can use an AppKit control with no extra code.

Why Make a Custom Control?

With all of AppKit’s ready-made controls, why would you need to implement your own? Here are two situations where the Cocoa control classes are not a good choice for your interface:

1. None of the AppKit controls support the interaction model you want to implement

Take Photoshop’s curves interface as an example. This interface requires that the user is able to add control points to a bezier curve. They must then be able to select the control points and drag them around to adjust the values of the curve. If they click on the pencil button, the interface must switch to a mode that lets them draw the curve directly into the view.

PSCurves.jpg

You’re not going to find an out of the box control that supports this interface in AppKit and NSControl may not be an appropriate place to start your custom implementation. If you look at its API, it is clear that NSControl was designed to create the AppKit controls. They all have fairly straightforward drawing, event handling and target/action needs. Point-and-click. If you were to use NSControl as a starting point for this interface, you would need to create a few custom cell classes that you would manage in your control’s custom cell. At this point, you’re asking for a headache. This interface is not what NSControl was designed for. You’re going to spend more time fighting with the framework than implementing your ideas.

2. You are drawing with OpenGL instead of Quartz

Picture 53(2).tiff

All of the controls in the iTunes Cover Flow interface are drawn with OpenGL textures. That includes the buttons, scrollbar and slider. These are absolutely not NSControls, which can only draw in a Quartz graphics context. If you want users to interact with your NSOpenGL view, you’re going to have to start from scratch with your controls. Don’t let this scare you away from using OpenGL views for your interface. They’re fast fast fast and if your app is displaying lots and lots of images, especially in a full screen situation with animation, they’re the way to go.

Leopard’s LayerKit (Core Animation Layers) technology advertises mixed Quartz and OpenGL drawing, but I just have a hard time getting behind that idea. More on this thought another time.

Using NSView

The subject of creating controls for an OpenGL view is a little out of the scope of this tutorial. Again, I will come back to the issue of OpenGL views in the not-too-distant future.

Working with NSView will let us touch on the very basics of what we need to make a control. For really specialized, one-off interfaces that you can add to your window’s view hierarchy with no fuss, it makes a lot of sense to start here.

As I mentioned before, there are three parts to a control. Let’s make a to-do list for our class design. Our view must be able to handle:

  1. Drawing
  2. Event Handling
  3. Communication with other parts of your app

We’ll handle number one with NSView and number two with its superclass, NSResponder. For number three, we’ll use Cocoa bindings.

What Are we Controlling?

Before we subclass anything, we need to figure out what our control will control. The example project contains a control for adjusting the values of a twirl distortion CoreImage filter. To start the design, I looked at the documentation for CITwirlDistortion. It lists the three attributes of the filter: center postition, radius and angle. I decided to create a circular design for controling all three attributes at once. This seemed to be a nicer interface than providing three sliders. Of course this design has some usability issues that will be obvious once you play around with it a bit, but it’s fun to experiment.

KDTwirlDistortionControl has this design:

conrolDiagram.jpg

It’s basically a circle. Users can drag on the main gray part of the circle to adjust its radius - this will change the radius attribute of the filter. Dragging on the blue center point will change the position of the circle and the center position attribute of the filter. Finally, dragging the small black circle around its perimeter will adjust the angle attribute of the filter.

We have an interface design. Time for code.

Defining the NSView subclass

Our NSView subclass, KDTwirlDistortionControl, needs to keep track of three rectangles (pictured in the diagram) that it will use for drawing and hit detection. These rectangles will also be used to calculate the adjustment values of the filter. It declares the following ivars for the rectangles in the header file:

// drawing and hit detection
NSRect	mPositionControlRect;
NSRect	mAngleControlRect;
NSRect	mRadiusControlRect;

The control also contains 4 float values that can be bound to. It does this by declaring the following ivars and their getters and setters:

// the values we bind to
float	mPositionX;	// a value between 0 and 1
float	mPositionY;	// a value between 0 and 1
float	mRadius;	// a value between 0 and 1
float	mAngle;		// a value between 0 and 6 radians

The getters and setters will always return normalized values for these ivars, which are calculated based on the positions and sizes of the rectangles in the view’s coordinate system. Look in the code for more details about this part of the implementation.

With the getters and setters in place, our control can communicate changes to these values to other classes with no more code. We can check number three off of our to-do list. Thanks Cocoa.

The last thing our control needs to manage is its state. There are four possible states in our design:

  1. the control is inactive
  2. the position rectangle is active
  3. the radius rectangle is active
  4. the angle rectangle is active

We’ll use this information when we draw to give the user feedback about what they are adjusting. We’ll also use it in our mouse drag handler so that we know which rectangle the user is adjusting. To define the states of the control, create an enum type like this:

typedef enum
{
	kKDTwirlDistortionControlState_Inactive = 0,
	kKDTwirlDistortionControlState_AngleControlActive,
	kKDTwirlDistortionControlState_RadiusControlActive,
	kKDTwirlDistortionControlState_PositionControlActive

}KDTwirlDistortionControlState;

The view subclass declares an ivar that it will use to keep track of its current state:

// state
KDTwirlDistortionControlState		mControlState;

This is all the data we need for our control. Now we will use NSView’s drawing and NSResponder’s event handler methods to implement the control.

Drawing

All we need to do to draw in an NSView subclass is to override the following NSView method:

- (void)drawRect:(NSRect)theRect;

To keep things organized, KDTwirlDistortionControl uses separate drawing methods for each part of the control. It also creates a separate method to lay out the rectangles in the view. It declares them as private methods in a category in the .m file:

@interface KDTwirlDistortionControl (Private)
- (void)drawPositionControlInContext:(CGContextRef)theContext;
- (void)drawAngleControlInContext:(CGContextRef)theContext;
- (void)drawRadiusControlInContext:(CGContextRef)theContext;
- (void)layoutControls;
@end

KDTwirlDistortionControl’s drawRect method looks like this:

- (void)drawRect:(NSRect)theRect
{
 CGContextRef aCGContextRef = [[NSGraphicsContext currentContext] graphicsPort];

 // draw the background
 CGContextSetRGBFillColor(aCGContextRef, 0.8, 0.8, 0.8, 1.0);
 CGRect aCGBackgroundRect = *((CGRect*)&theRect);
 CGContextFillRect(aCGContextRef, aCGBackgroundRect);

 // layout the controls
 [self layoutControls];

 // draw the radius control rect
 [self drawRadiusControlInContext:aCGContextRef];

 // draw the position control rect
 [self drawPositionControlInContext:aCGContextRef];

 // draw the angle control rect
 [self drawAngleControlInContext:aCGContextRef];
}

If you look at the draw methods, you’ll notice that before they draw, they check the control state ivar to determine what color they will use to draw. This gives the user feedback about the state of the control. You might also notice that the control uses Quartz2D drawing commands. Your control could just as well use Cocoa’s NSBezierPath class to draw itself. It’s good to be familiar with both drawing APIs. There might be cases where you will notice the performance difference, so it’s nice to be able to fall back on Quartz for drawing straight into the view instead of using another object.

We can check number 1 off of our to-do list. The drawing is finished. One more.

Event Handling

NSView is a subclass of NSResponder. The mechanism of the view hierarchy ensures that any view you add to it will be placed in the application’s “Responder Chain”. The window will use the view hierarchy to deliver mouse events to the view that the user clicked on. Keyboard events will be delivered through the responder chain. It’s up to the view to implement the NSResponder event handlers that it is interested in.

Most mouse events will be sent automatically to the appropriate view, but there is one step that a view must take to receive keyboard events. The keyboard events go to the “firstResponder” first and then travel through the responder chain. If your view is to receive keyboard events it must accept first responder status. To do this, the view needs to override the NSResponder method:

- (BOOL)acceptsFirstResponder

to return YES. By default it returns NO.

Here’s a list of the most common mouse event handlers that a custom view can impelment:

- (void)mouseDown:(NSEvent*)theEvent;
- (void)mouseDragged:(NSEvent*)theEvent;
- (void)mouseUp:(NSEvent*)theEvent;
- (void)mouseMoved:(NSEvent*)theEvent;
- (void)mouseEntered:(NSEvent*)theEvent;
- (void)mouseExited:(NSEvent*)theEvent;

And common keyboard event handlers:

- (void)keyDown:(NSEvent*)theEvent;
- (void)keyUp:(NSEvent*)theEvent;

NSEvent

All of the event methods are going to pass us an NSEvent object that describes the event. If it’s a mouse event, we can ask the event for the location of the mouse point using the NSEvent method:

- (NSPoint)locationInWindow;

This is going to give us the location of the mouse event in the window (duh). We need to convert this point to a coordinate in our view’s internal coordinate system. We’ll use NSView’s method

- (NSPoint)convertPoint:(NSPoint)thePoint fromView:(NSView*)theView;

If the event is a keyboard event, we can ask the NSEvent object for a string of characters associated with the event with the following methods:

- (NSString *)charactersIgnoringModifiers;
- (NSString *)characters;

Another useful bit of information we can get from NSEvent is whether or not a modifier key is associated with the event. Use the method

- (unsigned int)modifierFlags

to get the current modifier flags, which you can find documented in the list of NSEvent’s constants. Check this against the modifier flag you are looking for. This bit of code is checking for the command key:

if(([theEvent modifierFlags] & NSCommandKeyMask) != 0)
{
 // do something special
}

Check the NSEvent documentation for more information on getting neat things like tablet data.

Ok, Let’s get back to our control.

Mouse Down

When our view receives a mouse down, we want to check to see if the mouse point is inside any of the rectangles. There’s a handy function we can use to check a point struct against a rectangle struct:

BOOL NSPointInRect(NSPoint thePoint, NSRect theRect);

KDTwirlDistortionControl’s mouse down method checks all of the rects against the mouse point. If it determines that a click has occured inside any of its rects, it sets the control state to indicate which rectangle has been hit, tells itself to redraw and returns. Here’s an excerpt:

// down on the position control rect
if(NSPointInRect(aMousePoint,mPositionControlRect))
{
 mControlState = kKDTwirlDistortionControlState_PositionControlActive;
 [self setNeedsDisplay:YES];
 return;
}

If none of the rectangles have been hit, the view centers the position rectangle around the mouse point. This lets user click the background to set the position - hint: this feature comes in handy if you happen to drag it to an unusable position, like I said there are problems in this design ; )

Mouse Dragged

This might be the most important method our class implements. The mouse drag is going to change the values of our active rectangle. It’s also going to call the setter methods of our control’s float values, which will automatically trigger notification of a value change to any class that is bound to the control.

The first thing the mouse dragged handler does is check the control state to determine which rectangle the user is adjusting. It will then perform the calculations it needs to make adjustments to both the rectangle and the associated filter value. It sets the value, tells itself to redraw and returns. Here’s an excerpt:

// dragging the position control rect
if(mControlState == kKDTwirlDistortionControlState_PositionControlActive)
{
 // center the rect around the mouse point
 float aNewXPosition = aMousePoint.x-mPositionControlRect.size.width*.5;
 float aNewYPosition = aMousePoint.y-mPositionControlRect.size.height*.5;
 mPositionControlRect.origin = NSMakePoint(aNewXPosition, aNewYPosition);

 [self setPositionX:aNewXPosition];
 [self setPositionY:aNewYPosition];
 [self setNeedsDisplay:YES];

 return;
}

Mouse Up

The mouse up simply sets the control state to be inactive and tells itself to redraw.

Key Down and Key Up

The key down event handler looks for arrow key presses. When an arrow key is pressed, it adjusts the origin of the position rectangle a few points in the appropriate direction. It also sets the current control state so that the position rectangle is active and redraws. Here’s an excerpt from the method. It uses a switch statement to find the arrow keys:

case NSUpArrowFunctionKey:
   mControlState = kKDTwirlDistortionControlState_PositionControlActive;
   mPositionControlRect.origin.y = mPositionControlRect.origin.y+5;
   [self setPositionY:mPositionControlRect.origin.y];
   [self setNeedsDisplay:YES];
break;

The key up method also checks for arrow keys. If the event is from one of the arrow keys, it resets the control state to inactive and redraws.

Event handling was the last thing on our to-do list. Scratch it off, we’re done. We have a control.

Hi Asimo! Nice Hair-do!

Picture 21.png

The KDTwirlDistortionControl example is very specific to the kind of data it is controlling and it could be used with any Core Image filter that has the same attributes, despite its name.

In a future post, I will explore ways to abstract the design a little more to make the control more useful in more situations. This will be necessary for designing OpenGL controls and could be useful if you’re using CALayers as the basis for a control. I haven’t had a chance to work with CALayers, but I notice that they’re not descendants of NSResponder. Odd for such a view-like class.

Resources

The Example Project

Cocoa Event handling Guide

The Responder Chain

Cocoa drawing guide

Quartz2D Programming Guide

NSView - Working With the View Hierarchy

Cocoa Bindings

More advanced bindings examples: mmalc’s bindings examples, look at graphics bindings