TweetFollow Us on Twitter

Dec 01 Mac OS X

Volume Number: 17 (2001)
Issue Number: 12
Column Tag: Mac OS X

by Andrew Stone

Cocoamotion

Getting more for less with Cocoa.

Ever since ‘89 I’ve been developing with the precursor to Cocoa, NeXTStep & OpenStep. In each release, new features and new concepts have been added to the Application and related frameworks. making life even easier for the third party developer. The more reusable software components that Apple provides, the less code I have to write and maintain. Imagine being able to remove more and more code from your applications! Today I removed hundreds of lines of code in my Image drawing class by using the new NSImage drawing methods which respect the current transformation matrix.

This article goes over a few ways to eradicate code that you may have accrued by using new objects and new features in the old ones. We’ll look at a simplified Image drawing object, the NSStepper, and the fairly new drag methods in NSOutlineView and NSTableView.

NSImage Gets An Upgrade

Transformations

Before Mac OS X 10.0, NSImage would draw ignoring the current transformation matrix. Now this is fine if you have a simple list of graphics - but if you have nested layers of scaled, rotated, skewed groups, it’s a royal pain in the patooti to micromanage image drawing based on depth of a hierarchy!

For compatibility with older applications, the existing NSImage drawing methods such as compositeToPoint: alway draw with only the origin of the image transformed. The image itself is drawn ignoring scale and rotation transforms with the origin at the lower left. While it has been possible to draw with the current transform by getting one of the image’s representation and calling it’s draw method, two new methods have been added to NSImage that do this for you.

- (void)drawAtPoint:(NSPoint)point fromRect:(NSRect)fromRect operation:(NSCompositingOperation)op 
  fraction:(float)delta;
  
- (void)drawInRect:(NSRect)rect fromRect:(NSRect)fromRect operation:(NSCompositingOperation)op 
  fraction:(float)delta;

If you pass in NSZeroRect for the fromRect: parameter, then the whole image is used. For drawInRect:, the image will be scaled to fit in the destination rectangle as well as transformed with the context’s current transform. Please note that if you use these routines in a flipped view, you will need to ‘undo’ the negative y scale factor and adjust the origin before calling the new methods:

      // make a new transform:
                NSAffineTransform *t = [NSAffineTransform transform];
      
      // by scaling Y negatively, we effectively flip the image:
                [t scaleXBy:1.0 yBy:-1.0];
      
      // but we also have to translate it back by its height:
                [t translateXBy:0.0 yBy:-_bounds.size.height];
      
      // apply the transform:
                [t concat];

Now you can have groups of images that are scaled and skewed, and these transformations will automatically be correctly applied to the image when it is rendered. Total lines of code: 5. Number of lines of code replaced: 250. Improvement of rendering speed: 2x. Reliability and correctness were improved greatly.

Transparency:

Using these new methods, you can add a slider to your interface which controls the transparency of the image, because the new methods take a fractional dissolve, from 0.0 fully transparent to 1.0 fully opaque. Let’s say you store the amount of transparency as a float in _dissolve - then your call to render the image would be:

   // we have translated already to the origin of the image in its current group
   // _dissolve varies from 0 for no dissolve to 1 for fully transparent:
            [image drawInRect:NSMakeRect(0.0,0.0,_bounds.size.width,_bounds.size.height) 
            fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0 - _dissolve];

PDF Optimization:

In 10.1 and earlier, there is an “over-optimization” bug in Apple’s implementation of the NSPDFImageRep whereby it draws from its bitmap cache in certain circumstances which are incorrect. For example, when you print, you want the full resolution PDF, not a standin bitmap image which will produce jaggies. Also, when you zoom in, you want the PDF to render beautifully at that scale. You might want to test if you are printing or saving or at a high level zoom, and render the image directly from the PDF data:

      // if image is a pdf, and we are printing or saving or need the actual data:

            if (needToUseRealPDFData) {
          // grab the image’s best representation, the actual NSPDFImageRep:
                NSPDFImageRep *rep = [_image bestRepresentationForDevice:nil];
         // ask it to draw within our bounds:
                [rep drawInRect:NSMakeRect(0.0,0.0,_bounds.size.width,_bounds.size.height)];
            } else 
                  [image drawInRect:NSMakeRect(0.0,0.0,_bounds.size.width,_bounds.size.height) 
                  fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0 - _dissolve];

