Common Desktop Environment: Programmer's Guide

5 Integrating with Drag and Drop


Contents of Chapter:
Summary
Library and Header Files
Demo Program
Using Drag and Drop
To Integrate with Drag and Drop
Drag-and-Drop User Model
Drag and Drop Capability
Drag Icons
Drags from Inside Windows
Visual Feedback
Drag-and-Drop Sources
Drag-and-Drop Destinations
Drag-and-Drop Convenience API
Simplify Use for Developers
Establish Policy
Provide Common Functionality
Leverage Existing Motif API
Drag-and-Drop Transaction
Integration Action Plan
Review Drag-and-Drop API and Sample Code
Review Your Application for Possible Drop Zones
Review Your Application for Possible Drag Sources
API Overview
DtSvc Library and Header File
Functions
The DtDndContext Structure
Protocols
Operations
How Drag Sources Are Used
Starting a Drag
Dragging from Lists or Icons
Drag Threshold
Btransfer or Badjust
Initiating a Drag
Using Convert Callbacks
How Drop Zones Are Used
Registering a Drop Zone
Using the Transfer Callback
Using Data Typing
This chapter describes the drag-and-drop user model and the Common Desktop Environment drag-and-drop convenience application program interface (API), and describes how to use drag and drop.


Summary

The Common Desktop Environment contains an application program interface (API) for drag and drop that is layered on top of Motif to provide convenient, consistent, and interoperable drag and drop across the desktop. The Common Desktop Environment drag-and-drop API makes it easier for developers to implement drag and drop. With drag and drop, users can manipulate objects on the screen directly by grabbing them, dragging them around the display, and dropping them on other objects to perform a transfer of data.

Text, files, and buffers are the three categories of data that are used with the Common Desktop Environment drag-and-drop API. Text is defined, in this context, as any user-visible text such as text in type-in fields. A file is a container of data that resides in the file system. Each file also has a format that describes its contents. Buffers are data contained in memory. Typically, each buffer also has a format that describes its contents.

Library and Header Files

To use drag and drop, you need to link to the DtSvc library. The header file is Dt/Dnd.h.

Demo Program

A demo program containing an example of drag and drop is in /usr/dt/examples/dtdnd.

Using Drag and Drop

To Integrate with Drag and Drop

To integrate your application with drag and drop, follow these steps:

  1. Include Dt/Dnd.h.

  2. Link to libDtsvc.

  3. As recipient:

    a. Register as a drop zone using DtDndDropRegister.

    b. Optionally, write a drop animate callback.

    c. Write a transfer callback.

  4. As source:

    a. Recognize user action (possibly requiring a modification of translation tables) and call DtDndDragStart.

    b. Write a convert callback.

    c. Write a drag finish callback.


Drag-and-Drop User Model

This section describes the user model behind drag and drop to help you design an application that is consistent with the rest of the desktop and users' expectations.

See the CDE Style Guide and Certification Checklist for more information about the drag-and-drop user model and for guidelines for the visual appearance of drag-and-drop elements.

When drag and drop is available for all applications on the desktop, the system is more predictable to the user and is, therefore, easier to use and to learn. Users leverage their learning across more applications by using skills that they already know. In addition, many users prefer drag and drop to using menus.

In this chapter, the term drop zone is used to describe places where users can drop something. Drop zones are usually represented by a control or icon graphic; for example, a trash icon or a type-in field graphic. The term drop target is used to describe the rectangular area that represents the drop zone.

Drag and Drop Capability

With the Drag and Drop capability, users can select and manipulate objects represented as icons.


Note: Drag and drop is an accelerator to functionality that is accessible through other user interface controls supported within your application. However, not all users are able to take advantage of drag and drop. Do not support any basic operations solely through drag and drop. Any basic function that your application supports through drag and drop should also be supported by menus, buttons, or dialog boxes.

Drag Icons

