Showing posts with label Cocoa. Show all posts
Showing posts with label Cocoa. Show all posts

Wednesday, September 12, 2007

Why Objective-C is cool

I've been asked to do an intro about Cocoa. So I thought about what would I tell people about Cocoa if I had some time. Sure I could throw up a quick tutorial on how to code a Cocoa app showing a bare minimum of how Objective-C works. But there are a million of tutorials like that and it doesn't really do the Cocoa justice. I want to give people an idea of why Cocoa or perhaps more specifically Objective-C is cool. I think anybody who has played computer games to some extent know how the game Doom (1993) from id software revolutionized gaming on the PC platform. What few people know was the the game was actually not developed at the PC platform at all. At the time Doom was developed in 1992, Windows 95 didn't exist yet and software development on PC's looked like this: Not very impressive. Instead it was developed on computers from NextStep, the company founded by Steven Jobs after he was kicked out of Apple. As id developer John Romero says:
Why do I care so much about NeXT computers? Because we at id Software developed the groundbreaking titles DOOM and Quake on the NeXTSTEP 3.3 OS running on a variety of hardware for about 4 years. I still remember the wonderful time I had coding DoomEd and QuakeEd in Objective-C; there was nothing like it before and there still is no environment quite like it even today.
To get an impression of how far ahead of its time Objective-C and what is now known as Cocoa was ahead of its time, consider this:
In fact, with the superpower of NeXTSTEP, one of the earliest incarnations of DoomEd had Carmack in his office, me in my office, DoomEd running on both our computers and both of us editing one map together at the same time. I could see John moving entities around on my screen as I drew new walls. Shared memory spaces and distributed objects. Pure magic.
Consider how long time ago that was, CORBA didn't support C++ for remote method invokation until 1996. At the time id did this it was just in its infant stage. Not to mention this was long long before Java RMI made remote objects populare and mainstream. It isn't even common to do this kind of thing today, and yet this was something that was quite trivial to do in Objective-C and Cocoa back in 1992.

Introducing Objective-C

Every time someone introduce you to Objective-C they will tell you about what a small and simple language it is. How easy it is to learn etc. But that was not my impression when I first tried to learn it. At the time I knew C++. When I saw an example of how to declare a class:
@interface MyClass : NSObject
{
  int         mSomeNumber;
  NSString*   mSomeString;
}

- (int)someNumber;
- (void)setSomeNumber:(int)aNum;
@end
I didn't think it looked easy or simple at all. Especially when I saw some code examples:
- (void)drawRect:(NSRect)frameRect
{
  // Fill whole background with white
  [[NSColor whiteColor] set];
  [NSBezierPath fillRect:frameRect];

  // Construct rows of lines
  NSBezierPath *gridLines = [[NSBezierPath alloc] init];
  for (unsigned row = 0; row <= mNoRows; ++row) {
      [gridLines moveToPoint: rowLeft];        
      [gridLines lineToPoint: rowRight];
      rowLeft.y  += rowHeight;
      rowRight.y += rowHeight;            
  }        

  // Set style to draw line in
  [[NSColor blackColor] set];
  [gridLines setLineCapStyle:NSSquareLineCapStyle];
  
  float pattern[2]  = {2.0f, 5.0f};
  [gridLines setLineDash:pattern count:2 phase:0.0f];

  // Draw specified lines in given style
  [gridLines stroke];
  [gridLines release];    
}
The code below is just to give an idea of what Objective-C syntax is like. What the code does is not important. It has been simplified a bit to understand better. It basically draws several rows with black lines on a white background. When I first saw this kind of code I didn't think it looked easy at all. And I thought whoever said that Objective-C was a much simpler language than C++ must have been smoking something that wasn't good for them. The problem was that I was too caught up in the syntax. The syntax is indeed very unusual, but if one looks beyond that, the structure of the syntax is actually quite simple. Perhaps the best way to understand the syntax is to understand, why it looks so strange.

Background

