| Documentation: FOX Drag and Drop Facilities [Remove Frame]

Drag and Drop refers to the facility in FOX that allows entities to be dragged not just from within one part of an application to another, but also between applications. The FOX Drag And Drop implementation is based on the XDND Protocol developed by John Lindal.
FOX supports the latest version (XDND 5) of this protocol. On Windows, FOX uses a very similar protocol.
As FOX provides fairly high-level API's to access these features, it is actually fairly easy to instrument your programs with a Drag & Drop facility.

For better understanding of how this works, it is important to define some terminology first:

- A Drag Source is a FOX Widget capable of sourcing one or more types of drag and drop data or Drag Types.
- A Drop Target is a FOX Widget capable of accepting one or more types of Drag Types.
- A Drag Type is an abstract handle to a type of drag and drop data.
- A Drag Action determines what happens when a drop takes place; examples of drag actions are copy, move, and link.

As mentioned before, the Drag Source and the Drop Target may or may not be in the same application. In fact, their corresponding applications could even be running on different machines. We assume, of course, that both drag source and drop target are shown on the same display.

Registering Drag Types

In order to communicate a particular data structure across applications, both partners need to first register a Drag Type. The Drag Type is created by calling the function:

    FXDragType FXApp::registerDragType(const FXString& name) const;

The registerDragType() function registers a new Drag Type "name" with the application's display, and returns an abstract handle to the Drag Type. The returned handle is used in all subsequent Drag and Drop operations. The Drag Type handle is unique for the display, that is, each application subsequently registering the same drag type name will receive the same handle. Obviously, the display must have been already opened before calling this function.

It is strongly suggested that if your application intends to communicate with others, the Drag Type Names you use should be those of the corresponding MIME types.
This guarantees everybody else's applications can make sense of drag data originating in your application [and vice versa]. Otherwise, Drag Type Names can be any ASCII string sequence.

A corresponding function:

    FXString FXApp::getDragTypeName(FXDragType type) const;

Will return the Drag Type Name, given the Drag Type. You may need to use this in case your application receives a drop of an unknown type, and you need to decide what to do with it.

Becoming A Drop Target

In order to be able to receive drops, a FOX Widget first needs to make itself a Drop Target. It does this by calling:

    virtual void FXWindow::dropEnable();

To cancel drop-ability, use a function:

    virtual void FXWindow::dropDisable();

A Widget will not receive drag and drop messages unless it has been enabled as a drop target with dropEnable(). Note that the Widget may receive drag and drop messages with drop-data it does not understand, and thus it should only accept drops of the proper type.

Messages to the Drop Target

FOX Widgets which have have been enabled for Drop Targets may receive a number of messages during a drag-and-drop operation. To give a user feedback about what is going on, I suggest that the Widget somehow change its visual appearance based on receiving these messages.

For example, a Folder Icon, normally shown in the closed state, may be changed to the opened state to indicate that a drop is pending and will be accepted if performed. Another method [which is usually performed by the Drag Source Widget, see later], is to change the shape of the cursor to a STOP sign when the drop will NOT be accepted; one could also use a combination of the two methods.

Drop Target Widgets may receive the following messages:

- SEL_DND_ENTER. This message is received when the cursor first enters the Widget. At this point, the Widget may inspect the Drag Types available, and determine whether or not to accept a drop. If necessary, the Widget could even tentatively request the Drop Data, and inspect the data itself. It must be prepared to throw the data away again, however.
- SEL_DND_LEAVE. This message is received when the cursor leaves the Widget. If the Widget did not receive a SEL_DND_DROP before this message, it must release the data, if it has requested it.
- SEL_DND_DROP. The Widget receives this message when an actual drop takes place. Typically, the Widget requests the Drop Data at this point.
- SEL_DND_MOTION. This message indicates to the Widget the exact position of the cursor (and thus the Drop Point). Simple Widgets may not care about this, but more complicated Widgets will probably use the position to determine the exact action to take. For example, depending on position, the Widget may or may not accept certain Drop Types.