When users select and manipulate icons using drag and drop, they expect the graphic icon that represents the item being dragged to remain consistent from the selection through the drag and drop. If the user selects a message icon in the File Manager and starts to drag it, the source portion of the drag icon is represented by that message icon. Providing this kind of consistency makes drag and drop more predictable to the user. Where the destination application uses icons, the icon shown should, in most cases, be the same one that was selected and then dragged and dropped. This behavior is not, however, always appropriate for all applications. Dragging text is an exception. A text drag icon is used instead of dragging the selected text.

Both the source and destination applications specify the visual appearance of drag icons. You are responsible for ensuring that an application has a consistent and appropriate icon to drag. Although the drag-and-drop library provides default icons, it is a good idea for you to specify your own for each application. Most often, you should use the data-typing database to obtain the icon associated with the type data represented by the icon. See Chapter 9, "Accessing the Data_Typing Database ."

When users start a drag without selecting an icon, it is appropriate for you to provide a relevant drag icon. For example, in an appointment editor, the user can select an appointment out of a scrolling list--which may or may not show icons. You should use an appointment icon as the source indicator. The destination application (for example, a File Manager) should display the same appointment icon.

Parts of the Drag Icon

The drag icon changes appearance to provide drag-over feedback when the user moves it over potential drop zones.

The drag icon has three parts that combine to provide the drag-over feedback:

The state indicator is a pointer used for positioning combined with a valid or invalid drop zone indicator. The valid state indicator is an arrow pointer. The pointer has a hot spot so users can position it in a predictable manner. The invalid state indicator--a circle with a diagonal line--is displayed when users have positioned the cursor over an invalid drop zone.

The operation indicator gives users feedback on what operation is occurring during the drag; either move, copy, or link. Because most drags are moves, users are given additional feedback when they perform the less-frequent copy or link operations.


Note: The operation feedback is drawn on top of the state and source feedback. This behavior is consistent with Motif drag-and-drop behavior.

The user can choose the drag operation move, copy, or link by pressing and holding certain keys during a drag, as shown in Table 5-1.

Table 5-1 Keys Used to Modify a Drag Operation

The source application can force a copy, as in the case of the read-only File Manager window. When the user chooses an operation, the drop zone must match that operation for the drop to succeed; otherwise, the drop zone is invalid. In other words, if the user chooses a copy by holding down the Control key, and then drags the drag icon over the trash icon, the drag icon should show the trash icon as an invalid drop zone and any drop should fail, because copying to the trash is not allowed.

The source indicator represents the selection (or the item being dragged). The source indicator varies depending on whether the selection represents single or multiple items and what kind of item the selection represents. Table 5-2 shows the default source indicators in the Common Desktop Environment. These source indicators are generated automatically when you use the Common Desktop Environment drag-and-drop convenience API. The icons are approximations, not exact screen representations.

Table 5-2 Types of Drag Icons

Drags from Inside Windows

Sometimes an application needs to enable a drag from within a dialog box or window. The Appointment Editor in Calendar has a scrolling list of appointments and an entry area for editing an appointment. Users can drag from the scrolling list to get an appointment, but users also need to be able to drag from the appointment entry area. Enabling users to drag from the entry area covers those times when the appointment is not yet inserted in the calendar (for example, when a proposed meeting time is entered but not inserted into the calendar).

The item that can be dragged needs to have an icon graphic associated with it. Place the icon graphic in the dialog box in an appropriate area adjacent to the information to be dragged. The upper-right corner of the dialog box or window is the recommended default position. The icon lets the user know that something can be dragged and the graphic used is the same graphic used in the drag icon to provide consistency. The icon should be 32x32 pixels and have a label so that it resembles a File Manager icon. See the CDE Style Guide and Certification Checklist chapter on drag and drop for more information.


Note: Drags are only enabled from human interface elements that have components or items that can be selected. Drags cannot be enabled from static labels such as those on buttons or menus.

Visual Feedback

The following sections describe the drop zone feedback and transition effects of drag and drop.

Drop Zone Feedback

The default drop zone feedback, called drag under , can be a solid line drawn around the site, a raised or lowered surface with a beveled edge around the drop zone, or a pixmap drawing over the drop zone.