The trick to get zoomed PDF to render onscreen at full quality is to multiply the size of the PDF image to the zoom:

   // helper method to return an integral size of an image, based on the zoom:
   
    - (NSSize)sizeForZoom:(float)zoom {
       NSSize s = [_image size];
       if (zoom == 1.0 || zoom == 0.0) return s;
       // images cannot be fractional sizes, so we round down:
       return NSMakeSize(floor(s.width * zoom), floor(s.height * zoom));
    }
    
          // Before drawing the image, we check if we are zoomed:
         // if our image is a PDF, and we’re drawing to screen, get a bigger image:
         
            if (_isPDF &&  [[NSGraphicsContext currentContext] isDrawingToScreen]  &&  zoom != 1.0) {
                NSSize s = [self sizeForZoom:zoom];
                if (_zoomedPDFImage == nil) {
                    _zoomedPDFImage = [_image copyWithZone:[self zone]];
             }
             if ( !NSEqualSizes([_zoomedPDFImage size], s))
                    [_zoomedPDFImage setSize:s];
                image = _zoomedPDFImage;
            } else {
                image = _image;
            }

NSStepper

An NSStepper provides what is known in Carbon as ‘little arrows’. These are common controls for date and time entries, but are also useful for any UI component that has values which can be “tweaked” a little bit. For example, we use them in Create to allow small adjustments to scale:


The ‘little arrows’ are a new addition to Cocoa, but have been around Carbon for awhile.

Like most control subclasses, NSStepper relies on the behavior of its custom NSStepperCell for its functionality. You don’t even need to know to this to use the stepper because the control has cover methods for the standard cell methods. Besides methods familiar from slider controls (setMaxValue:, setMinValue:, setAutorepeat:), the NSStepper allows you to set the granularity of an increment (or a decrement if the lower arrow is clicked) with setIncrement:.

You can also set whether the values loop around (as would be true in the case of rotation stepper) or not with setValueWraps:. In the example of a scale slider, for example, it makes no sense to go from the maximum value to the minimum value with one click!

Using the NSStepper in your interface consists of two parts: initializing the stepper for your requirements and keeping the value of the stepper in synch with data model, since it needs to know the original value in order to increment or decrement the value. You can initialize the stepper when loading the UI components for the first itme or directly in Interface Builder. This example is for a rotational slider: When loading the UI components the first time, you might initialize the values of the stepper, in this example, for a rotational slider. You can also set these values directly in Interface Builder, or programmatically in the File Owner’s class in awakeFromNib, which is called by the nib loading mechanism if this method exists:

- (void)awakeFromNib {
   [stepper setMinValue:0.0];
   [stepper setMaxValue:360.0];
   [stepper setIncrement:1.0];
   [stepper setValueWraps:YES];
   [stepper setAutorepeat:YES];
       // target/action set in IB
}

When inspecting a graphic that can be rotated, you reload the stepper with the current value of the graphic’s rotation:

   double currentRotation = [graphic rotation];
    [circularSlider setDoubleValue: currentRotation];
      [rotationStepper setDoubleValue: currentRotation];
   ...

The stepper handles all mousedowns and it knows whether it needs to increment or decrement the value. Let’s say you have connected the stepper to an action “incrementDecrementAction:”: The stepper has set its internal value to its incremented or decremented value, depending where the user clicked.

- (void)incrementDecrementAction:(id)aStepper {
    [self setSomeValue:[aStepper doubleValue]];  
      // take the value from the stepper
    [self reloadInspectingUI];   
         // update textfields, sliders, etc with new values 
}

The NSStepper is an excellent addition to the Cocoa developer’s toolkit, and both saves some lines of code as well as provide a standard mechanism for tweaking UI values.

Drag & Drop Support in NSTableView and NSOutlineView

