TweetFollow Us on Twitter

What a Drag Volume Number: 16 (2000)
Issue Number: 12
Column Tag: Mac OS X

What a Drag!

By Andrew C. Stone

Creating drag wells in Cocoa

The richness of the user interface in Macintosh OS X is due, in part, to the abundance of elements that allow dragging and dropping of data within and between applications. For example, Cocoa uses drag and drop for applying color swatches to text selections and objects. Stone Design's flagship application, Create[TM], makes heavy use of the drag and drop metaphor. A library of resources allows users to drag in components, pages, effects, blends, images, and patterns. The user can quickly save a selection of graphics to one of many image formats with Create's "Image Well". This article will cover the basics of creating a custom control which allows a user to drag in a file, and then allows the user to drag out the file.


Create's image well lets you drag out data in various image formats.

First, a bit of article administrivia. Mac OS X has been a fast moving target with the various developer releases, Public Beta, and soon OS X GM (for Golden Master which always reminds me of that Eddy Murphy movie about G)! Because of the changes introduced with each release and the several month lag time between penning articles and when MacTech hits the stands, there are times when what I've written doesn't jive with the current reality. To address this, I've added a section to the Stone Design website for MacTech article updates and errata. So if you get confused, check out www.stone.com/dev/MacTech_Errata/ to see if there are updates, and if not, email me so I can post fixes.

It's actually quite simple to create new types of user interface controls using Cocoa because of the well designed hierarchy of classes that comprise the Application framework. Your first job is to find an existing class that your control can inherit from, which will reduce the amount of code that you have to write. I keep /Developer/Documentation/Cocoa/cocoa.html open so I can quickly navigate to the AppKit or Foundation API's. But an even easier way to look at the object hierarchy is to use InterfaceBuilder. First launch ProjectBuilder and create a new Cocoa Application project named ImageWellTester. Click on the "Resources" triangle in the Files and Groups outline view, and double-click the MainMenu.nib. This will launch InterfaceBuilder.

Click on the "Classes" tab of the document window, and then explore the NSObject outline view:


Interface Builder lets you explore the hierarchy of objects offered by Cocoa.

Our drag well is definitely a subclass of NSView, but we can gain further functionality by subclassing NSControl, which gives us the target/action support. Select NSControl in the Classes pane. If you hold down the CONTROL key while clicking on NSControl, a context-sensitive menu appears. Do this and select "Subclass". A new class which inherits from NSControl is created and named, by default, MyControl. Rename the class to DragWell.

Why write code if you can have it written for you? You can use InterfaceBuilder to produce stub files where all you have to do is fill in the functionality in the stubbed out methods. Click on the "outlet" icon to add instance variables to the class, and the "+" icon to add actions to the class. For now, we don't have any to add. Be sure DragWell is selected, and choose select "Create Files..." from the Classes menu (or again using the context menu via CONTROL key). They will be named DragWell.m and DragWell.h - leave the "Insert into Project Builder" selected and click OK.

Drag out a "Custom View" from the IB palette window, second tab, onto to the main window. Choose Tools->Inspector->Custom Class popup button, and click on "DragWell". The custom view should now say "DragWell". Save the file.

Go back to ProjectBuilder, select the newly added DragWell.h and DragWell.m and you'll see the stub:

#import <Cocoa/Cocoa.h>

@interface DragWell : NSControl
{
}

@end
...
#import "DragWell.h"

@implementation DragWell

@end

Every custom view must define its own drawing method, drawRect:, where the actual drawing of the view takes place. We'll want a simple, depressed bezeled look, with an icon to drag in the center. And our control will adhere to two protocols - NSDraggingDestination and NSDraggingSource, to allow both dragging out of info and accepting dragged in info. A complete list of the methods required by the protocols are found in:

/System/Library/Frameworks/AppKit.framework/Headers/NSDragging.h 

Here's the 'well' commented code for the DragWell - type it in (or download it from www.stone.com/dev/MacTech/Jan-2001/). You can copy and paste it as a template for use in other objects, modifying where needed to copy other data types to the drag pasteboard as needed.

+++++++++++ DragWell.h ++++++++++++++++

#import <Cocoa/Cocoa.h>

@interface DragWell : NSControl
{
    NSImage *image;      // the image displayed and dragged by the user
    NSString *file;      // the file path that the user will drag out
    unsigned int last;   // for optimizing the draggingUpdated: method
}

// if you want to programmatically set a file in the well:
- (void)setFile:(NSString *)newFile;

@end

+++++++++++ DragWell.m ++++++++++++++++

#import "DragWell.h"

/* Example source by Andrew Stone andrew@stone.com www.stone.com for MacTech */

@implementation DragWell

// when our DragWell is reconstituted from the nib file, awakeFromNib gets called