Transition Effects

Transition effects show the user that the drop has either succeeded or failed. The two transition effects are melt and snap back.

Melting occurs when the user drops a drag icon on a valid drop zone. When the user drops a drag icon on a valid drop zone, the drag icon melts into the drop zone. The drag icon is replaced by the icon appropriate to the destination application. A printer on the Front Panel may show nothing other than the melting effect. An open File Manager window may display an appropriate icon.

When an icon is dropped, sometimes the melting effect does not take place immediately. The icon is displayed where it is placed until the transfer is done. It is a good idea for the destination to set its cursor to a busy state while the transfer is occurring. The user cannot move or select the icon until the transfer is complete; the busy cursor lets the user know the transfer is in process.

Snap back occurs when a drop fails. Drops can fail in two ways. If the user drops a drag icon over an invalid drop zone, then the drag icon snaps back to the source application. Once a drop occurs, the source and destination applications have to transfer the data. If the data transfer fails, the drag icon snaps back and the destination application is responsible for indicating failure to the user and providing information on why the drop failed.

Drag-and-Drop Sources

To help you understand the behavior of drag-and-drop sources, Table 5-3 describes the key desktop components that can be a source of drags of text selections, files, and buffers.

Table 5-3 Desktop Components That Can Be Drag Sources

*Any application that has Motif text field sources selected drags text.

Drag-and-Drop Destinations

The following components on the desktop provide drop destinations:

Each component accepts drops of text selections, files, and buffers. Most of the text drop destinations are provided automatically by the Motif library. File or buffer data drop destinations require additional code.

When a user drops data from a file, and that file is modified in some way, the modifications can be written back to the original holder of the file. This behavior is described as saveback . However, when data is dropped from a buffer, the data does not have information about an originating file. As a result, changes to data from buffers cannot be written back, because there is no original holder of the data. This behavior is described as no saveback .

For example, the Mailer can export mail attachments to editors using drag and drop. If the attachment is exported as a buffer (that has no saveback), the editor has no way to change the original attachment in the mailer. So, the editor can only save its modified version of the attachment to a new file.

Because mail attachments are not already separate files (they are embedded into a mail folder file), they are only exported as buffers and cannot be saved back by other editors.

If the attachment is exported as a file (that has saveback) the editor saves its modified version to that same file.

Table 5-4 describes the drops of text selections, files, and buffers on editor-type components such as Text Editor, Icon Editor, Calendar, Mailer, and Application Builder.

Table 5-4 Editor Drop Destinations

Table 5-5 describes the drops of text selections, files, and buffers on file and folder icons in the File Manager.

Table 5-5 File Manager Drop Destinations

Table 5-6 describes the drops of text selections, files, and buffers on action icons in the Front Panel.

Table 5-6 Front Panel Drop Destinations

See the CDE Style Guide and Certification Checklist for more information and guidelines on how the drag and drop should appear to the user.


Drag-and-Drop Convenience API

The Common Desktop Environment provides a drag-and-drop convenience API to promote consistency and interoperability across the desktop, and to make it easier for developers to implement drag and drop.

The existing Motif API for drag and drop provides reasonable functionality to achieve a rendezvous between the source and destination applications in the transaction. It provides a framework for data transfer but leaves the actual data transfer details up to the application. For true consistency and interoperability between applications across the desktop, all applications must use the same data transfer protocols. The Common Desktop Environment drag-and-drop convenience API provides common data transfer routines.

Simplify Use for Developers

The existing Motif API for drag and drop is very flexible and, therefore, is somewhat difficult for nonexpert developers to use. The Common Desktop Environment drag-and-drop convenience API provides some convenience functions, described in the following paragraphs, that result in an API that is simpler and easier to use by providing the following services:

Establish Policy

The drag-and-drop API establishes policy in three areas:

Provide Common Functionality

The drag-and-drop API provides common functionality in these areas:

Leverage Existing Motif API

