Debian Codegraph @

plugins/org.eclipse.emf.edit.ui/src/org/eclipse/emf/edit/ui/dnd/EditingDomainViewerDropAdapter.java

raw
1 /**
2 * Copyright (c) 2002-2012 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v2.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v20.html
7 *
8 * Contributors:
9 * IBM - Initial API and implementation
10 */
11 package org.eclipse.emf.edit.ui.dnd;
12
13
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.List;
18
19 import org.eclipse.jface.util.LocalSelectionTransfer;
20 import org.eclipse.jface.viewers.IStructuredSelection;
21 import org.eclipse.jface.viewers.Viewer;
22 import org.eclipse.swt.SWT;
23 import org.eclipse.swt.dnd.DND;
24 import org.eclipse.swt.dnd.DropTargetAdapter;
25 import org.eclipse.swt.dnd.DropTargetEvent;
26 import org.eclipse.swt.dnd.FileTransfer;
27 import org.eclipse.swt.dnd.TransferData;
28 import org.eclipse.swt.graphics.Point;
29 import org.eclipse.swt.graphics.Rectangle;
30 import org.eclipse.swt.widgets.Control;
31 import org.eclipse.swt.widgets.TableItem;
32 import org.eclipse.swt.widgets.TreeItem;
33 import org.eclipse.swt.widgets.Widget;
34
35 import org.eclipse.core.resources.IResource;
36 import org.eclipse.emf.common.CommonPlugin;
37 import org.eclipse.emf.common.command.Command;
38 import org.eclipse.emf.common.util.URI;
39 import org.eclipse.emf.edit.command.DragAndDropCommand;
40 import org.eclipse.emf.edit.command.DragAndDropFeedback;
41 import org.eclipse.emf.edit.domain.EditingDomain;
42
43
44 /**
45 * This implementation of a drop target listener is designed to turn a drag and drop
46 * operation into a {@link Command} based on the model objects of an
47 * {@link EditingDomain} and created by {@link DragAndDropCommand#create}. It is
48 * designed to do early data transfer so the the enablement and feedback of the
49 * drag and drop interaction can intimately depend on the state of the model objects
50 * involved. On some platforms, however, early data transfer is not available, so this
51 * feedback cannot be provided.
52 * <p>
53 * The base implementation of this class should be sufficient for most applications.
54 * Any change in behaviour is typically accomplished by overriding
55 * {@link org.eclipse.emf.edit.provider.ItemProviderAdapter}.createDragAndDropCommand
56 * to return a derived implementation of {@link DragAndDropCommand}.
57 * This is how one these adapters is typically hooked up:
58 * <pre>
59 * viewer.addDropSupport
60 * (DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK,
61 * new Transfer [] { LocalTransfer.getInstance() },
62 * EditingDomainViewerDropAdapter(viewer));
63 * </pre>
64 * <p>
65 * This implementation prefers to use a {@link LocalTransfer},
66 * which short-circuits the transfer process for simple transfers within the workbench;
67 * the method {@link #getDragSource} can be overridden to change the behaviour.
68 * The implementation also only handles an {@link IStructuredSelection},
69 * but the method {@link #extractDragSource} can be overridden to change the behaviour.
70 * In EMF 2.9, this class was enhanced to also handle {@link LocalSelectionTransfer} and {@link FileTransfer}.
71 * For the latter, the file names are converted to a list of {@link URI}s by {@link #extractDragSource}.
72 * <p>
73 * SWT's {@link DND#FEEDBACK_SCROLL auto-scroll} and {@link DND#FEEDBACK_EXPAND auto-expand}
74 * (hover) are enabled by default. The method {@link #getAutoFeedback} can be overridden
75 * to change this behaviour.
76 */
77 public class EditingDomainViewerDropAdapter extends DropTargetAdapter
78 {
79 /**
80 * This indicates whether the current platform is motif, which needs
81 * special treatment, since it cannot do early data transfer, but doesn't
82 * cleanly return null either.
83 */
84 protected final static boolean IS_MOTIF = "motif".equals(SWT.getPlatform());
85
86 /**
87 * This is the viewer for which this is a drop target listener.
88 */
89 protected Viewer viewer;
90
91 /**
92 * This is the domain in which drag and drop commands will be executed.
93 */
94 protected EditingDomain domain;
95
96 /**
97 * This is the collection of source objects being dragged.
98 */
99 protected Collection<?> source;
100
101 /**
102 * This is the command created during dragging which provides the feedback and will carry out the action upon completion.
103 */
104 protected Command command;
105
106 /**
107 * This records the object for which the {@link #command} was created.
108 */
109 protected Object commandTarget;
110
111 /**
112 * This keeps track of the original operation that the user requested, before
113 * we started changing the event.detail. We always try to create the command
114 * using this.
115 */
116 protected int originalOperation;
117
118 /**
119 * This keeps track of the information used to create {@link #command}, but
120 * does not need to be disposed. This allows us to dispose of the command
121 * in dragLeave, and then, if we need to execute it, recreate it in drop.
122 */
123 protected DragAndDropCommandInformation dragAndDropCommandInformation;
124
125 /**
126 * This creates an instance with the given domain and viewer.
127 */
128 public EditingDomainViewerDropAdapter(EditingDomain domain, Viewer viewer)
129 {
130 this.viewer = viewer;
131 this.domain = domain;
132 }
133
134 /**
135 * This is called when the mouse first enters or starts dragging in the viewer.
136 */
137 @Override
138 public void dragEnter(DropTargetEvent event)
139 {
140 // Remember the requested operation.
141 originalOperation = event.detail;
142
143 helper(event);
144 }
145
146 /**
147 * This is called when the mouse leaves or stops dragging in the viewer,
148 * whether the operation was aborted or is about to do a dropAccept and drop.
149 * The event argument is uninitialized, so it is impossible to distinguish
150 * between the two cases. So, we do the clean-up now and recreate the
151 * command later, if necessary.
152 */
153 @Override
154 public void dragLeave(DropTargetEvent event)
155 {
156 // Clean up the command if there is one. If we need it again in drop,
157 // we'll recreate it from dragAndDropCommandInformation.
158 //
159 if (command != null)
160 {
161 command.dispose();
162 command = null;
163 commandTarget = null;
164 }
165
166 // Clear the source data. We won't need this again, since, if it was
167 // available, it's already in the command.
168 //
169 source = null;
170 }
171
172 /**
173 * This is called when the operation has changed in some way, typically because the user changes keyboard modifiers.
174 */
175 @Override
176 public void dragOperationChanged(DropTargetEvent event)
177 {
178 // Remember the requested operation.
179 originalOperation = event.detail;
180
181 helper(event);
182 }
183
184 /**
185 * This is called repeatedly, as the mouse moves over the viewer.
186 */
187 @Override
188 public void dragOver(DropTargetEvent event)
189 {
190 helper(event);
191 }
192
193 /**
194 * This is called when the mouse is released over the viewer to initiate a
195 * drop, between dragLeave and drop.
196 */
197 @Override
198 public void dropAccept(DropTargetEvent event)
199 {
200 helper(event);
201 }
202
203 /**
204 * This is called to indicate that the drop action should be invoked.
205 */
206 @Override
207 public void drop(DropTargetEvent event)
208 {
209 // A command was created if the source was available early, and the
210 // information used to create it was cached...
211 //
212 if (dragAndDropCommandInformation != null)
213 {
214 // Recreate the command.
215 //
216 command = dragAndDropCommandInformation.createCommand();
217 }
218 else
219 {
220 // Otherwise, the source should be available now as event.data, and we
221 // can create the command.
222 //
223 source = extractDragSource(event.data);
224 Object target = extractDropTarget(event.item);
225 command = DragAndDropCommand.create(domain, target, getLocation(event), event.operations, originalOperation, source);
226 }
227
228 // If the command can execute...
229 //
230 if (command.canExecute())
231 {
232 // Execute it.
233 //
234 domain.getCommandStack().execute(command);
235 }
236 else
237 {
238 // Otherwise, let's call the whole thing off.
239 //
240 event.detail = DND.DROP_NONE;
241 command.dispose();
242 }
243
244 // Clean up the state.
245 //
246 command = null;
247 commandTarget = null;
248 source = null;
249 dragAndDropCommandInformation = null;
250 }
251
252 /**
253 * This method is called the same way for each of the
254 * {@link org.eclipse.swt.dnd.DropTargetListener} methods, except for leave
255 * and drop. If the source is available early, it creates or revalidates
256 * the {@link DragAndDropCommand}, and updates the event's detail (operation)
257 * and feedback (drag under effect), appropriately.
258 */
259 protected void helper(DropTargetEvent event)
260 {
261 // If we can't do anything else, we'll provide the default select feedback
262 // and enable auto-scroll and auto-expand effects.
263 event.feedback = DND.FEEDBACK_SELECT | getAutoFeedback();
264
265 // If we don't already have it, try to get the source early. We can't give
266 // feedback if it's not available yet (this is platform-dependent).
267 //
268 if (source == null)
269 {
270 source = getDragSource(event);
271 if (source == null)
272 {
273 // Clear out any old information from a previous drag.
274 //
275 dragAndDropCommandInformation = null;
276 return;
277 }
278 }
279
280 // Get the target object from the item widget and the mouse location in it.
281 //
282 Object target = extractDropTarget(event.item);
283 float location = getLocation(event);
284
285 // Determine if we can create a valid command at the current location.
286 //
287 boolean valid = false;
288
289 // If we don't have a previous cached command...
290 //
291 if (command == null)
292 {
293 // We'll need to keep track of the information we use to create the
294 // command, so that we can recreate it in drop.
295 dragAndDropCommandInformation = new DragAndDropCommandInformation(domain, target, location, event.operations, originalOperation, source);
296
297 // Remember the target; create the command and test if it is executable.
298 //
299 commandTarget = target;
300 command = dragAndDropCommandInformation.createCommand();
301 valid = command.canExecute();
302 }
303 else
304 {
305 // Check if the cached command can provide DND feedback/revalidation.
306 //
307 if (target == commandTarget && command instanceof DragAndDropFeedback)
308 {
309 // If so, revalidate the command.
310 //
311 valid = ((DragAndDropFeedback)command).validate(target, location, event.operations, originalOperation, source);
312
313 // Keep track of any changes to the command information.
314 dragAndDropCommandInformation = new DragAndDropCommandInformation(domain, target, location, event.operations, originalOperation, source);
315 }
316 else
317 {
318 // If not, dispose the current command and create a new one.
319 //
320 dragAndDropCommandInformation = new DragAndDropCommandInformation(domain, target, location, event.operations, originalOperation, source);
321 commandTarget = target;
322 command.dispose();
323 command = dragAndDropCommandInformation.createCommand();
324 valid = command.canExecute();
325 }
326 }
327
328 // If this command can provide detailed drag and drop feedback...
329 //
330 if (command instanceof DragAndDropFeedback)
331 {
332 // Use it for the operation and drag under effect.
333 //
334 DragAndDropFeedback dragAndDropFeedback = (DragAndDropFeedback)command;
335 event.detail = dragAndDropFeedback.getOperation();
336 event.feedback = dragAndDropFeedback.getFeedback() | getAutoFeedback();
337 }
338 else if (!valid)
339 {
340 // There is no executable command, so we'd better nix the whole deal.
341 //
342 event.detail = DND.DROP_NONE;
343 }
344 }
345
346 /**
347 * This returns the bitwise OR'ed flags for desired auto-feedback effects.
348 * Drag under effect DND constants are always OR'ed with this to enable them.
349 * This implementation enables {@link DND#FEEDBACK_SCROLL auto-scroll} and
350 * {@link DND#FEEDBACK_EXPAND auto-expand} (hover).
351 */
352 protected int getAutoFeedback()
353 {
354 return DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND;
355 }
356
357 /**
358 * This attempts to extract the drag source from the event early, i.e.,
359 * before the drop method. This implementation tries to use a
360 * {@link org.eclipse.emf.edit.ui.dnd.LocalTransfer}. If the data is not yet
361 * available (e.g. on platforms other than win32), it just returns null.
362 */
363 protected Collection<?> getDragSource(DropTargetEvent event)
364 {
365 // Check whether the current data type can be transfered locally.
366 //
367 LocalTransfer localTransfer = LocalTransfer.getInstance();
368 if (localTransfer.isSupportedType(event.currentDataType))
369 {
370 // Motif kludge: we would get something random instead of null.
371 //
372 if (IS_MOTIF) return null;
373
374 // Transfer the data and, if non-null, extract it.
375 //
376 Object object = localTransfer.nativeToJava(event.currentDataType);
377 return object == null ? null : extractDragSource(object);
378 }
379 else
380 {
381 LocalSelectionTransfer localSelectionTransfer = LocalSelectionTransfer.getTransfer();
382 if (localSelectionTransfer.isSupportedType(event.currentDataType))
383 {
384 // Motif kludge: we would get something random instead of null.
385 //
386 if (IS_MOTIF) return null;
387
388 // Transfer the data and, if non-null, extract it.
389 //
390 Object object = localSelectionTransfer.nativeToJava(event.currentDataType);
391 return object == null ? null : extractDragSource(object);
392 }
393
394 FileTransfer fileTransfer = FileTransfer.getInstance();
395 if (fileTransfer.isSupportedType(event.currentDataType))
396 {
397 // Motif kludge: we would get something random instead of null.
398 //
399 if (IS_MOTIF) return null;
400
401 // Transfer the data and, if non-null, extract it.
402 //
403 Object object = fileTransfer.nativeToJava(event.currentDataType);
404 return object == null ? null : extractDragSource(object);
405 }
406 else
407 {
408 // Iterate over the data types to see if there is a data type that supports a local transfer.
409 //
410 TransferData [] dataTypes = event.dataTypes;
411 for (int i = 0; i < dataTypes.length; ++i)
412 {
413 TransferData transferData = dataTypes[i];
414
415 // If the local transfer supports this data type, switch to that data type
416 //
417 if (localTransfer.isSupportedType(transferData))
418 {
419 event.currentDataType = transferData;
420 return null;
421 }
422 }
423
424 // Iterate over the data types to see if there is a data type that supports a local selection transfer.
425 //
426 for (int i = 0; i < dataTypes.length; ++i)
427 {
428 TransferData transferData = dataTypes[i];
429
430 // If the local selection transfer supports this data type, switch to that data type
431 //
432 if (localSelectionTransfer.isSupportedType(transferData))
433 {
434 event.currentDataType = transferData;
435 return null;
436 }
437 }
438
439 // Iterate over the data types to see if there is a data type that supports a file transfer.
440 //
441 for (int i = 0; i < dataTypes.length; ++i)
442 {
443 TransferData transferData = dataTypes[i];
444
445 // If the file transfer supports this data type, switch to that data type
446 //
447 if (fileTransfer.isSupportedType(transferData))
448 {
449 event.currentDataType = transferData;
450 return null;
451 }
452 }
453 return null;
454 }
455 }
456 }
457
458 /**
459 * This extracts a collection of dragged source objects from the given object retrieved from the transfer agent.
460 * This default implementation converts a {@link IStructuredSelection structured selection} into a collection of elements.
461 * As of EMF 2.9,
462 * an array of strings is converted to a collection of {@link URI#createFileURI(String) file URI}s
463 * and each {@link IResource} in a selection is {@link URI#createPlatformResourceURI(String, boolean) converted to a URI}.
464 */
465 protected Collection<?> extractDragSource(Object object)
466 {
467 // Transfer the data and convert the structured selection to a collection of objects.
468 //
469 if (object instanceof IStructuredSelection)
470 {
471 List<?> list = ((IStructuredSelection)object).toList();
472 if (CommonPlugin.IS_RESOURCES_BUNDLE_AVAILABLE)
473 {
474 list = ResourcesHelper.resourceToURI(list);
475 }
476 return list;
477 }
478 else if (object instanceof String[])
479 {
480 List<URI> result = new ArrayList<URI>();
481 for (String file : ((String[])object))
482 {
483 result.add(URI.createFileURI(file));
484 }
485 return result;
486 }
487 else
488 {
489 return Collections.EMPTY_LIST;
490 }
491 }
492
493 /**
494 * This extracts an object from the given item widget.
495 */
496 protected Object extractDropTarget(Widget item)
497 {
498 if (item == null) return null;
499 return item.getData();
500 }
501
502
503 /**
504 * This returns the location of the mouse in the vertical direction, relative
505 * to the item widget, from 0 (top) to 1 (bottom).
506 */
507 protected float getLocation(DropTargetEvent event)
508 {
509 if (event.item instanceof TreeItem)
510 {
511 TreeItem treeItem = (TreeItem)event.item;
512 Control control = treeItem.getParent();
513 Point point = control.toControl(new Point(event.x, event.y));
514 Rectangle bounds = treeItem.getBounds();
515 return (float)(point.y - bounds.y) / (float)bounds.height;
516 }
517 else if (event.item instanceof TableItem)
518 {
519 TableItem tableItem = (TableItem)event.item;
520 Control control = tableItem.getParent();
521 Point point = control.toControl(new Point(event.x, event.y));
522 Rectangle bounds = tableItem.getBounds(0);
523 return (float)(point.y - bounds.y) / (float)bounds.height;
524 }
525 else
526 {
527 return 0.0F;
528 }
529 }
530
531 /**
532 * This holds all of the information used to create a
533 * {@link DragAndDropCommand}, but does not need to be disposed.
534 */
535 protected static class DragAndDropCommandInformation
536 {
537 protected EditingDomain domain;
538 protected Object target;
539 protected float location;
540 protected int operations;
541 protected int operation;
542 protected Collection<?> source;
543 public DragAndDropCommandInformation
544 (EditingDomain domain, Object target, float location, int operations, int operation, Collection<?> source)
545 {
546 this.domain = domain;
547 this.target = target;
548 this.location = location;
549 this.operations = operations;
550 this.operation = operation;
551 this.source = new ArrayList<Object>(source);
552 }
553
554 public Command createCommand()
555 {
556 return DragAndDropCommand.create(domain, target, location, operations, operation, source);
557 }
558 }
559 }
560
561 /**
562 * A utility class for converting IResource to their corresponding URI.
563 *
564 */
565 class ResourcesHelper
566 {
567 public static List<?> resourceToURI(List<?> dragSource)
568 {
569 List<Object> result = new ArrayList<Object>();
570 for (Object object : dragSource)
571 {
572 if (object instanceof IResource)
573 {
574 result.add(URI.createPlatformResourceURI(((IResource)object).getFullPath().toString(), true));
575 }
576 else
577 {
578 result.add(object);
579 }
580 }
581 return result;
582 }
583 }