Unlike C++, Objective-C wasn't really a new language at all originally. There was no Objective-C compiler. Instead Objective-C was just plain old C, with an added preprocessor. As any C/C++ developer worth his/her salt should know all statements starting with # specifies a preprocessor directive in C/C++. E.g. #define and #include. The preprocessor runs before the compiler and replaces the directives with actual C/C++ code. What the makers of Objective-C did was to add another preprocessor, but instead of marking the directives with #, they marked them with @. That way their special preprocessor could find all the new directives easily. While this does make Objective-C look like some alien entity inside C, it does make it trivial to distinguish between pure C code and the add-ons from Objective-C. Unlike C++, where what is C and what is C++ is blurred. Actually C++ isn't a strict superset of C like Objective-C although it usually compiles C code. The reason being among other things that C++ reinterprets a lot of regular C code into new C++ concepts. E.g. a struct isn't just a struct anymore but actually a class in C++.

Syntax inspiration from smalltalk

The second stumble block in order to understand Objective-C syntax is to realize it is derived from Smalltalk, while C/C++ syntax is derived from Algol. Algol based languages separate arguments with comma, while smalltalk separates with name of argument and colon. Below is a code snippet that demonstrates setting the position and dimension of a rectangle object.
// Smalltalk
rectangle setX: 10 y: 10 width: 20 height: 20

// Objective-C
[rectangle setX: 10 y: 10 width: 20 height: 20];
[rectangle setX1: 10 y1: 10 x2: 20 y2: 20];

// C++
rectangle->set(10, 10, 20, 20);
The Smalltalk/Objective-C syntax improves readability of code. When specifying a rectangle some libraries use the start and end coordinates while others use start coordinates and size. With Smalltalk/Objective-C it is made quite clear what is done. While with C++ it is not clear whether the first or the second line of Objective-C code is used. Unlike Smalltalk Objective-C methods are called by enclosing call with []. This was originally to aid the preprocessor in extracting what was regular C code and what was Objective-C specific code.

A small and simple language

What do we exactly mean by saying that Objective-C is a small an simple language. C++ looks simpler syntax wise for the novice. However as said before syntax in deceiving. C++ add a host of new features to the C language: classes, virtual methods, non-virtual methods, constness, templates, friend classes, multiple inheritance, pure virtual functions, operator overloading, function overloading, private, public and protected members, constructors etc. Objective-C on the other hand add very little, it is just classes, methods, categories and protocols. There is only one way to create classes and to inherit form them. You can specify whether inheritance is public or private e.g. There is only one kind of methods. There is no distinction between virtual and non-virtual. They can't be const or not const. The concept of constructors and destructors don't exist. Instead these are just normal methods. As mentioned Objective-C is so simple they didn't even need to create a new compiler. A preprocessor was enough. This can make Objective-C seem overly simple. How can you do much with a language like that? The answer is the Objective-C runtime. The runtime is in fact what makes most of the Objective-C magic happen. Most of Objective-Cs features is provided at runtime and not done at compile time.

Methods and Selectors

Objective-C differs from C++ in that one distinguish between methods and selectors. To call a method on an Objective-C method you send a message. The method is not called directly. Instead Objective-C determines based on the selector which method to call. Conceptually one can think of a message (selector) as simply a string with a list of arguments. The code below e.g. send the message setX:y:width:height: to object rectangle. This will invoke a method on rectangle if it understands the message.
[rectangle setX: 10 y: 10 width: 20 height: 20];
If we think of Objective-C as just a preprocessor as it originally was, all message sending is replaced with a call to a C function:
id objc_msgSend(id theReceiver, SEL theSelector, ...)
So when the preprocessor encounters our rectangle message it is translated into something like this:
objc_msgSend(rectangle, "setX:y:width:height:", 10, 10, 20, 20);
objc_msgSend queries rectangle for its class and then queries the class for methods it contains. Then it finds out which method corresponds to the given selector. The method is nothing but a function pointer of the form:
id (*IMP)(id, SEL, ...)
Of course this is a simplified explanation. In reality every selector is registered. Meaning we don't pass newly created strings to objc_msgSend each time we invoke a method but a pointer to a string. This pointer has to be unique. So we can't pass any string pointer. So if we got å string we can find the unique pointer to this string by using the function:
sel_registerName(const char *str)
Which returns the pointer if it exist or registers the selector as a unique string pointer if it doesn't exist. The benefit of this is that selectors can be looked up quickly and compared quickly by just comparing their pointer addresses rather than comparing each character of the string.