The API for drag and drop does not invent a new drag-and-drop subsystem; rather, it uses the existing Motif API. In addition, since common data transfer protocols were chosen, where available, applications can interoperate at the selection protocol level without requiring global use of the new API.

The transfer of text and files use existing protocols. Buffer transfer uses new protocols.


Drag-and-Drop Transaction

Figure 5-1 illustrates how the basic drag-and-drop transaction is performed. The dotted-line boxes show the basic transaction. The solid boxes show the optional transitions and operations.

Figure 5-1 The basic drag-and-drop transaction

Figure 5-2 Optional transitions and operations for drag and drop

Figure 5-2 illustrates the optional transitions and operations for the drag-and-drop transaction.


Integration Action Plan

This section suggests a plan of action for integrating your application with drag and drop in Common Desktop Environment 1.0.

Review Drag-and-Drop API and Sample Code

Use the information provided in this chapter to familiarize yourself with the drag-and-drop API. Once you have a basic understanding of the API, review the source code for the drag-and-drop demo program, /usr/dt/examples/dtdnd . This code provides examples of how to use the API in various ways. The examples should give you an understanding of the character and amount of code you need to write to support drag and drop in your application. Understanding the actions and the data-typing API is useful as well.

Review Your Application for Possible Drop Zones

Identify the types of data your application might accept through a drag-and-drop transaction. If, for example, you are writing a bitmap editor, you want to support the drop of files. Once you have identified the data types you will allow to be dropped on your application, determine the widget or widgets that should be drop zones. For the bitmap editor example, you may decide the only place a file should be dropped on the application is the bitmap editing area. In this case, register the widget representing this area using DtDndDropRegister() and provide the appropriate callbacks.

Because it is easiest to handle the drop of file names, start by implementing them. Once you have mastered this technique, you will find it easier to move on to implementing the drop of text and buffers.

Review Your Application for Possible Drag Sources

Identify the types of data your application might permit as sources for a drag-and-drop transaction. In the example of the bitmap editor, you may want bitmap data containing the current bitmap selection to be a drag source as an accelerator for cut and paste. Once you have identified the data types you will allow to be dragged from your application, determine the widget or widgets that should be drag sources. In the bitmap editor example, you may decide the bitmap editing area containing the highlighted bitmap selection should serve as the drag source. In this case, enable the widget representing this area for sourcing drags.

Start by implementing the drag of buffers that are most appropriate or specific to your application. You will also want to add the ability to drop buffers on your application to enable easy data transfer between multiple invocations of your application.


API Overview

This section provides an overview of the drag-and-drop application program interface (API).

DtSvc Library and Header File

The drag-and-drop functionality is implemented in the Desktop Services library, DtSvc . To access the drag-and-drop API, include the header file <Dt/Dnd.h> and link with -lDtSvc .

Functions

The API includes four function calls, which are declared in the header file Dnd.h and outlined in the following paragraphs. These functions are described in greater detail in later sections.

The DtDndContext Structure

You handle transfers of data using the DtDndContext data structure. This structure contains fields for the transfer protocol, the number of items being transferred, and an array of the data items being transferred. See the DtDndDragStart(3X) and DtDndDropRegister(3X) man pages for details about the syntax of this structure.

Protocols

Protocols are used to tell the API the type of data being transferred. The predefined protocols are shown in Table 5-7.

Table 5-7 Predefined Protocols

Operations

The drag source and the drop zone can transfer the data in one of three ways, as described in Table 5-8.

Table 5-8 Data Transfer Operations


How Drag Sources Are Used

This section describes how drag sources are used.

Starting a Drag

A drag is started in one of two ways. First, the user may start a drag by pressing down Btransfer , the middle mouse button. As soon as the button is pressed down, the drag begins. Second, the user may start a drag by pressing and holding down Bselect , the left mouse button, and moving the cursor across the screen. The drag begins when the user moves the mouse a certain distance. This distance is called the drag threshold and it is measured in pixels. The default drag threshold is 10 pixels for Bselect . For Btransfer , the drag threshold is 0; because there is no drag threshold, the drag begins as soon as the pointer is moved. Motif scrolled text lists and text widgets are automatically registered as drag sources for text drags using Btransfer and Bselect .