At any point between receiving SEL_DND_ENTER and SEL_DND_LEAVE /SEL_DND_DROP, the Drop Target may call the following functions to inquire about the type of the data being dragged, the data itself, and the drag-action being performed. Based on this information, it can feed back information to the Drag Source to indicate whether or not it will accept the data:

    void FXWindow::acceptDrop(FXDragAction action=DRAG_ACCEPT);

To accept or reject a drop, the Widget calls acceptDrop() with an argument specifying the Drag Action suggested by the Drop Target. The Widget can call this any number of times; however, the last value will be the one reported to the Drag Source Widget. For acceptDrop(), the following values are valid:

- DRAG_REJECT. This indicates that the Drop Target will NOT accept any type of Drag Action.
- DRAG_ACCEPT. The Drop Target chooses to accept the drop, no matter what the Drag Action is. The suggested Drag Action is the same as the one supplied by the Drag Source.
- DRAG_COPY. The Drop Target accepts the drop, but suggests that the Drag Action be a copy.
- DRAG_MOVE. The Drop Target accepts the drop and suggests that the Drag Action be a move.
- DRAG_LINK. The Drop Target accepts the drop and suggests that the Drag Action be a link.

Other Drag Actions may be supported in the future. The Drop Target can find out the Drag Action by calling the following function:

    FXDragAction FXWindow::inquireDNDAction() const;

The Drag Source should change the cursor to reflect the Drag Action in effect; if necessary, the cursor should change to reflect the Drag Action suggested by the Drop Target.

Normally, a Widget may get many, many SEL_DND_MOTION messages. In order to cut down on the traffic, a Drop Target Widget may indicate a rectangle and whether or not it wants further updates while the cursor is inside this rectangle by calling:

    void FXWindow::setDragRectangle(FXint x,FXint y,FXint w,FXint h,FXbool wantupdates=TRUE);

Widgets which do not care where the drop takes place may call setDragRectangle(0,0,width,height,FALSE), which will cause the Drag Source to send no further updates while the cursor is inside the Widget.

    void FXWindow::clearDragRectangle();

Clearly, this is the opposite of setDragRectangle(). It is equivalent to setDragRectangle(0,0,0,0,TRUE);

    FXbool FXWindow::inquireDNDTypes(FXDNDOrigin origin,const FXDragType*& types,FXuint& numtypes);
    FXbool FXWindow::offeredDNDType(FXDNDOrigin origin,FXDragType type);

The first call yields an array of Drag Types currently available from the Drag Source. The list is read-only, and should NOT be freed. The Widget should NOT keep pointers to this list, as the list ceases to exist after SEL_DND_LEAVE. The second call tests to see if a certain Drag Type is being offered by the Drag Source.

If the Drag Type information is not enough, the Drop Target may have to inquire the actual data from the Drag Source and inspect it. It does this by calling:

    FXbool FXWindow::getDNDData(FXDNDOrigin origin,FXDragType type,FXuchar*& data,FXuint& size);

This call acquires the Drag Type type from the Drag Source. Upon return, data points to an array of bytes containing the Drop Data, and size is set to the number of bytes in the array. The array is now owned by the Drop Target Widget, and should be freed with the FXFREE() macro. The corresponding function in the Drag Source is describes elsewhere. The parameter origin should be set to FROM_DRAGNDROP.

Becoming a Drag Source

Making a Widget a Drag Source is comparatively easy. The transaction begins when the mouse button goes down. The Widget will need to call grab() to capture the mouse to the Widget, so that all future mouse events will be reported to the Widget, even if they occur outside of the Widget. Next, the Widget will call:

    FXbool FXWindow::beginDrag(const FXDragType *types,FXuint numtypes);

to start a drag-operation. The arguments to beginDrag() describe the list of types [which must have been registered previously] which are being offered. The Drag Source must be willing to furnish each of these types when requested by the Drop Target. The beginDrag() function returns FALSE if it failed to initiate a drag operation; the application should not proceed with dragging in this case.