Unique dynamic features of Objective-C

I don't intend to go into every minor of the Objective-C runtime library but the example above should give an idea of how the dynamic features of Objective-C works.

Classes

In C++ classes don't exist passed compile time. Or at least in modern C++ compilers which support runtime type identification classes exist in a watered down sense in that one can query if two classes have a relationship. In Objective-C it is almost opposite. Classes don't exist at compile time but rather are runtime entities. Classes are registered at runtime with function:
void objc_addClass(Class myClass);
Likewise methods and selectors are registered at runtime. So classes can in fact be modified at runtime. Of course users don't call objc_addClass. These methods along with the ones that registers methods are generated by the preprocessor from the class definition provided by the programmer. But it is this fact that classes and methods exist as structures in memory at runtime that allows the programmer at runtime to query classes about their member variables and functions and whether they respond to a selector or not. In fact an Objective-C developer could create an application which could let user specify classes to call and functions to call. User could just type in the name of a class. Then developer could use C function NSClassFromString() to get corresponding class. NSSelectorFromString() could be used to retrieve the selector. With this one could query class further about arguments existing for selector etc. To learn more about Objective-C look at wikipedia

Monday, September 18, 2006

String manipulation: Qt vs Cocoa

Background

I am coding a raytracer program using C++ and Qt. It is program that supports many different algorithms and file formats. One of the algorithms had some bugs that I had problems finding, so I made a OpenGL visualizer of the scene with the hope to be able to visualize different steps in the algorithm to find the error.

Unfortunately the Qt OpenGL implementation proved extremely slow. Instead of looking all over the place to find a solution I decided to create the OpenGL viewer in Cocoa. It seems like Qt4 has several performance problems compared to Qt3. Qt Designer is quite slow when editing properties. Before the last update, it was so slow to type in a text field that I had to type in another window and then cut and paste the text in. Likewise Assistant was so slow I ended up using Safari instead to browse the help documentation.

The scene I read was written for the RenderBitch raytracer. The format is basically like this:

lookat 0 .15 -4.0 ''0 0 0 ''0 1 0
persp 40 1 4.3 .0

material cyan
r_diff .7 1 1
r_refl 0 0 0

# this adds vertices to the scene
vertex 1.25 1 1.3
vertex 1.25 1 -3.3

That is it is a text based file format with some command at each line. So to read the file I had to do a bunch of string manipulation.

I had already done code to read this text in using Qt, so it proved an interesting comparison doing the same task in Cocoa

String classes in Qt and Cocoa

The approach used by Qt and Cocoa is quite different. When looking through Cocoa documentation it reminded me more of how I did string manipulation in script languages like Python and Ruby. Except the methods names were extremely long as is usual in Cocoa (One of the things I dislike the most about Cocoa).

In Qt you deal with strings using the QString, QStringList, QTextStream and QRegExp classes. In Cocoa the equivalents would more or less be: NSString, NSArray and NSScanner. Cocoa does not have an class for regular expressions.

The difference caused by Cocoa being dynamically typed shows itself in the use of NSArray instead of a special string list container. It is general purpose and can hold any kind of objects. Since objects in general can create string representations of itself NSArray also contains methods to joint elements into a string with a separator like QStringList.

One of the creates strength of Qt comes is visible when dealing with primitive types like int and float. By using templates and operator overloading these can be handled a lot easier than Cocoa. In Cocoa you must explicitly box primitive types.

So with Qt I could easily read in data from the text file using QTextStream and have operator overloading automatically take care of type conversion

The example below shows how I can read in e.g. a vertex line in the scene file. Placing the vertex keyword in the keyword variable and the coordinates in x, y and z:

// Reading in a line of text using Qt
QString keyword;
float x, y, z;
QTextStream in(line);
in >> keyword >> x >> y >> z;

In Cocoa I would have to do it explicitly:

// Reading a line of text using Cocoa
NSString* keyword;
float x, y, z;
NSScanner* scanner = [NSScanner scannerWithString:line];
[scanner scanUpToString:@" " intoString:&keyword];
[scanner scanFloat:&x];
[scanner scanFloat:&y];
[scanner scanFloat:&z];