Dragging from Lists or Icons

There are two common interface objects that can be used to source a drag: lists and icons. The Motif List widget automatically sources text drags. If other types of drags are desired, this is accomplished by overriding the default widget translations with new Bntl and Btn2 translations. There is no icon widget in Motif but often a drawing area is used as container of icons. In this case, an event handler for Btn1Motion would be used to start the drag. Refer to the sample code in /usr/dt/examples/dtdnd for more detailed code examples.

Drag Threshold

When starting a drag using Bselect the widget event handler or translation procedures must apply the drag threshold of 10 pixels before starting the drag. For Btransfer , there is no threshold and the drag starts immediately.

Btransfer or Badjust

Style Manager has a setting in the Mouse category that controls whether Btn2 , the middle mouse button, acts as Btransfer or Badjust . This setting is stored as a resource name: enableBtn1Transfer . A setting of 1 indicates that Btn2 is Badjust and should adjust the selection while a setting of any other value means that Btn2 is Btransfer and should start a drag. Btn1 , the left mouse button, always starts a drag.

The following example shows how to determine whether Btn2 should be Btransfer or Badjust.

Display* display;

int adjust;

XtVaGetValues ((Widget)XmGetXmDisplay(display, "enableBtn1Transfer", &adjust, NULL);

if (adjust == 1)

/* Btn2 is adjust */ else /* Btn2 is transfer */

Initiating a Drag

Common Desktop Environment 1.0 applications start a drag by calling DtDndDragStart() . This function performs some desktop-specific setup and calls XmDragStart() to initiate a drag. The DtDndDragStart() function synopsis and parameter usage are described as follows:

Widget

DtDndDragStart( Widget dragSource, XEvent *event, DtDndProtocol protocol, Cardinal numItems, unsigned char operations, XtCallbackList convertCallback, XtCallbackList dragFinishCallback ArgList argList, Cardinal argCount)

Widget dragSource
The widget that received the event that triggered the drag.

XEvent *event
The button press or button motion event that triggered the drag.

DtDndProtocol protocol
The protocol used for the data transfer. The protocol may be one of the following:

DtDND_TEXT_TRANSFER
DtDND_FILENAME_TRANSFER
DtDND_BUFFER_TRANSFER

Cardinal numItems
Specifies the number of items being dragged.

unsigned char operations
Specifies options supported by dragSource . The options are XmDROP_MOVE , XmDROP_COPY, and XmDROP_LINK . A drag source may support any combination of these operations. You specify a combination of operations by using or. For example, to support the move and copy operations, specify XmDROP_MOVE | XmDROP_COPY .

XtCallbackList convertCallback
This callback is invoked when a drop has started and the drop zone has requested data from the drag source. The convertCallback is explained in more detail in the next section.

XtCallbackList dragFinishCallback
This callback is invoked when the drag-and-drop transaction is complete. The dragFinishCallback should reset the dragMotionHandler() and free any memory allocated by the drag source during the drag-and-drop transaction.

Using Convert Callbacks

The convert callback provides data to the drop zone when a drop occurs. The first action in the convert callback is a verification of the reason field in the callData . If the reason is not DtCR_CONVERT_DATA or DtCR_CONVERT_DELETE , you should return immediately; otherwise, proceed to convert the data. For example, if you are handling the conversion of a file name, retrieve the appropriate file name from your internal data structures and copy it into the file data object. If your drag source supports the move operation, you need to support conversion of the DELETE target. That is, when convertCallback is called with a reason of DtCR_CONVERT_DELETE , perform the appropriate deletion action for the data that was moved. In the case of the file transfer, delete the file. Here is a simple convertCallback that handles the conversion and deletion of file names.

void
convertFileCallback(
   Widget dragContext,
   XtPointer clientData,
   XtPointer callData)
{
   DtDndConvertCallbackStruct *convertInfo =
   (DtDndConvertCallbackStruct*) callData;
   char    *fileName = (char *) clientData;

if (convertInfo->reason == DtCR_DND_CONVERT_DATA) { convertInfo->dragData->data.files[0]= XtNewString(fileName); } else if (convertInfo->reason == DtCR_DND_CONVERT_DELETE) { deleteFile(fileName); } else { convertInfo->status = DtDND_FAILURE; } }


How Drop Zones Are Used

This section describes how drop zones are used.

Registering a Drop Zone

You generally register drop zones just after the widget that is going to be the drop zone is created. If you want a modal drop zone, you may register the widget as a drop zone when you want users to be able to drop on it and unregister it when you do not want users to drop on it.

Motif text widgets are automatically registered as drop zones for text when they are created. Dual registration is allowed. If you want a text widget to accept drops of other data, such as file names, in addition to text, you may register the text widget as a drop zone for file names as well. The text drop functionality provided by Motif is preserved. The functionality for file-name (or other data-type) drops is layered on top.

Use the function DtDndDropRegister() to register a widget as a drop zone. This function handles dual registration, if necessary, performs desktop-specific setup, and calls XmDropSiteRegister() . The DtDndDropRegister() function synopsis and parameter use are as follows.

void DtDndDropRegister(
   Widget          dropSite,
   DtDndProtocol   protocols;
   unsigned char   operations;
   XtCallbackList  transferCallback;
   ArgList         argList;
   Cardinal        argCount)

Widget dropSite
The widget that is being registered as a drop zone.

DtDndProtocol protocols
Specifies the list of data transfer protocols that the drop zone can use. To specify the use of more than one protocol, use OR with the protocol values.

unsigned char operations
The operations supported by the drop zone. The drop zone may support any combination of XmDROP_MOVE , XmDROP_COPY , and XmDROP_LINK by using OR for the desired combination of operations.

XtCallbackList transferCallback
This function accepts the data that is dropped on the drop zone. The transfer callback is explained in greater detail in the next section.

ArgList argList
Specifies an optional argument list.

Cardinal argCount
Specifies the number of arguments in argList.

Using the Transfer Callback

The transfer callback accepts data from the drag source when a drop occurs. The first action in the transfer callback is a verification of the reason field in the callData . If the reason is not DtCR_DND_TRANSFER_DATA , you should return immediately; otherwise, proceed with data transfer based on its type and the operation specified in the reason. For example, if you are handling the copy of a file, retrieve the file name from the data structure, open the file, and copy its contents. If your drop zone supports more than one data type, you need to support the transfer of each data type appropriately.

Here is a simple transfer callback for a drawing area drop zone that supports the copying of text and file-name data types.

void
   TransferCallback(
   Widget widget,
   XtPointer clientData,
   XtPointer callData)
{
    DtDndTransferCallbackStruct *transferInfo =
       (DtDndTransferCallbackStruct*) callData;
    int ii;
    DtDndcontext * dropData = transferInfo->dropData;
       return;
    switch dropData->protocol {
    case DtDND_FILENAME_TRANSFER:
       for (ii=0; ii < dropData->numItems; ii++) {
          drawTheString(dropData->data, strings[ii]);
       }
      break;
   case DtDND_TEXT_TRANSFER:
      for (ii=0; ii<dropData->numItems; ii++){
      drawTheFile(dropData->data.files[ii]);
      }
      break;
   default: 
      transferInfo->status = DtDND_FAILURE;
   }
}

Using Data Typing

In an application that accepts drops of buffers, you may want to handle the dropped data in a different way depending on its type. To accomplish data typing, use the data-typing API. Data-typing function calls of interest are DtDtsBufferToDataType() and DtDtsBufferToAttributeValue() . The former returns the data attribute name for the data, the latter returns the value of a specified attribute of the data. Attributes you may find useful for drag and drop are shown in Table 5-9 .

Table 5-9 Data-Typing Attributes

See Chapter 9, "Accessing the Data_Typing Database" for more information.



Generated with CERN WebMaker