Upon each mouse movement, the Drag Source needs to indicate the new mouse position to the system; it also notifies the Drop Target of the new Drag Action. It does this by calling the function:

    FXbool FXWindow::handleDrag(FXint x,FXint y,FXDragAction action=DRAG_COPY);

The handleDrag() function determines the Widget under the cursor, and issues a SEL_DND_ENTER when it first enters a Widget, a SEL_DND_LEAVE when it leaves the Widget, and a SEL_DND_MOTION when the cursor simply has moved over the Widget [subject to the drag rectangle set by the Drop Target]. It will not send any messages if the widget under the cursor has not called dropEnable() first to enable drops on it.

The handleDrag() function may return FALSE if it fails. To find out if a Drag Source is in the middle of a drag operation, applications may call the following member function:

    FXbool FXWindow::isDragging() const;

While the Drag Source is dragging, it may want to inquire whether the Drop Target's accepted or rejected a drop. It does this by calling:

    FXDragAction FXWindow::didAccept() const;

The function didAccept() simply returns DRAG_REJECT when the Drop Target would NOT accept the drop, and returns DRAG_COPY, DRAG_MOVE, DRAG_LINK if it did; the Drag Source should reflect the Drag Action returned by changing its cursor. For safety's sake, didAccept() will also returns DRAG_REJECT if the Drop Target has not called dropEnable(), or if the Drop Target fails to respond to any drag-and-drop messages.

Applications may choose to change the cursor shape based on what didAccept() returned, as illustrated by the following code fragment:

    handleDrag(event->root_x,event->root_y);

    if(didAccept()!=DRAG_REJECT){
      setDragCursor(drop_ok_cursor);
      }
    else{
      setDragCursor(drop_not_ok_cursor);
      }

The rationale is that even though Drop Targets may give a visual cue when a drop is OK, not all applications running on your system may be drag-and-drop aware; changing the cursor also will give an additional clue.

When the user releases the mouse button, the Widget needs to call ungrab() to release the mouse capture, and then calls:

      FXDragAction FXWindow::endDrag(FXbool drop=TRUE);

This will cause a SEL_DND_DROP message to be sent to the Drop Target, if and only if:

- The flag drop is TRUE.
- The Drop Target has previously called acceptDrop().
- The Drag Source has received status messages back from the Drop Target.

Passing a flag drop allows the Drag Source to deny a drop even though the Drop Target may have accepted a drop. The endDrag() function returns the action actually performed by the drop target.
The XDND version 5 protocol returns the drag action performed by the target, since in processing the drop, the target may be unable to perform the requested action, perhaps due to some runtime error. Returning the action actually performed allows the drag source to take the appropriate action.

Messages to the Drag Source

During a drag operation, a drag source may receive one or more requests for the drag data. These requests take the form of a SEL_DND_REQUEST message sent to the owner of the drag data. When a drag source receives a request for its data, it should first inspect the requested drag type, which is found in the FXEvent's target member variable. If the drag source can supply its data in the requested drag type, it should then allocate an array (using the FXMALLOC macro) and stuff the data into it.

The drag source then calls

      FXbool FXWindow::setDNDData(FXDNDOrigin origin,FXDragType type,FXuchar* data,FXuint size);

To hand the array over to the system. At this point, ownership of the array passes to the system, and the drag source should not attempt to make any further references to this array. The origin parameter should be set to FROM_DRAGNDROP.

The drop target may make a request for the drag data from the drag source by calling getDNDData(), described above.

Drag and Drop of FOX Objects

The data exchange described above takes place using raw bytes. In more realistic cases, complicated data structures may have to be exchanges. It is important to realize that:

- The Drag Source and Drop Target may be different programs. Thus, it is usually meaningless to exchange pointers to data structures.
- The Drop Target and Drag Source may not only be different programs, but also may be programs running on different machines with different byte orders and different word lengths.

