TweetFollow Us on Twitter

The Ins and Outs of Drag and Drop

Volume Number: 18 (2002)
Issue Number: 11
Column Tag: Mac OS X

The Ins and Outs of Drag and Drop

by Andrew C. Stone

The most copied feature of the Mac OS X interface is the ubiquitous drag and drop. When NeXTStep advanced the techniques pioneered at Xerox's Palo Alto Research Center in the late '80's, the way in which people interacted with software was changed forever. The ability to move data and objects seamlessly between windows and applications without any additional steps is the hallmark of a native OS X application. This article will explore some more advanced techniques and some of the issues you might encounter when preparing your interface for drag and drop, as covered in other MacTech articles, such as http://www.stone.com/The_Cocoa_Files/What_a_Drag_.html. We'll cover making an entire window a receptacle for drag and drop, using central control to reduce code, dealing with temporary subviews such as field editors, and auto-swapping Tab views based on the type of data being dropped.

Many of Stone Design's applications fit into the category of "just drag and drop and you're done," such as PStill, GIFfun, PackUpAndGo, DOCtor and SliceAndDice. Taking PStill as an example, the user just drags a file onto the PStill window or application tile in the Dock or the Finder to convert the file to or redistill it as PDF:



Drag files onto Dock or Window

The strategy I like to employ is to make the entire window a valid drag target by subclassing NSWindow or NSPanel, and forwarding the actual methods to the window's delegate:

@interface NSObject(implement_this_in_delegate)
- (void)registerTypesForPanel:(NSPanel *)panel;
@end
@interface SDDragInPanel : NSPanel
{}
@end
@implementation SDDragInPanel
- (void)awakeFromNib
{
   [[self delegate] registerTypesForPanel:self];
}
- (unsigned int) draggingEntered:sender
{
    return [[self delegate] draggingEntered:sender];
}
- (unsigned int) draggingUpdated:sender
{
    return [[self delegate] draggingUpdated:sender];
}
- (BOOL) prepareForDragOperation:sender
{
        return [[self delegate] prepareForDragOperation:sender];
}
- (BOOL) performDragOperation:(id <NSDraggingInfo>)sender
{
    return [[self delegate] performDragOperation:sender];
}
@end

Typical code for delegate would be:

// Dragging stuff:
- (NSArray *)acceptableDragTypes{
    return [NSArray arrayWithObjects:NSFilenamesPboardType,nil];
}
- (void)registerTypesForPanel:(NSPanel *)panel;
{
   [panel registerForDraggedTypes:[self acceptableDragTypes]];
}
- (unsigned int)draggingEnteredOrUpdated:(id <NSDraggingInfo>)sender {
    // we want to ignore drags originating in our own window:
    if ([sender draggingSource] == dragWellView) return NSDragOperationNone;
    else {
        unsigned int sourceMask = [sender draggingSourceOperationMask];
        NSPasteboard *pboard = [sender draggingPasteboard];
        NSString *type = [pboard availableTypeFromArray:[self acceptableDragTypes]];
        if (type) return sourceMask;
        return NSDragOperationNone;
    }
}
- (unsigned int)draggingEntered:(id <NSDraggingInfo>)sender
{
    return [self draggingEnteredOrUpdated:sender];
}
- (unsigned int)draggingUpdated:(id <NSDraggingInfo>)sender
{
    return [self draggingEnteredOrUpdated:sender];
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
    NSPasteboard *pboard = [sender draggingPasteboard];
    NSString *type = [pboard availableTypeFromArray:[self acceptableDragTypes]];
    BOOL loaded = NO;
    id ts = nil;
    if (type) {
        if ([type isEqualToString:NSFilenamesPboardType]) {
            NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
            unsigned i = [files count];
            while (i-- > 0) {
                NSString *f = [files objectAtIndex:i];
                if ([[self acceptableFileTypes] containsObject:[f pathExtension]] && 
                (ts = [SomeObject objectWithContentsOfFile:f])!=nil) {
                    loaded = YES;
          break;
      }
            }
        }
     }
    return loaded;
}
- (BOOL)prepareForDragOperation:sender
{
    return YES;
}
Be sure to register the view for the accepted types. A good place to do this is in 
-(void)awakeFromNib. This method is called on any object instantiated in a NIB (NeXT Interface 
Builder) file that has an implementation of awakeFromNib after all the objects are created and linked 
up, but before the window appears on screen. By implementing a single method acceptableDragTypes that 
returns which types you actually accept, you can avoid out-of-synch code when you add more types to 
open later:

   [panel registerForDraggedTypes:[self acceptableDragTypes]];

So we are done, right? Not quite, because of the way NSTextFields work. When you click or tab into a text field, a shared NSTextView is inserted into the view hierarchy. When the user drags a file over any part of the window that doesn't have an active textfield, the draggingEntered works as planned. But when you pass over the active text field, the NSTextView's drag validation methods come into play. The solution is to subclass NSTextView to also forward the methods to your window's delegate - or just to the window, since the window will forward on to the delegate:

#import <Cocoa/Cocoa.h>
@interface DragTextView : NSTextView
{
}
@end
#import "DragTextView.h"
@implementation DragTextView
// override drag stuff...
- (id)initWithFrame:(NSRect)r
{
    [super initWithFrame:r];
    [self registerForDraggedTypes:[[[self window] delegate] acceptableDragTypes]];
   // this is so TAB and RETURN end editing
   // instead of being inserted into the field:
    [self setFieldEditor:YES];  
    return self;
}
// note we just pass it up to the window:
- (unsigned int) draggingEntered:sender
{
    return [[self window] draggingEntered:sender];
}
... etc, just passing on the method to the window
@end