However I didn't actually end up using the operator overloading in Qt. There was some benefits to doing in another way and perhaps it was influenced by my experience dealing with strings in script languages that don't have operator overloading and templates.

So instead I chopped the lines into pieces and converted each string separate like this:

// Split element on line separated by whitespace
QString keyword;
float x, y, z;
QRegExp whitespace("\\s");
QStringList list = line.split(whitespace, QString::SkipEmptyParts);
keyword = line[0];
x = line[1].toFloat();
y = line[2].toFloat();
z = line[3].toFloat();

This looks more complicated but it didn't turn out much different when considering that I read parameters in bulk and they were usually all floats or ints.

In Cocoa I could to similar with this code (although ironically I ended up using the stream approach there):

// Split element on line separated by whitespace
NSString* keyword;
float x, y, z;
NSArray* list = [line componentsSeparatedByString:@" "];
keyword = [list objectAtIndex:0];
x = [[list objectAtIndex:1] floatValue];
y = [[list objectAtIndex:2] floatValue];
z = [[list objectAtIndex:3] floatValue];

It is not entirely equal because it separates on single space and not on any whitespace. This is why I ended up with NSScanner because it has more options on separators.

Unicode

Both Qt and Cocoa uses unicode strings. However in Qt this is not something you have to think much about due to operator overloading. You can write line[0] == '#' and it works, despite line[0] actually representing a unicode character and '#' is not. But overloading of == takes care of the translation trasparently.

With Cocoa it is a different story, because of operator overloading.So to compare a unicode character to a range of other characters one would have to use the NSCharacterSet class.

// line[0] == '#'
NSCharacterSet* hash = [NSCharacterSet characterSetWithCharactersInString:@"#"];
if ([hash characterIsMember: [line characterAtIndex:0]]) {
''''// Do somehting...
}

Of course in this particular instance when we are just checking for a character at the start of the line there is a simpler solution:

// line[0] == '#'
if ([line hasPrefix:@"#"]) {
''''// Do somehting...
}

Experiences with the whole development cycle

It is of course hard to compare the development effort for both environments for this task given that I have much more experience with Qt and did the program in Qt first and then later in Cocoa. So it might even out in the sense that I didn't have to think that much about program design in Cocoa but I had to look up more documentation on how to deal with strings.

With debugging I think Cocoa overall was easier to deal with than Qt. Although I have noticed earlier that the weak typing used in C can cause from problems in Cocoa programs. A number of type mistakes are more easily caught using Qt because it uses C++ which has stronger typing than C.

Some problems with C was also enhanced by how Apple has chosen to let xCode build by default. It uses a Zero linking technique which I thought was great at first because it severely cuts down the compile and link process. However it is quite dangerous because it lets you compile and run programs with calls to functions that don't exist, or with the wrong number of parameters. Now one might argue that this is the case with most dynamic languages in general like script languages. However the combination of late binding and C is a very bad one. There are no proper error handlers when something goes wrong so you remain quite clueless to what went wrong.

However apart from that it is much easier to trace through and debug Objective-C programs in gdb than C++ programs. Almost all Objective-C classes give descriptions of themselves so they can easily be inspected. C functions and Objective-C methods are easier to call because they don't have problems with name mangling like C++ methods and functions.

For instance to debug Qt program I frequently had to make standalone methods that printed out specific objects I had to inspect.

Not an ideal solution because you have to add that code to every Qt program you debug and you have to make code for every class you want to inspect.

Since C++ methods are tricky to call, in debug mode it is hard to change their state through method calls in the debugger.

Conclusion

Although Qt and C++ have some distinct benefits like strong typing, templates and less verbose code, I found it quicker to develop my Cocoa solution because it was much faster to hunt down bugs in the program because debugging was easier.

Monday, August 28, 2006

Graphics: Qt vs Cocoa

The logic of how things work in Cocoa is quite different from most other OO toolkits, especially when it comes to graphics. Here I will give a comparison to how one does some basic graphics operations in Cocoa as opposed to Qt.