FOX takes care of some of the latter troubles by furnishing special FOX primitive types, such as FXchar, FXshort, FXint and so on. A FOX implementation will ALWAYS make sure these types have the same size, although byte order may still be reversed on some machines.

More sophisticated data transfers can be accomplished using the FOX FXMemoryStream class. The FXMemoryStream is a subclass of FXStream that serializes/deserializes data to/from a memory-buffer. The FXStream classes also support byte swapping on the reader side, making it very convenient to exchange data between hererogeneous machines; moreover, the FOX Stream classes support serialization of FOX Objects.

Thus, entire networks of objects may be serialized, transmitted to the drop site, and then deserialized.

Example:

Serialize into a buffer, then give the buffer to the DND system:

> FXMemoryStream str;
> FXuchar *buffer;
> FXuint size;
> FXObject *myobjectptr; // Pointer to the FXObject-derived object we wish to transfer
> FXuchar endianness;

> endianness=FXStream::isLittleEndian();

> str.open(NULL,FXStreamSave); // The FXMemoryStream will create its own buffer
> str << endianness;
> str << myobjectptr;
> str.takeBuffer(buffer,size); // Take ownership of the buffer away from the FXMemoryStream
> str.close();
> setDNDData(dndtype,buffer,size); // Give the buffer to the DND system

Take data from the DND system, then give the buffer to the Stream and deserialize from it:

> FXMemoryStream str;
> FXuchar *buffer;
> FXuint size;
> FXObject *myobjectptr; // When done, this points to an FXObject-derived object
> FXuchar endianness;

> getDNDData(dndtype,buffer,size); // Take possesion of the buffer from the DND system

> str.open(buffer,size,FXStreamLoad);
> str >> endianness;
> str.swapBytes(endianness!=FXStream::isLittleEndian()); // Swap bytes in the receiver if necessary!!
> str >> myobjectptr;
> str.close();
> FXFREE(&buffer);

As you see, this is a mighty fine way to transfer arbitrary objects between applications. All you have to do is derive certain objects from the FXObject base class, then properly inplement the load() and save() member functions for that class, so that all object member data may be properly serialized or deserialized. For more info, see the chapter on Serialization.

Tips and Hints: Moving Data Between Applications

When data is being moved between applications, the Drop Target should perform the following sequence of operations:

Acquire the dropped data, using getDNDData(), exactly the same as what it would do for a Copy Drag Action;

Then do a getDNDData() with the Drag Type DELETE, which must have been previously registered with registerDragType("DELETE").

The Drag Source will not supply any data when a request for the DELETE drag type is received; instead, knowing the data has been properly received by the Drop Target, it will delete the data instead.

Thus, the getDNDData() call with Drag Type DELETE will yield a NULL data array pointer.

Tips and Hints: When to Copy and When to Move

This is no hard and fast rule, but generally speaking when data are being dragged within the same window, the default Drag Action should default to DRAG_MOVE, whereas when dragging between windows, the Drag Action should default to DRAG_COPY. These defaults can be overridden by holding down the Control-Key, which should force a DRAG_COPY, or the Shift-Key, which should force a DRAG_MOVE. Holding down the Alt-Key should probably force a DRAG_LINK.

Tips and Hints: When to Auto-Scroll

When dragging from within scrollable windows, no scrolling should take place while outside the window; instead, scrolling should happen only when the cursor is being moved very close to the window border.

Tips and Hints: Let Cursor Reflect the Action

There are two major schools of thought; some people prefer to let animate or highlight the drop-site to indicate an impending accept or reject of a drop, whereas others change the cursor instead. Apart from psychology, my take on this is do both:

- Changing the cursor has the advantage that there is some feedback while moving over inert backgrounds.
- Changing the drop site has the advantage that it is very clear where the dropped data will wind up, especially if drop sites may be very small on the screen.

This reflects my view that in the software world, we can make our own rules; we can diverge from the physical model of ``manipulating rigid objects'' if this is appropriate or gives the user a better handle on things.

Copyright © 1997-2016 Jeroen van der Zijp