TweetFollow Us on Twitter

MACINTOSH C CARBON
MACINTOSH C CARBON: A Hobbyist's Guide To Programming the Macintosh in C
Version 1.0
2001 K. J. Bricknell
Go to Contents Go to Program Listing

CHAPTER 23

DRAG AND DROP

Overview

The Drag Manager

Using the Drag Manager, you can provide your application with the capability to drag objects from your application's windows, to your application's windows, and within your application's windows.

The Three Phases of a Drag

All drag and drop operations comprise the following three distinct phases:

  • Starting the drag.

  • Tracking the drag.

  • Finishing the drag.

Different applications may be involved in each of these three phases. For example, when the user drags an item from one application to another, the source application starts the drag, other applications through whose windows the user drags the item may track the drag, and the application owning the target window finishes the drag by accepting the drop (see Fig 1).

Of course, when the drag and drop is wholly within one of an application's document windows, that single application starts the drag, tracks it through the window, and accepts the drop.

Starting the Drag

A drag is initiated when the user clicks on a selected object, keeps the mouse button down, and begins to move the mouse (see the left hand window at Fig 1). Using the function WaitMouseMoved, you can determine if the mouse has moved far enough to initiate a drag. If WaitMouseMoved returns true, your application should call NewDrag to create a new drag reference. A drag reference is an opaque data type that you use to refer to a specific drag process.

Having created a drag reference, and for each item in the drag, you must then add at least one drag item flavour to that reference using the function AddDragItemFlavor. Drag item flavours represent the various data formats in which each individual item may be produced. The concept is similar to that applying to Scrap flavours as described at Chapter 20.

With the drag item flavour (or flavours) added, your application can then initiate tracking by calling the function TrackDrag.

Tracking the Drag - Drag Tracking Handlers

The Drag Manager tracks the drag through each window the cursor moves over as the user drags the selection across the screen. During this process, the user is presented with the following feedback:

  • Destination highlighting will occur when the cursor has left the source location. (See the middle window at Fig 1, whose owner application supports drag and drop and can accept the drop).

  • If a container under the cursor (such as a folder in the Finder) can accept the drop, that container will be highlighted.