The refinement of the Application framework is an ongoing process. For example, a few years ago we had to write our own code for drag and drop row reordering of table views and outlineviews (http://www.stone.com/GIFfun/GIFfunSource/Row_Moving_Protocol.html). Now, that code can be thrown away, and you can use the exposed API to accomplish this:

typedef enum { NSTableViewDropOn, NSTableViewDropAbove } NSTableViewDropOperation;

// In drag and drop, used to specify a dropOperation. For example, given a table with N rows 
(numbered with row 0 at the top visually), a row of N-1 and operation of NSTableViewDropOn would 
specify a drop on the last row. To specify a drop below the last row, one would use a row of N and 
NSTableViewDropAbove for the operation.

- (BOOL)tableView:(NSTableView *)tv writeRows:(NSArray*)rows toPasteboard:(NSPasteboard*)pboard;
    // This method is called after it has been determined that a drag should begin, but before the drag 
    has been started.  To refuse the drag, return NO.  To start a drag, return YES and place the drag 
    data onto the pasteboard (data, owner, etc...).  The drag image and other drag related information 
    will be set up and provided by the table view once this call returns with YES.  The rows array is 
    the list of row numbers that will be participating in the drag.

- (NSDragOperation)tableView:(NSTableView*)tv validateDrop:(id )info 
   proposedRow:(int)row proposedDropOperation:(NSTableViewDropOperation)op;
   
    // This method is used by NSTableView to determine a valid drop target.  Based on the mouse 
    position, the table view will suggest a proposed drop location.  This method must return a value 
    that indicates which dragging operation the data source will perform.  The data source may 
    “re-target” a drop if desired by calling setDropRow:dropOperation: and returning something other 
    than NSDragOperationNone.  One may choose to re-target for various reasons (eg. for better visual 
    feedback when inserting into a sorted position).

- (BOOL)tableView:(NSTableView*)tv acceptDrop:(id )info row:(int)row 
   dropOperation:(NSTableViewDropOperation)op;
    // This method is called when the mouse is released over an outline view that previously decided to 
    allow a drop via the validateDrop method.  The data source should incorporate the data from the 
    dragging pasteboard at this time.

Our free application, GIFfun, allows users to reorder the individual images that make up the final animated GIF. Here’ s a sample implementation of the Drag and Drop support in an NSTableView:

static int _moveRow = 0;

- (BOOL)tableView:(NSTableView *)tv writeRows:(NSArray*)rows toPasteboard:(NSPasteboard*)pboard 
{
    int count = [gifFileArray count];
    int rowCount = [rows count];
    if (count < 2) return NO; 

    [pboard declareTypes:[NSArray arrayWithObject:GifInfoPasteBoard] owner:self];
    [pboard setPropertyList:rows forType:GifInfoPasteBoard];
    _moveRow = [[rows objectAtIndex:0]intValue];
    return YES;
}

- (unsigned int)tableView:(NSTableView*)tv validateDrop:(id )info 
   proposedRow:(int)row proposedDropOperation:(NSTableViewDropOperation)op 
{
    if (row != _moveRow) {
        if (op==NSTableViewDropAbove) {
            return NSDragOperationAll;
        }
        return NSDragOperationNone;
    }
    return NSDragOperationNone;
}

- (BOOL)tableView:(NSTableView*)tv acceptDrop:(id )info row:(int)row 
   dropOperation:(NSTableViewDropOperation)op 
{
   BOOL result = [self tableView:tableView didDepositRow:_moveRow at:(int)row];
   [tableView reloadData];
   return result;
}

// here we actually do the management of the data model:

-  (BOOL)tableView:(NSTableView *)tv didDepositRow:(int)rowToMove at:(int)newPosition
{
   if (rowToMove != -1 && newPosition != -1) {
      id object = [gifFileArray objectAtIndex:rowToMove];
      if (newPosition < [gifFileArray count] - 1) {
         [gifFileArray removeObjectAtIndex:rowToMove];
         [gifFileArray insertObject:object atIndex:newPosition];
      } else {
         [gifFileArray removeObjectAtIndex:rowToMove];
         [gifFileArray addObject:object];
      }
      return YES;   // ie reload
   }
   return NO;
}

These few lines listed replace the 650 lines of code from SDTableView.h, SDTableView.m and SDMovingRowsProtocol.h. The complete source code to GIFfun is available at http://www.stone.com/GIFfun/.

Adding Features By Doing Nothing

And, if my Zen slacker coding model isn’t convincing enough, consider how you can add new features by doing nothing!

If you are using the Model-View-Controller pattern and taking advantage of the NSDocument architecture, then the introduction of Mac OS X 10.1 brought you new features, without you doing anything. Because your application links at runtime with the current version of the Application and Foundation frameworks, new features available in the kits become available to your users.

10.1 adds Hidden file extensions (which is way more Mac-like than the UNIX file extensions), ability to track documents, folders, and volumes which are renamed, and ability to save documents in a way which preserves aliases to the documents and additional document info such as maintaining file permissions, creation date, and icon settings.

Some of these features do require that you recompile your application, because the Apple engineers wanted to provide full backwards binary compatibility in programs that were linked against the Mac OS 10.0 version of the Cocoa framework.

Conclusion

Software is a process not a product, and therefore it is never finished! The frameworks that Cocoa developers rely on are continually being refined and improved, so it’s very important to carefully read the Release Notes found in /Developer/Documentation/ReleaseNotes, especially AppKit.html and Foundation.html. Always check for new functionality which can replace your home-rolled versions, thus making your application more compact and reducing the code base that you need to support.


Andrew Stone andrew@stone.com is the chief executive haquer at Stone Design Corp http://www.stone.com and divides his time between raising children, llamas & cane and writing applications for Mac OS X.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.