Now we have our custom text view, but how do we make sure our text view is used in place of the standard text view? We can't set z in Interface Builder, but we can code it. If a window's delegate implements a method called -windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client, the Appkit code will call this method and use the text view it returns if non-nil, otherwise it uses a standard text view set in field editor mode.)

// add textView as  an iVar to the NSWindowController subclass which controls the window
- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client {
    if (sender == [self window]) {
        if (!textView) textView = [[DragTextView alloc]initWithFrame:[myField bounds]];
        return textView;
    }
    return nil;
}

At this point, our interface is ready to accept the correct files and data at any location in the window.

There's one final issue: what if a user can drag a file out of your interface (for example, in PStill, you can drag the distilled PDF file out of the "drag out well") and that file type can also be dragged in to the application (for example, PStill accepts PDF files as input). A user might start a drag out of the application, change her mind, and drop the file back onto the application window. In this case, the application should probably not process the file. Therefore, the window delegate should check the draggingSource to make sure it's not a component of the window itself. This is why we have this line in the draggingEnteredOrUpdated code above:

    if ([sender draggingSource] == dragWellView) return NSDragOperationNone;

Autoswapping Tab Views

The concept of filtering the dragging methods through the window's delegate can be very useful when your window contains an NSTabView with different acceptable types in each view. In Create(R), for example, there is a resources library which can accept art, images, effects, blends, patterns and pages:


Create(R) lets you store many different types of resources - and it will swap to the correct tab view as necessary

Each of these tabviews has an NSScrollView, which contains an NSMatrix. When a user 
drags in a certain type that is not correct for the current view, but is acceptable in another one of 
the tab views, the tab view should automatically switch to the other view so that the drag can drop 
successfully in the right place. We do this by first checking if we can deal with it - and if not, 
we'll ask the window controller (which keeps track of the other views) to check the other resource 
managers. Note we also don't want to accept drags that start from this particular resource's matrix:

- (unsigned int)draggingEntered:(id <NSDraggingInfo>)sender
{
   return [self draggingEnteredOrUpdated:sender checkOthers:YES];
}
- (unsigned int)draggingUpdated:(id <NSDraggingInfo>)sender
{
    return [self draggingEnteredOrUpdated:sender checkOthers:YES];
}
- (unsigned int)draggingEnteredOrUpdated:(id <NSDraggingInfo>)sender 
checkOthers:(BOOL)checkOthers
{
    if ([sender draggingSource] == dragMatrix) return NSDragOperationNone;
    else {
        NSPasteboard *pboard = [sender draggingPasteboard];
        NSString *type = [pboard availableTypeFromArray:[self acceptableDraggedTypes]];
        if (type) {
            unsigned int sourceMask = [sender draggingSourceOperationMask];
            if ([type isEqualToString:NSFilenamesPboardType]) {
                NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType];
                if ([filenames count] == 1) {
                    NSString *filename = [filenames objectAtIndex:0];
                    if ([[[self resourceClass] fileTypes] containsObject:
         [filename pathExtension]])
                     return sourceMask;
                }
            } else return sourceMask;
        }
    }
    if (checkOthers) return [_controller draggingEnteredOrUpdated:sender];
    else return NSDragOperationNone;
}

The _controller's implementation might look something like this:

- (unsigned int)draggingEnteredOrUpdated:(id <NSDraggingInfo>)sender
{
    int i, c = [_resourceSources count];
    unsigned int returnValue;
    for (i = 0; i < c; i++) {
        ResourceSource *res = [_resourceSources objectAtIndex:i];
   if (res == _currentSource) continue;   // already checked!
        if ((returnValue = [res draggingEnteredOrUpdated:sender checkOthers:NO]) 
        != NSDragOperationNone) {
            [self showResourceSourceNamed:[res resourceSourceName]];
       return returnValue;
        }
    }
    return NSDragOperationNone;
}
- (void)showResourceSourceNamed:(NSString *)name
{
    [tabView selectTabViewItemAtIndex:[tabView indexOfTabViewItemWithIdentifier:name]];
}

Because the matrix may not fill the scroll view entirely, we'll also have to subclass the scroll view to forward draggingEntered methods to the matrix. To the end user, the entire scroll view is seen as the target, not just the matrix!

- (unsigned int)draggingEntered:(id <NSDraggingInfo>)sender
{
    return [[self documentView]draggingEntered:sender];
}

... etc. for all the other methods.

Application Tile Drag Support

You only have to perform a few tasks to add support for drag and drop to your Application icon and its Dock tile. First, you'll need to alert the system of the valid file types handled by your application. Then, you'll implement a method in the Application's delegate subclass which calls the actual method to deal with that file type.

First, add information about which files can be opened by your application in Project Builder's application Target Inspector, in the "Document Types" pane:


Be sure to add the file types that your application can open in Project Builder

Second, set your application's delegate. You can do this programmatically with NSApplication's setDelegate:. Or, you can use Interface Builder: (a) instantiate an object of your delegate class in your main NIB file, and (b) connect the File's Owner instance variable "delegate" to this new object.

Third, implement a single method in your delegate's class:

- (BOOL)application:(NSApplication *)sender openFile:(NSString *)path
{
   MyDocument *doc = [[NSDocumentController sharedDocumentController] 
   openDocumentWithContentsOfFile:path display:YES];
   return doc;
}

Now, not only will the dock tile accept drag and drop, but Finder will display your application as a choice for opening that kind of document.

Conclusion

If you want your application to really sing, be sure users can take full advantage of drag and drop everywhere! Not only will it make program interaction easier and more fun, it makes demoing the app more spectacular!


Andrew Stone is founder, janitor and chief computer scientist at Stone Design, www.stone.com.

 

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.