"I have a mind like a steel... uh... thingy." Patrick Logan's weblog.

Search This Blog

Saturday, August 27, 2011

The Relative Coordinate Systems of Cappuccino's CPView

Cappuccino's Objective-J API is based on the Objective-C source for NeXTStep. NextStep was developed at NeXT in the 1980's. At that time it was considered the premier GUI programming API. As it happens the corresponding Cappuccino API should be considered the premier browser-based, "rich", "single-page app", whathaveyou, programming API.

I added a simple example to github which illustrates how easy it is to create multiple subdivided views that resize appropriately as the browser window resizes. Or you could use HTML5/CSS3 and write "puns" to trick the web page layout model into behaving like a window system. I find the straightforward approach significantly more productive.

The best way to solve a complex programming problem is to address simpler problems that add up. The nested views with relative coordinate systems goes back to something like the beginning of computer graphics. Complex layouts become simple combinations of much simpler layouts.

I'm putting most of my exposition in the README.org and jotting about updates on subjot, e.g. this one, or watch the github repository itself.

Tuesday, August 23, 2011

Objective-J Exuberant Ctags Regex

The following does a decent job of indexing Objective-J source using Exuberant Ctags (a ctags/etags replacement with a lot of features). Based on Greg Sexton's regexps for Objective-C.

