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

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.