As the cursor moves through, for example, the middle window at Fig 1, the Drag Manager calls a function, called a drag tracking handler, defined by that window's owner application. Drag tracking handlers inspect the description of the item, or items, being dragged and highlight the window if this inspection reveals that the window can accept the drop. The application's drag tracking handler uses the functions ShowDragHilite and HideDragHilite to create and remove the highlighting. (The acceptable drop region, and thus the region highlighted, does not necessarily have to be the whole of the window's content region.)

Finishing the Drag - Drag Receive Handlers

When the user releases the mouse button in, for example, the right hand window at Fig 1, the Drag Manager calls a function, called a drag receive handler, defined by that window's owner application. Drag receive handlers accept the drop and insert the selection at its final destination.

More on Drag Items, Drag Item Flavours, and Handlers

Drag Items and Item Reference Numbers

A drag item is a single distinct object, which could be, for example, a selection from a painting in a painting program, a selection of objects in a drawing program, or a continuous range of text editing program.. A discontinuous selection of text (resulting from using the Command key in some programs) would result in multiple drag items.

A new drag item is created if the item reference number passed in the theItemRef parameter of a call to AddDragItemFlavor is different from any other item reference number.

In many cases it is easiest to use index numbers as item reference numbers (e.g., 1, 2, 3...). Item reference numbers are only used as unique "key" numbers for each item. Item reference numbers do not need to be given in order, nor must they be sequential. Depending on your application, it might be easier to use your own internal memory addresses as item reference numbers (as long as each item being dragged has a unique item reference number).

Drag Item Flavours

Any item that can be dragged can generally be represented using several different flavours (that is, data formats). At the start of a drag, your application must inform the Drag Manager, using the function AddDragItemFlavor, of the flavours that you can provide to the receiver of the drag. For example, if the drag item is a selection of text, you might elect to provide the data in both the standard 'TEXT' format and in the Rich Text Format (RTF). Alternatively, instead of supplying the data in RTF, you might supplement the 'TEXT' data with 'styl' data. You might also provide the data in your application's own internal data format to cater for a drag and drop to one of your application's documents, including the source document.

Your application adds additional flavours to an item by passing the same item reference number in the AddDragItemFlavor call as was used in the AddDragItemFlavor call which created the item and added the first flavour.

Different destinations may prefer different data formats, and there is no certainty as to whether a drag will contain the preferred, or an acceptable, flavour. Thus, as previously stated, the destination application needs to inspect the description of the items being dragged to determine whether an acceptable flavour is available and only highlight the relevant window if it can accept a drop. The function GetFlavorFlags is used to determine whether the drag contains a specific flavour type.

Flavour Flags

The following flavour flags, which are used by the Drag Manager and its clients to provide additional information about a specific drag item flavour, may be passed in the theFlags parameter of the function AddDragItemFlavor and retrieved by the function GetFlavorFlags:

Flag

Description

flavorSenderOnly

Set by the sender if the flavour should only be available to the sender.

flavorSenderTranslated

Set if the flavour data is translated by the sender. Useful if the receiver needs to ascertain whether the sender is performing its own translation to generate this data type.

flavorNotSaved

Set by the sender if the flavour data should not be stored by the receiver. Useful for marking flavour data that will become stale after the drag is completed.

flavorSystemTranslated

Set if the flavour data is translated by the Translation Manager. If this flavour is requested, the Drag Manager will acquire the required data type from the sender and then use the Translation Manager to provide the data requested by the receiver.

Note that the Finder does not save flavour types marked with the flavorSenderTranslated, flavorNotSaved, and flavorSystemTranslated flags into clippings files.

Drag Handlers

Drag tracking handlers and drag receive handlers are callback functions that your application registers with the Drag Manager using the functions InstallTrackingHandler and InstallReceiveHandler. The window reference of the window on which the handlers are to be installed is passed in the theWindow parameter of the two handler installer functions. You can install more than one tracking handler and more than one receive handler on the same window, in which case the Drag Manager calls each of the handlers in the order they were installed.

If you pass NULL in the theWindow parameter of the handler installer functions, the Drag Manager will register the handler in a special area that is used when the drag occurs in any window of your application. Handlers installed in this special area are called default handlers.

Drag Tracking Handlers

As the user moves the mouse through your application's windows during the drag, the Drag Manager sends status messages to your tracking handler. These messages are as follows:

Message

Description

Enter handler

Received when the focus of the drag enters a window handled by your tracking handler from a window not handled by your tracking handler.

Enter window

Received when the focus of a drag enters any window handled by your tracking handler.

In window

Received as the user drags within a window handled by your tracking handler.

Leave window

Received when the focus of a drag leaves a window that is handled by your tracking handler.

Leave handler

Received when the focus of a drag enters a window that is not handled by your tracking handler.

Fig 2 illustrates the receipt of tracking messages involving multiple applications and windows.

Drag Receive Handlers

When the user drops an item, or a collection of items, in one of your application's windows, the Drag Manager calls any receive handlers installed on the destination window. Your receive handler can then request the drag item flavour, or flavours, that you wish to accept and insert the data at its final destination.

When the drop occurs within the window in which the drag originated, and the user did not press the option key either before the mouse button went down or before it was released, receive handlers must delete the original selection before inserting the dropped data. If the option button was not pressed, receive handlers must not delete the selection.

Creating the Drag Region and Setting the Drag Image

Creating the Drag Region

Recall that your application initiates tracking by calling the function TrackDrag. This function takes a region, specifically, the drag region, in its theRgn parameter. This is the region, drawn by the Drag Manager in the dithered gray pattern (Mac OS 8/9) or gray colour (Mac OS X), that moves with the mouse during the drag (see Fig 1).

As an example, to create a drag region when a single item is selected, your application should:

  • Copy the drag item's region to a temporary region and inset the temporary region by 1 pixel.

  • Use DiffRgn to subtract the temporary region from a copy of the item's region.

The resulting copy of the item's region has the same outline as the item's original region but is only one pixel thick (see Fig 3).

Setting the Drag Image - Translucent Drags

The drag region may also be visually represented to the user by a translucent image of the original selection (see Fig 4).

To support translucent dragging of a text selection on Mac OS 8/9, you should:

  • Create an offscreen graphics world the size of the bounding rectangle of the highlight region. The offscreen graphics world should be eight bits deep.

  • Copy the area of the window enclosed by the highlight region's bounding rectangle to the offscreen graphics world.

  • Create a region for a mask which is exactly the same shape as the highlight region. (Note that, if you do not supply a mask, the entire rectangular area of the offscreen pixel map, including white space, will be dragged.)

  • Call SetDragImage to associate the image with the drag reference, passing in the handle to the offscreen pixel map, the handle to the mask region, and a constant specifying the required level of translucency. SetDragImage installs a custom drawing function (see below) to perform the translucent drawing.

The level of translucency may be specified using one of the following drag image flags:

Constant

Value

Description

kDragStandardTranslucency 0L

65% image translucency. This is the recommended level.

kDragDarkTranslucency 1L

50% image translucency.

kDragDarkerTranslucency 2L

25% image translucency.

kDragOpaqueTranslucency 3L

0% image translucency (opaque).

Drag Functions - Overriding Drag Manager Default Behaviour

If you wish to override the Drag Manager's default behaviour, you can supply it with several different kinds of drag function. Only the sender can specify drag functions.

Drawing Function

When a drawing function is installed, the Drag Manager sends that function a sequence of messages that allow the application to assume responsibility for drawing the drag region (or similar feedback) on the screen. If translucent dragging is used, you must not install a custom drawing function.

Send Data Function

If you install a send data function, the Drag Manager calls that function when the receiver application requests a drag item flavour that the Drag Manager does not currently have the data cached for.

Ordinarily, the Drag Manager caches the flavour data for all flavours that were added to the drag with the AddDragItemFlavor function. If a receiver calls GetFlavorData to get a flavour's data, the Drag Manager simply returns the cached data to the receiver.

However, if your application passes NULL as the pointer to the flavour data in the AddDragItemFlavor call, the Drag Manager does not cache the data. In effect, your application has made a "promise" to later supply the data in the event that a receiver requests it. Thus, if a receiver calls GetFlavorData for that particular flavour, the Drag Manager will call your send data function to get the data from the sender. Your send data function should then create that flavour's data and call SetDragItemFlavorData to send the data to the Drag Manager.

This mechanism of "promising" data that may, in the event, not be called for by a receiver is useful where the sender must perform expensive computations to produce the data or if the resulting data requires a large amount of memory to store.

Drag Input Function

If you install a drag input function, the Drag Manager calls that function when sampling the mouse position and keyboard state to allow the application to override the current state of the input devices. The Drag Manager passes the current mouse location, mouse button state, and keyboard modifier status to your drag input function, which can then modify those parameters.

Main Drag Manager Constants, Data Types, and Functions

Constants

Flavour Flags

flavorSenderOnly               = (1 << 0)
flavorSenderTranslated         = (1 << 1)
flavorNotSaved                 = (1 << 2)
flavorSystemTranslated         = (1 << 8)

Drag Attributes

kDragHasLeftSenderWindow       = (1L << 0)
kDragInsideSenderApplication   = (1L)
kDragInsideSenderWindow        = (1L << 2)

Drag Tracking Handler Messages

kDragTrackingEnterHandler      = 1
kDragTrackingEnterWindow       = 2
kDragTrackingInWindow          = 3
kDragTrackingLeaveWindow       = 4
kDragTrackingLeaveHandler      = 5

Drag Image Flags

kDragStandardTranslucency      = 0L
kDragDarkTranslucency          = 1L
kDragDarkerTranslucency        = 2L
kDragOpaqueTranslucency        = 3L

Drag Drawing Handler Messages

kDragRegionBegin               = 1
kDragRegionDraw                = 2
kDragRegionHide                = 3
kDragRegionIdle                = 4
kDragRegionEnd                 = 5

Data Types

typedef struct OpaqueDragRef *DragRef;
typedef UInt32  DragItemRef;
typedef OSType  FlavorType;
typedef UInt32  DragAttributes;
typedef UInt32  FlavorFlags;
typedef SInt16  DragTrackingMessage;
typedef SInt16  DragRegionMessage;

Functions

Installing and Removing Drag Handlers

OSErr   InstallTrackingHandler(DragTrackingHandlerUPP trackingHandler,WindowRef theWindow,
        void *handlerRefCon);
OSErr   InstallReceiveHandler(DragReceiveHandlerUPP receiveHandler,WindowRef theWindow,
        void *handlerRefCon);
OSErr   RemoveTrackingHandler(DragTrackingHandlerUPP trackingHandler,WindowRef theWindow);
OSErr   RemoveReceiveHandler(DragReceiveHandlerUPP receiveHandler,WindowRef theWindow);

Creating and Disposing of Drag References

OSErr   NewDrag(DragRef *theDrag);
OSErr   DisposeDrag(DragRef theDrag);

Adding Drag Item Flavors

OSErr   AddDragItemFlavor(DragRefthe Drag,DragItemRef theItemRef,FlavorType theType,
        const void *dataPtr,Size dataSize,FlavorFlags theFlags);
OSErr   SetDragItemFlavorData(DragRef theDrag,DragItemRef theItemRef,FlavorType theType,
        const void *dataPtr,Size dataSize,UInt32 dataOffset);

Performing a Drag

OSErr   TrackDrag(DragRef theDrag,const EventRecord *theEvent,RgnHandle theRegion);

Getting Drag Item Information

OSErr   CountDragItems(DragRef theDrag,UInt16 *numItems);
OSErr   GetDragItemReferenceNumber(DragRef theDrag,UInt16 index,DragItemRef *theItemRef);
OSErr   CountDragItemFlavors(DragRef theDrag,DragItemRef theItemRef,UInt16 *numFlavors);
OSErr   GetFlavorType(DragRef theDrag,DragItemRef theItemRef,UInt16 index,
        FlavorType *theType);
OSErr   GetFlavorFlags(DragRef theDrag,DragItemRef theItemRef,FlavorType theType,
        FlavorFlags *theFlags);
OSErr   GetFlavorDataSize(DragRef theDrag,DragItemRef theItemRef,FlavorType theType,
        Size *dataSize);
OSErr   GetFlavorData(DragRef theDrag,DragItemRef theItemRef,FlavorType theType,
        void * dataPtr,Size *dataSize,UInt32 dataOffset);

Getting and Setting Drag Status Information

OSErr   GetDragAttributes(DragRef theDrag,DragAttributes *flags);
OSErr   GetDragMouse(DragRef theDrag,Point *mouse,Point *globalPinnedMouse);
OSErr   SetDragMouse(DragRef theDrag,Point globalPinnedMouse);
OSErr   GetDragOrigin(DragRef theDrag,Point *globalInitialMouse);
OSErr   GetDragModifiers(DragRef theDrag,SInt16 *modifiers,SInt16 *mouseDownModifiers,
        SInt16 *mouseUpModifiers);

Window Highlighting Utilities

OSErr   ShowDragHilite(DragRef theDrag,RgnHandle hiliteFrame,Boolean inside);
OSErr   HideDragHilite(DragRef theDrag);
OSErr   UpdateDragHilite(DragRef theDrag,RgnHandle updateRgn);

Drag Manager Utilities

Boolean WaitMouseMoved(Point initialMouse);

Setting Drag Functions

OSErr   SetDragSendProc(DragRef theDrag,DragSendDataUPP sendProc,void *dragSendRefCon);
OSErr   SetDragInputProc(DragRef theDrag,DragInputUPP inputProc,void *dragInputRefCon);
OSErr   SetDragDrawingProc(DragRef theDrag,DragDrawingUPP drawingProc,void *dragDrawingRefCon);

Setting the Drag Image Translucent Dragging

OSErr   SetDragImage (DragRef theDrag, PixMapHandle imagePixMap,RgnHandle imageRgn,
                      Point imageOffsetPt,DragImageFlags theImageFlags);

Creating and Disposing of Universal Procedure Pointers

DragTrackingHandlerUPP  NewDragTrackingHandlerUPP(DragTrackingHandlerProcPtr userRoutine);
DragReceiveHandlerUPP   NewDragReceiveHandlerUPP(DragReceiveHandlerProcPtr userRoutine);
DragSendDataUPP         NewDragSendDataUPP(DragSendDataProcPtr userRoutine);
DragInputUPP            NewDragInputUPP(DragInputProcPtr userRoutine);
DragDrawingUPP          NewDragDrawingUPP(DragDrawingProcPtr userRoutine);
void    DisposeDragTrackingHandlerUPP(DragTrackingHandlerUPP userUPP);
void    DisposeDragReceiveHandlerUPP(DragReceiveHandlerUPP userUPP);
void    DisposeDragSendDataUPP(DragSendDataUPP userUPP);
void    DisposeDragInputUPP(DragInputUPP userUPP);
void    DisposeDragDrawingUPP(DragDrawingUPP userUPP);

Application Defined (Callback) Functions

OSErr   myDragTrackingHandler(DragTrackingMessage message,WindowRef theWindow,
        void *handlerRefCon,DragRef theDrag);
OSErr   myDragReceiveHandler(WindowRef theWindow,void *handlerRefCon,DragRef theDrag);
OSErr   muDragSendDataFunction(FlavorType theType,void *dragSendRefCon,DragItemRef theItemRef,
        DragRef theDrag);
OSErr   myDragInputFunction(Point *mouse,SInt16 *modifiers,void *dragInputRefCon,
        DragRef theDrag);
OSErr   myDragDrawingFunction(DragRegionMessage message,RgnHandle showRegion,
        Point showOrigin,RgnHandle hideRegion,Point hideOrigin,void *dragDrawingRefCon,
        DragRef theDrag);

Relevant TextEdit Function

OSErr   TEGetHiliteRgn(RgnHandle region,TEHandle hTE);

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Soft Drummer (Music)
Soft Drummer 1.0 Device: iOS Universal Category: Music Price: $14.99, Version: 1.0 (iTunes) Description: Soft Drummer is the closest thing to a pro session subtle drummer in your pocket. Easy to use and fast, it's much more than a... | Read more »
Is GO Gear the Pokemon GO map app you...
Now that we've settled into something of a Pokemon GO status quo, the number one desire of most players can best be summed out by modifying a quote from Rod Tidwell of Jerry Maguire: "Show me the Pokemon!" [Read more] | Read more »
Rodeo Stampede update: Mountains, new an...
The Savannah and Jungle were just the beginning in Rodeo Stampede. Get ready to head for the Mountains. I think I heard that in a beer ad once. [Read more] | Read more »
COSMOS RINGS (Games)
COSMOS RINGS 1.0.0 Device: iOS iPhone Category: Games Price: $5.99, Version: 1.0.0 (iTunes) Description: This game cannot be played without the Apple Watch.Released anniversary sale until August 31,2016 PST! A tragic tale of time's... | Read more »
How to get started selling on Mercari
As far as ecommerce has come over the last decade or so, there's still a tremendous opportunity to make it easier for people to buy and sell goods. That's especially true when it comes to shopping apps, which should only continue to increase in... | Read more »
Human Anatomy Atlas 2017 Edition - Compl...
Human Anatomy Atlas 2017 Edition - Complete 3D Human Body 1.0.24 Device: iOS iPhone Category: Medical Price: $24.99, Version: 1.0.24 (iTunes) Description: | Read more »
Heroes of Normandie (Games)
Heroes of Normandie 1.5 Device: iOS Universal Category: Games Price: $14.99, Version: 1.5 (iTunes) Description: The game does not support iPhone 4s and below | Read more »
Why you should never power up Pokemon in...
There's no question that candy is dandy in Pokemon GO. You need big quantities of it to evolve your Pokemon, and when combined with stardust, it can be used to power up your favorite pocket monsters as well, making them more formidable for the gym... | Read more »
Webzen launches 3D MMORPG MU Origin on i...
Mu Origin is featured time and time again at the very top of App Stores in China, and within the top five worldwide top-grossing charts on Google Play.Its popularity in Korea and China, featuring more than 120 registered players in China and 6... | Read more »
Severed (Games)
Severed 1.0 Device: iOS Universal Category: Games Price: $5.99, Version: 1.0 (iTunes) Description: LAUNCH DISCOUNT ON NOW!! ENDS AUGUST 4! ==== Take control of a one-armed warrior named Sasha, wielding a living sword on her journey... | Read more »

Price Scanner via MacPrices.net

Second-Quarter Tablet Shipments Fell 4.8% –...
The latest report from the global market research firm TrendForce finds that worldwide tablet shipments for this second quarter totaled 33.54 million units, representing a quarterly drop of 4.8% and... Read more
Global Smartphone Sales Volumes Mark Second S...
According to preliminary results from the International Data Corporation (IDC) Worldwide Quarterly Mobile Phone Tracker, vendors shipped a total of 343.3 million smartphones worldwide in the second... Read more
Apple TVs on sale for $20-$40 off MSRP
Best Buy has 32GB and 64GB Apple TVs on sale for $20-$40 off MSRP on their online store. Choose free shipping or free local store pickup (if available). Sale prices for online orders only, in-store... Read more
Mac minis on sale for $50-$100 off MSRP
B&H Photo has Mac minis on sale for $50 off MSRP including free shipping plus NY sales tax only: - 1.4GHz Mac mini: $449 $50 off MSRP - 2.6GHz Mac mini: $649 $50 off MSRP - 2.8GHz Mac mini: $949... Read more
Clearance 2015 13-inch MacBook Airs available...
B&H Photo has clearance 2015 13″ MacBook Airs available for $300 off original MSRP. Shipping is free, and B&H charges NY sales tax only: - 13″ 1.6GHz/4GB/128GB MacBook Air (MJVE2LL/A): $799... Read more
Apple certified refurbished iPad mini 4s avai...
Apple has certified refurbished iPad mini 4s now available for up to $120 off the cost of new models. An Apple one-year warranty is included with each iPad, and shipping is free. The following models... Read more
Notebook Makers In No Rush To Adopt USB-C – R...
Digitimes’ Cage Chao and Joseph Tsai note that while the USB Type-C interface is enjoying growing popularity among smartphones and tablet makers, notebook and all-in-one (AIO) PC vendors (other than... Read more
iMacs on sale for up to $250 off MSRP
B&H Photo has 21″ and 27″ Apple iMacs on sale for up to $250 off MSRP including free shipping plus NY sales tax only: - 27″ 3.3GHz iMac 5K: $2049 $250 off MSRP - 27″ 3.2GHz/1TB Fusion iMac 5K: $... Read more
12-inch 1.1GHz Retina MacBooks on sale for up...
Amazon has 2016 12″ 1.1GHz/256GB Retina MacBooks on sale for up to $100 off MSRP including free shipping: - 12″ 1.1GHz Space Gray Retina MacBook: $1199 $100 off MSRP - 12″ 1.1GHz Silver Retina... Read more
Bare Bones Software Releases Free TextWrangle...
Bare Bones Software has announced the release and immediate availability of TextWrangler 5.5, a significant update to its powerful, free, general purpose text editor for Mac OS X. TextWrangler is a... Read more

Jobs Board

*Apple* Solutions Consultant - APPLE (United...
Job Summary As an Apple Solutions Consultant, you'll be the link between our future customers and our products. You'll showcase your entrepreneurial spirit as you Read more
Lead *Apple* Solutions Consultant - APPLE (...
Job Summary The Lead ASC is an Apple employee who serves as the Apple business manager and influencer across a number of Reseller locations. The Lead ASC's role Read more
*Apple* Retail - Multiple Positions, Charles...
Job Description:SalesSpecialist - Retail Customer Service and SalesTransform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Retail - Multiple Positions, Willow...
Job Description:SalesSpecialist - Retail Customer Service and SalesTransform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Evangelist - JAMF Software (United S...
The Apple Evangelist is responsible for building and cultivating strategic relationships with Apple 's small and mid-market business development field teams. This Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.