--langdef=objj
--langmap=objj:.j
--regex-objj=/^[[:space:]]*[-+][[:space:]]*\([[:alpha:]]+[[:space:]]*\*?\)[[:space:]]*([[:alnum:]]+):[[:space:]]*\(/\1/m,method/
--regex-objj=/^[[:space:]]*[-+][[:space:]]*\([[:alpha:]]+[[:space:]]*\*?\)[[:space:]]*([[:alnum:]]+)[[:space:]]*\{/\1/m,method/
--regex-objj=/^[[:space:]]*[-+][[:space:]]*\([[:alpha:]]+[[:space:]]*\*?\)[[:space:]]*([[:alnum:]]+)[[:space:]]*\;/\1/m,method/
--regex-objj=/^[[:space:]]*\@implementation[[:space:]]+(.*)$/\1/c,class/

Sunday, August 21, 2011

Double Dispatch In Objective-J

My previous post describes a controller for separating an application's model from Cappuccino's CPOutlineView. But there's actually one place where the model and view kind of meet up:

- (id)outlineView:(CPOutlineView)outlineView objectValueForTableColumn:(CPTableColumn)tableColumn byItem:(id)item
{
  return (nil == item) ? @"" : [item objectValueForOutlineColumn: tableColumn];
}

I decided to have the controller give a model class access to a column, which is part of the view. Why?

This example has four kinds of columns and three kinds of model classes. Each column wants to display each kind of model element differently. One obvious solution is to use a conditional expression:

if the column is a ... and the model element is a ... then ...

But even simple object-oriented languages like Objective-J have easy mechanisms and patterns for reducing the need to test objects for their class or whether they implement some specific message. Going way back in Smalltalk lore, there's Double Dispatch.

The goal is to reveal to a column the presentation object to use in each of its rows. To do so, the column view, CPTableColumn, is subclassed for each kind of column in the example's outline:

  • SDNavigationColumn
  • SDTopicColumn
  • SDNotesColumn
  • SDDateColumn

Each of these subclasses implements the following methods:

  • objectValueForTopLevel:
  • objectValueForPriority:
  • objectValueForStuff:

Each of the model classes implements objectValueForOutlineColumn: by sending one of the above messages to the given column. For example, SDStuff is implemented as follows:

- (id)objectValueForOutlineColumn:(id)anOutlineColumn
{
  return [anOutlineColumn objectValueForStuff: self]; 
}

This dispatches right back ("double dispatch") to have the column respond with the awareness that it is on a row for detailed stuff. Each column will be interested in different aspects of the stuff. The navigation column is only interested in hierarchy and not details. Here is its implementation, which just returns the empty string to indicate its disinterest:

- (id)objectValueForStuff:(SDStuff)aStuff
{
  return "";
}

On the other hand the date column is interested in a presentation of the given date:

- (id)objectValueForStuff:(SDStuff)aStuff
{
  return [[[aStuff date] description] substringToIndex: 10];
}

Although this kind of brings the model and the view together, the names could be refactored because there is nothing really "column-specific" about this mini-protocol. Also Objective-J has "categories" for grouping methods. The intent of this protocol could be explained by placing the methods in a "presenting" category.

There are certainly more elaborate mechanisms available for keeping views and models separated, yet in-sync. Double Dispatch is just a simple one for reducing the need to test for classes and messages before sending them.

Programming with Cappuccino's CPOutlineView

I wrote in my recent post on Cappuccino about the OK but not great state of documentation. My learning process has been smooth though. I have always had a sense of moving forward with little frustration. But I should attempt to fill some of the documentation gaps myself.

I recently wanted to understand how to program outline views, but ran into some of those gaps. And so my second blog post of the day begins like so.

CPOutlineView is a subclass of CPTableView however from the code using an outline, the requirements are different. Rather than providing a two-dimensional array of data, an application has to provide more of a hierarchy of two-dimensional data. The way I achieve this in my first example is through defining a new class, an SDOutlineController.

(Don't worry about "SD" - that's just the class prefix I am using. Class prefixes are a convention going way back with NeXTStep and before that Smalltalk. Presumably Javascript itself will adopt a conventional if not standard namespace mechanism, and Objective-J can piggyback on that. But I digress...)

This example outline has two groups at the top level: "my stuff" and "other's stuff". Each top-level group has three second-level groups of priorities: "high", "medium", and "low". The third level of the outline are the lists of stuff, themselves. These are arrays of instances of SDStuff.

Here's the class definition for stuff with instance variables for a date, a topic, and notes:

@implementation SDStuff : CPObject
{
  CPDate   date  @accessors(readonly);
  CPString topic @accessors(readonly);
  CPString notes @accessors(readonly);
}

This is Objective-J, a superset of Javascript. I'm assuming that's fairly readable even if you've not programmed in Objective-C and Cocoa. Objective-J can be compiled to Javascript up-front on the server, or in the browser.

The SDOutlineController is the C in MVC for this outline. The V is Cappuccino's CPOutlineView class (and some others). The controller's job is to work with an application's model (the M) in order to present it in the view for user interaction. The model in this case is a little controved, but boils down the essence of a hierarchical model.

I have defined the top-level of the model hierarchy to be a simple class with a label and references to it's children, which group stuff into high, medium, and low priorities:

@implementation SDStuffTopLevel : CPObject
{
  CPString       label                     @accessors(readonly);
  SDStuffParent  highPriorityStuffParent   @accessors(readonly);
  SDStuffParent  mediumPriorityStuffParent @accessors(readonly);
  SDStuffParent  lowPriorityStuffParent    @accessors(readonly);
}

The middle of the hierarchy is similarly defined, but the children are maintained as an array of stuff:

@implementation SDStuffParent : CPObject
{
  CPString label @accessors(readonly);
  CPArray  stuff @accessors(readonly);
}

The model classes above organize data into a fairly simple hierarchical structure. However this structure does not suit all imaginable hierarchies. And so SDOutlineController is designed to avoid having the view depend on any given structure, and vice-versa. The controller has a reference to the top-level for my stuff and the top-level for other's stuff:

@implementation SDOutlineController : CPObject
{
  SDStuffTopLevel myStuffTopLevel;
  SDStuffTopLevel othersStuffTopLevel;
}

The controller has methods expected by CPOutlineView for mediating between the model and the view. The messages are:

  • outlineView:numberOfChildrenOfItem: is kind of obvious.
  • outlineView:isItemExpandable: should be YES (true) if the item has children.
  • outlineView:child:ofItem: should access a hierarchical node's children given an index.
  • outlineView:objectValueForTableColumn:byItem: should provide an object for representing the given model element in the view.

In this example, the top-level of the model always has two elements. The protocol for CPOutlineView uses the convention of passing nil (i.e. the Objective-J equivalent of Javascript's null.) to indicate the root of the model. And so I have not implemented the root as a class.

The following method provides the number of children for any given model element because I have implemented methods for the count message for each model class.

- (int)outlineView:(CPOutlineView)outlineView numberOfChildrenOfItem:(id)item
{
  return (item == nil) ? 2 : [item count];
}

Expandability of a hierarchical element is based on the number of children being greater than zero:

- (BOOL)outlineView:(CPOutlineView)outlineView isItemExpandable:(id)item
{
  return 0 < [self outlineView: outlineView numberOfChildrenOfItem: item];
}

Indexing the child of a hierarchical element is a little more complicated, again just because the root is represented as nil. Otherwise I have implemented objectAtIndex: for the model classes:

- (id)outlineView:(CPOutlineView)outlineView child:(int)index ofItem:(id)item
{
  var result = nil;
  if (nil == item) {
    switch (index) {
    case 0:
      result = myStuffTopLevel;
      break;
    case 1:
      result = othersStuffTopLevel;
      break;
    }
  } else {
    result = [item objectAtIndex: index];
  }
  return result;
}

The remaining method determines the the presentation object for a given model element. The root is never displayed, but to be compelete, this method returns the empty string. Every model class implements objectValueForOutlineColumn: in order to convert itself to its presentation object (which is always a string in this example).

- (id)outlineView:(CPOutlineView)outlineView objectValueForTableColumn:(CPTableColumn)tableColumn byItem:(id)item
{
  return (nil == item) ? @"" : [item objectValueForOutlineColumn: tableColumn];
}

I will use a follow-up blog post to discuss the implementation of objectValueForOutlineColumn:. Perhaps this post provides a little more clarity than other information I've found on the web for programming with CPOutlineView. Let me know if you have a correction or something to add.

On Cappuccino and Avoiding The Modern "Impedance" Mismatch

Wow. My head is just not geared toward writing a blog any longer. But I will model through it.

Cappuccino is a great system for writing rich web applications in the browser, without plugins. There's finally a growing emphasis on Model/View/Controller among modern javascript libraries. Most of them rely on HTML and CSS for the View mechanisms. Which is as you would expect. The problem is the "impedance mismatch" (if you will) between these mechanisms and the desired views for traditional rich applications.

Cappuccino does not suffer such a mismatch, being based on a good portion of the API of NeXTStep, OpenStep, GNUStep, and Apple's Cocoa. And so the Cappuccino API is essentially 25 years old or so.

This choice is not without its pro's and con's. The pro's win for me for applications with these characteristics:

  • At least one display screen greater than 10 inches, i.e. typically used on more than a tablet or phone
  • A good bit more data than would easily fit on a single page, and complex relationships throughout
  • More than a few operations on that data, with a good bit of keyboard input

Because Cappuccino provides an HTML view, this is not a total loss. I've not done much with this yet, but the "con" seems to become a "pro" by allowing for applying HTML and CSS when those mechanisms are the best fit.

Another initial "con" for me the first time I poked at Cappuccino turned "pro" eventually. I'd done a fairly extensive search several months ago on the state of the art of MVC for javascript. Cappuccino was low on my list because I wanted to use javascript per se. Just as Cocoa, et al. are written in Objective-C, Cappuccino is in Objective-J.

I actually like the syntax and class mechanisms, and their similarity to Objective-C and Smalltalk. (Also emacs' Objective-C mode works pretty well as-is with Objective-J.) As the javascript runtimes and tools are adapted to support multiple languages, the tool support for Objective-J should increase.

I came back to Cappuccino after frustration with manipulating HTML and CSS to do my bidding. I don't have any great need for the kind of styling afforded by HTML and CSS. (And with the fallback to an HTML view as per above, even less so.) Most of what I need can be provided satisfactorily using the traditional GUI views going back to Smalltalk-80's MVC.

As it happens, I've done a lot of GUI programming in Smalltalk and several other languages and libraries over the years, so my claim of the pragmatism of this approach also coincides with my experience. Some readers may recall a few years ago that I was in favor of programming web clients using Adobe Flex with ReSTful web services rather than immature javascript/HTML/CSS libraries.

The programmability of views from javascript/HTML/CSS is significantly better now than in 2007. But the majority of libraries are still immature and incomplete. Cappuccino is the best exception to the rule I know of. Fortunately one no longer requires a plugin to achieve Flex's level of productivity.

Cappuccino's class documentation is good, because the API and documentation is already 25 years mature. Tutorials and examples are good, growing, and fortunately supplemented by Cocoa material when the Capp material iteself is lacking.

Blog Archive

About Me

Portland, Oregon, United States
I'm usually writing from my favorite location on the planet, the pacific northwest of the u.s. I write for myself only and unless otherwise specified my posts here should not be taken as representing an official position of my employer. Contact me at my gee mail account, username patrickdlogan.