I might have chosen to compare Cocoa to Java or .NET frameworks but I am most familiar with Qt. Qt graphics model is quite similar to that use in Java and .NET so the differences explained here should be of interest to Java and C# programers as well.

Introduction

Cocoa and Qt have similar image models for graphics. Both are able to describe images independent of output device (device on which image is displayed) and information about points in drawings (vertices) are retained in the model so that different transformations can be applied to it (e.g. affine transformations.)

Programmin models

However their programming models are different. A programming model can be statefull or stateless and procedure oriented or object oriented. E.g. OpenGL has a statefull and procedure oriented programming model while DirectX has a stateless and object oriented programming model.

In a statefull programming model all drawing operations are affected by the state of the graphics system. E.g. a command to draw a box might be drawBox(x, y, width, height). This would draw a box with current color. The color is then a state in the graphics system. In a stateless system the command would be drawBox(x, y, width, height, color).

The reason why many people find Cocoa confusing at first is that it uses a statefull and object oriented programming model. This is uncommon as Qt, Java and .NET all use a stateless object oriented programming model. In this respect Cocoa has a lot of similarities with OpenGL.

Setting drawing target

In Qt drawing commands change the image or graphics of a QPaintDevice. Typically one of the subclasses like QWidget is used. Below is an example on how one can draw a line of thickness 2 and blue color through three points p1, p2 and p3 on some arbitrary widget returned by getCanvas().

QWidget* w = getCanvas(); ''// Returns our drawing surface
QPainter paint(w);

QPen pen(Qt::blue);
pen.setWidthF(2.0);
paint.setPen(pen);

QPoint p1(x1, y1);
QPoint p2(x2, y2);
QPoint p3(x3, y3);

paint.drawLine(p1, p2);
paint.drawLine(p2, p3);

As one can see the surface to draw on is provided specifically to the QPainter object as well as the pen and color to use. The graphics system is not in any state. The result of the drawing operations is determined exclusively by the objects involved an their attributes.

Below is an example on how to do the same with Cocoa:

NSView* view = getCanvas(); // Returns our drawing surface
NSBezierPath* path = [[NSBezierPath alloc] init];

[[NSColor] blueColor] set];
[path setLineWidth:2.0];

NSPoint p1 = NSMakePoint(x1, y1);
NSPoint p2 = NSMakePoint(x2, y2);
NSPoint p2 = NSMakePoint(x3, y3);

[path moveToPoint:p1];
[path lineToPoint:p2];
[path lineToPoint:p3];

[view lockFocus];
[path stroke];
[view unlockFocus];

As one can see there are some noticeable differences. There is no one object that represents the state of the graphics system like QPainter. NSBezierPath might look like it but it merely keeps track of points on a path and how the lines that connect the points are. No color information is passed to NSBezierPath in the form of a NSColor object nor is the surface on which to draw specified as in the Qt example.

Instead the state of the graphics system itself is changed. [color set] is used to change the color state of the graphics system. Likewise [view lockFocus] is used change the state for current drawing area in the graphics system. Usually when a views method to update its area is called, the state of the drawing area has already been set to that view. So most of the time the user does not have to call lockFocus himself.

Drawing bitmaps

One are that is difficult to understand once one gets started with Cocoa graphics is how to deal with bitmaps. It is confusing precisely because when one is not used statefull programming models for graphics it is not obvious how one draws into a bitmap.

Both Qt and Cocoa have two different image formats. However comparing them is difficult because there is no one to one correspondence in functionality. Qt has QPixmap and QImage. QPixmap is used for drawing images that will go on screen. Because graphics can be created in many different ways on screen individual pixel access is not possible. QImage on the other hand exists off screen in memory an allows individual pixel manipulation. However to put a QImage on screen it has to be converted to a QPixmap