- (void) awakeFromNib
{
     // this is where you register for various types of drag pasteboards:
     [self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
}

// Never add an ivar which allocates memory without releasing it in dealloc:
// Don't Litter!

- (void)dealloc {
    [file release];
    [image release];
    [super dealloc];
}

// Every custom view must implement drawRect:
// We'll draw our depressed bezeled rect
// and if there is a file, we'll draw an image for dragging out

- (void)drawRect:(NSRect)rects
{
    // one simple call draws the depressed bezel:
    NSDrawGrayBezel([self bounds] , [self bounds]);

    // if you like the pinstripes, then include these two lines:
    [[NSColor windowBackgroundColor] set];
    NSRectFill(NSInsetRect([self bounds],3.0,3.0));

    // find the center of the view and draw the image over:
    if (image != nil) {
        NSPoint p;
        NSSize sz = [image size];
        p.x = ([self bounds].size.width - sz.width)/2.;
        p.y = ([self bounds].size.height - sz.height)/2.;
        [image compositeToPoint:p operation:NSCompositeSourceOver];
    }
}

// When we set the file, we also set the image which we get from the NSWorkspace:

- (void)setFile:(NSString *)newFile {

    // it's good practice to not do any work if nothing would change:
    if (![newFile isEqualToString:file]) {
    
        // live clean and let your works be seen:
        [file release];
        [image release];
        
        // copy the newFile into our instance variable file:
        file = [newFile copyWithZone:[self zone]];
        
        // check if the file is nil or empty string:
        if (!file || [file isEqualToString:@""]) {
            image = nil;
        } else {
            // we have a file, now let's find the image for that file:
            image = [[[NSWorkspace sharedWorkspace] iconForFile:file]retain];
        }
        
        // we'll need to redraw next event 
        // this is the approved Cocoa way of setting ourselves "dirty"
        [self setNeedsDisplayInRect:[self bounds]];
    }
}

// here we copy the filename to the pasteboard
// I like to factor this out because it may vary from object to object:

- (BOOL)copyDataTo:pboard
{
    if (file != nil && ![file isEqualToString:@""]) {
        [pboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:self];
        [pboard setPropertyList:[NSArray arrayWithObject:file] forType:NSFilenamesPboardType];
        return YES;
    } else return NO;
}

// DRAGGING SOURCE PROTOCOL METHODS
// To add drag away functionality to a control, implement these:

// draggingSourceOperationMaskForLocal lets you control the behavior of what should
// happen with the data on the pasteboard: copy, link or any
// the isLocal flag tells you whether the object querying is from within your app
// or from another application running on the system

- (unsigned int)draggingSourceOperationMaskForLocal:(BOOL)isLocal
{
        if (isLocal) return NSDragOperationCopy;
        return NSDragOperationCopy|NSDragOperationGeneric|NSDragOperationLink;
}

// The simple dragImage:at:offset:event:pasteboard:source:slideback: method
// is all we do to initiate and run the actual drag sequence
// But we only do this if we have an image and we successfully write our data
// to the pasteboard in copyDataTo: method

- (void)mouseDown:(NSEvent *)e
{
        NSPoint location;
        NSSize size;
        NSPasteboard *pb = [NSPasteboard pasteboardWithName:(NSString *) NSDragPboard];

        if (image && [self copyDataTo:pb]) {
                size = [image size];
    location.x = ([self bounds].size.width - size.width)/2;
    location.y = ([self bounds].size.height - size.height)/2;

                [self dragImage:image at:location offset:NSZeroSize event:(NSEvent *)e
pasteboard:pb source:self slideBack:YES];
        }
}

// DRAGGING DESTINATION PROTOCOL METHODS
// To add drag acceptance functionality to a control, implement these methods:

// this is called when the drag enters our view
// by returning NSDragOperationCopy
- (unsigned int) draggingEntered:sender
{
    NSPasteboard   *pboard;

     last      = NSDragOperationNone;
     pboard    = [sender draggingPasteboard];

// we don't acept drags if we are the provider!!
     if ([sender draggingSource] == self) return NSDragOperationNone;

     if ([[pboard types] containsObject:NSFilenamesPboardType]) {
         if (image == nil) {
            image = [[[NSWorkspace sharedWorkspace] iconForFile:[[pboard
propertyListForType:NSFilenamesPboardType]objectAtIndex:0]]retain];   
             [self setNeedsDisplayInRect:[self bounds]];
          }
   // we'll copy or link depending on the intent of the dragging source:
   last = [sender draggingSourceOperationMask]; 
     }
     return last;
}

// instead of constantly rechecking the pasteboard as the mouse moves inside the view
// we'll simply return the cached value that we set in 'last' in draggingEntered:

- (unsigned int) draggingUpdated:sender
{
     return last;
}

// Because we're providing feedback by setting the file right when the user enters
// we'll need to undo that work if the user does not let go of the drag inside and exits instead:

- (void) draggingExited:sender
{
    // the user has exited -> clean up:     
    if ([sender draggingSource] != self)  {
        if (file == nil) {
            // then unset the file image we set in mouseEntered as feedback...
            [image release];
            image = nil;
            [self setNeedsDisplayInRect:[self bounds]];
        } 
        last = NSDragOperationNone;
    }
}

// any dragging clean up might be done here
// don't forget to return YES!

- (BOOL) prepareForDragOperation:sender
{
     return YES;
}

// Actually do the work in this method if it's not too time consuming
// Otherwise, you may consider returning YES, and doing the work
// in concludeDragOperation to prevent the drag from sliding back
// because it "timed out"

- (BOOL) performDragOperation:(id <NSDraggingInfo>)sender
{
    NSPasteboard   *pboard;
    pboard    = [sender draggingPasteboard];
    [self setFile:[[pboard propertyListForType:NSFilenamesPboardType]objectAtIndex:0]];
    return YES;
}

- (void)concludeDragOperation:(id <NSDraggingInfo>)sender
{
    // we already did the work in draggingEntered
    // You might notify some other object that the file is here
}

// this is good if you want to be able to drag out data even if the window is not
// front most, the first click will do more than just bring the window to front -
// It will also allow the drag to begin on that first mouse down

- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent {
    return YES;
}

@end

Conclusion

Adding drag and drop support to controls and views is very easy in Cocoa. Because ease of use and intuitive behavior is the keystone of Mac OS X, be sure to make your applications conform to this model.


Andrew Stone <andrew@stone.com> washes windows at Stone Design Corp <http://www.stone.com/> and divides his time between writing applications for Mac OS X and raising farm animals, including children.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom 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.