In Cocoa there is a similar situation. NSImage vaguely coresponds to QPixmap. You can not access its individual pixels but you can draw into it and display it on screen. NSBitmapImageRep corresponds roughly to QImage. You can access its pixels individually and set up exactly how pixels are stored, how many color components are used etc. However until recently you could not draw directly into it. Instead you would draw to a NSImage. The reason for this is that NSImage can represent an offscreen window, while NSBitmapImageRep is just a bunch of bytes in memory. Windows area can be drawn on by graphics hardware so they can be represented in any number of ways. They could exist in special graphics memory or on a remote machine. Thus accessing individual pixels on an NSImage makes no sense. However giving drawing commands does because the graphics hardware have drawing commands implemented to do it fast. Doing drawing on NSBitmapImageRep does not make sense because it is not accessible to graphics hardware and drawing can be done by graphics hardware.

Below is an example on how to manipulate the pixels in a QPixmap

Pixmap pixmap = getImage(); // Get some image we want to manipulate
QImage img = pixmap.toImage();

for (int y=0; y < img.height(); ++y) {
''''for (int x=0; x < img.width(); ++x) {
''''''''QRgb pix = img.pixel(x,y);
''''''''doSomethingWithPixel(&pix);
''''''''img.setPixel(x,y,pix);
''''}
}

The code below shows how to do the same thing in Cocoa. That is, to manipulate the pixels in a NSImage. Notice how you must lockFocus on the NSImage to for the pixel grabbing to occur on that particular image.

NSImage* pixmap = getImage(); // Get some image we want to manipulate
NSRect rect = NSMakeRect(NSZeroPoint, [pixmap size]);

[pixmap lockFocus]; // Make pixmap target for drawing commands
NSBitmapImageRep* img = [[NSBitmapImageRep alloc] initWithFocusedViewRect:rect];
[pixmap unlockFocus];

for (int y=0; y < [img pixelsHigh]; ++y) {
''''for (int x=0; x < [img pixelsWide]; ++x) {
''''''''NSColor* pix = [img colorAtX:x y:y];
''''''''doSomethingWithPixel(pix);
''''''''[img setColor:pix atX:x y:y];
''''}
}

[pixmap addRepresentation:img];

Drawing images on screen

To round I need to show how you draw images on screen, or more specifically in a window. A QWidget in Qt's case and a NSView in Cocoa's case. Below we can see how to draw rectangular area within an image given by srcRect inside a rectangular area inside a window (QWidget) given by dstRect

QWidget* w = getCanvas(); ''// Returns our drawing surface
Pixmap pixmap = getImage(); // Return some image we want to draw

QPainter paint(w);

QRectF dstRect(x1, y1, width1, height1) // Area of window to draw into
QRectF srcRect(x1, y1, width2, height2); // Area of image to draw

paint.drawPixmap(dstRect, pixmap, srcRect);

Below we have the corresponding code for Cocoa. Notice that the drawing method is called on the NSImage itself. This does not however mean that drawing is performed inside the image as Qt, Java and C# programmers would easily assume. The target for drawing commands is always the surface/canvas which has focus.

NSView* w = getCanvas(); ''// Returns our drawing surface
NSImage* pixmap = getImage(); // Return some image we want to draw

NSRect dstRect = NSMakeRect(x1, y1, width1, heigth1); // Area of window to draw into
NSRect srcRect = NSMakeRect(x2, y2, width2, heigth2); // Area of image to draw

[w lockFocus];
[pixmap drawInRect:dstRect fromRect:srcRect operation:NSCompositeCopy fraction:1.0];
[w unlockFocus];

Final thoughts

It should be clear that drawing in Cocoa takes some time getting used to for Qt, Java or C# programmers. I have only scratched the surface in this post. From my own experience using both Java and Qt, it is a lot easier to get up to speed on graphics in Qt and Java at first.

However as is typical with everything else with Cocoa it might not be fast to get started but when you dwell into more complicate things, that is when Cocoa start to shine. Likewise with graphics. My own impression from using it (although I am no wizard in Cocoa graphics) is that when it comes to more complicated graphics Cocoa is much more capable than Qt.

It is also my impression that for short examples as given here Qt and Java would usually require less code, but when the graphics is more complicated less code is required in Cocoa.

However I must say that dealing with bitmap graphics seems overly complicated at times in Cocoa. Probably owing a lot to the fact that NEXTStep had totally vector based graphics. The graphics system would output post script drawing commands to the window server and not individual pixels. Basically vector graphics was made easy at the expense of pixel manipulation and raster graphics.