示例#1
0
 protected Object getSelection() {
   IStructuredSelection selection = (IStructuredSelection) transfer.getSelection();
   if (selection != null) {
     return selection.getFirstElement();
   }
   return null;
 }
示例#2
0
  private void installTitleDrag(Form form) {
    if (titleDragSourceListener == null /*&& !hasLeftToolBar()*/) {
      Transfer[] transferTypes;
      if (null == task) {
        transferTypes = new Transfer[] {TextTransfer.getInstance()};
      } else {
        transferTypes =
            new Transfer[] {
              LocalSelectionTransfer.getTransfer(),
              TextTransfer.getInstance(),
              FileTransfer.getInstance()
            };
      }
      titleDragSourceListener =
          new TaskDragSourceListener(
              new SelectionProviderAdapter() {
                @Override
                public ISelection getSelection() {
                  return new StructuredSelection(task);
                }
              });

      if (titleLabel != null) {
        DragSource source = new DragSource(titleLabel, DND.DROP_MOVE | DND.DROP_LINK);
        source.setTransfer(transferTypes);
        source.addDragListener(titleDragSourceListener);
      } else {
        form.addTitleDragSupport(
            DND.DROP_MOVE | DND.DROP_LINK, transferTypes, titleDragSourceListener);
      }
    }
  }
  /* (non-Javadoc)
   * @see org.eclipse.jface.viewers.ViewerDropAdapter#dragEnter(org.eclipse.swt.dnd.DropTargetEvent)
   */
  public void dragEnter(DropTargetEvent event) {
    fDropType = DROP_TYPE_DEFAULT;
    event.detail = DND.DROP_NONE;

    for (int i = 0; i < event.dataTypes.length; i++) {
      if (LocalSelectionTransfer.getTransfer().isSupportedType(event.dataTypes[i])) {
        if (isExpressionDrop()) {
          event.currentDataType = event.dataTypes[i];
          event.detail = DND.DROP_MOVE;
          fDropType = DROP_TYPE_EXPRESSION;
          break;
        } else if (isVariableDrop()) {
          event.currentDataType = event.dataTypes[i];
          event.detail = DND.DROP_COPY;
          fDropType = DROP_TYPE_VARIABLE;
          break;
        } else if (isWatchAdaptableElementDrop()) {
          event.currentDataType = event.dataTypes[i];
          event.detail = DND.DROP_COPY;
          fDropType = DROP_TYPE_WATCH_ADAPTABLE_ELEMENT;
          break;
        }
      } else if (TextTransfer.getInstance().isSupportedType(event.dataTypes[i])) {
        event.currentDataType = event.dataTypes[i];
        event.detail = DND.DROP_COPY;
        fDropType = DROP_TYPE_DEFAULT;
        break;
      }
    }

    super.dragEnter(event);
  }
  /**
   * Validates if the drop is valid by validating the local selection transfer to ensure that a
   * watch expression can be created for each contained IVariable.
   *
   * @param target target of the drop
   * @return whether the drop is valid
   */
  private boolean validateVariableDrop(Object target) {
    // Target must be null or an IExpression, you cannot add a new watch expression inside another
    if (target != null && getTargetExpression(target) == null) {
      return false;
    }

    IStructuredSelection selection =
        (IStructuredSelection) LocalSelectionTransfer.getTransfer().getSelection();
    int enabled = 0;
    int size = -1;
    if (selection != null) {
      size = selection.size();
      IExpressionManager manager = DebugPlugin.getDefault().getExpressionManager();
      Iterator iterator = selection.iterator();
      while (iterator.hasNext()) {
        Object element = iterator.next();
        if (element instanceof IVariable) {
          IVariable variable = (IVariable) element;
          if (variable instanceof IndexedVariablePartition) {
            break;
          } else if (manager.hasWatchExpressionDelegate(variable.getModelIdentifier())
              && isFactoryEnabled(variable)) {
            enabled++;
          } else {
            break;
          }
        }
      }
    }
    return enabled == size;
  }
 /* (non-Javadoc)
  * @see org.eclipse.jface.viewers.ViewerDropAdapter#performDrop(java.lang.Object)
  */
 public boolean performDrop(Object data) {
   if (LocalSelectionTransfer.getTransfer().isSupportedType(fCurrentTransferType)) {
     IStructuredSelection selection =
         (IStructuredSelection) LocalSelectionTransfer.getTransfer().getSelection();
     if (fDropType == DROP_TYPE_EXPRESSION) {
       return performExpressionDrop(selection);
     } else if (fDropType == DROP_TYPE_VARIABLE
         || fDropType == DROP_TYPE_WATCH_ADAPTABLE_ELEMENT) {
       return performVariableOrWatchAdaptableDrop(selection);
     }
   } else if (TextTransfer.getInstance().isSupportedType(fCurrentTransferType)) {
     if (data != null) {
       return performTextDrop((String) data);
     }
   }
   return false;
 }
 @Override
 public Transfer[] getSupportedTransferTypes() {
   return new Transfer[] {
     TextTransfer.getInstance(),
     FileTransfer.getInstance(),
     ResourceTransfer.getInstance(),
     EditorInputTransfer.getInstance(),
     LocalSelectionTransfer.getTransfer()
   };
 }
  @Override
  public boolean validateDrop(Object target, int operation, TransferData type) {
    overrideOperation(DND.DROP_COPY);
    //		if (application == null)
    //			return false;

    if (operation == DND.DROP_COPY || operation == DND.DROP_DEFAULT) {
      if (LocalSelectionTransfer.getTransfer().isSupportedType(type)) {
        IStructuredSelection selection =
            (IStructuredSelection) LocalSelectionTransfer.getTransfer().getSelection();
        Object[] objects = selection.toArray();
        for (Object obj : objects) {
          if (obj instanceof CloudService) {
            return true;
          }
        }
      }
    }
    return false;
  }
  @Override
  public IStatus handleDrop(
      CommonDropAdapter aDropAdapter, DropTargetEvent aDropTargetEvent, Object aTarget) {
    TreeSelection selection = (TreeSelection) LocalSelectionTransfer.getTransfer().getSelection();
    String operation = getOperationType(selection);

    if (STAGE_OP.equals(operation)) runCommand(ADD_TO_INDEX, selection);
    else if (UNSTAGE_OP.equals(operation)) runCommand(REMOVE_FROM_INDEX, selection);

    return Status.OK_STATUS;
  }
 /*
  * (non-Javadoc)
  *
  * @see org.eclipse.gmf.runtime.diagram.ui.parts.DiagramDropTargetListener#getObjectsBeingDropped()
  */
 @Override
 protected List getObjectsBeingDropped() {
   TransferData[] data = getCurrentEvent().dataTypes;
   List eObjects = new ArrayList();
   ISelection selection = LocalSelectionTransfer.getTransfer().getSelection();
   if (selection instanceof IStructuredSelection) {
     IStructuredSelection structuredSelection = (IStructuredSelection) selection;
     eObjects.addAll(structuredSelection.toList());
   }
   return eObjects;
 }
 /** @return whether the selection transfer contains only IVariables */
 private boolean isVariableDrop() {
   IStructuredSelection selection =
       (IStructuredSelection) LocalSelectionTransfer.getTransfer().getSelection();
   Iterator iterator = selection.iterator();
   while (iterator.hasNext()) {
     Object element = iterator.next();
     if (!(element instanceof IVariable)) {
       return false;
     }
   }
   return true;
 }
 /** @return whether the selection transfer contains only IExpressions */
 private boolean isExpressionDrop() {
   IStructuredSelection selection =
       (IStructuredSelection) LocalSelectionTransfer.getTransfer().getSelection();
   Iterator iterator = selection.iterator();
   while (iterator.hasNext()) {
     Object element = iterator.next();
     if (getTargetExpression(element) == null) {
       return false;
     }
   }
   return true;
 }
 /**
  * @return whether the selection transfer contains only objects adaptable to
  *     IWatchExpressionFactoryAdapter2
  */
 private boolean isWatchAdaptableElementDrop() {
   IStructuredSelection selection =
       (IStructuredSelection) LocalSelectionTransfer.getTransfer().getSelection();
   Iterator iterator = selection.iterator();
   while (iterator.hasNext()) {
     Object element = iterator.next();
     if (!(element instanceof IAdaptable
         && ((IAdaptable) element).getAdapter(IWatchExpressionFactoryAdapter2.class) != null)) {
       return false;
     }
   }
   return true;
 }
 /* (non-Javadoc)
  * @see org.eclipse.jface.viewers.ViewerDropAdapter#validateDrop(java.lang.Object, int, org.eclipse.swt.dnd.TransferData)
  */
 public boolean validateDrop(Object target, int operation, TransferData transferType) {
   if (LocalSelectionTransfer.getTransfer().isSupportedType(transferType)) {
     if (fDropType == DROP_TYPE_EXPRESSION) {
       return validateExpressionDrop(target);
     } else if (fDropType == DROP_TYPE_VARIABLE) {
       return validateVariableDrop(target);
     } else if (fDropType == DROP_TYPE_WATCH_ADAPTABLE_ELEMENT) {
       return validateWatchAdaptableDrop(target);
     }
   } else if (TextTransfer.getInstance().isSupportedType(transferType)) {
     return validateTextDrop(target);
   }
   return false;
 }
示例#14
0
  @Override
  public IStatus handleDrop(
      final CommonDropAdapter dropAdapter,
      final DropTargetEvent dropTargetEvent,
      final Object target) {

    // get the source data
    final TransferData td = dropAdapter.getCurrentTransfer();
    final ISelection sel = (ISelection) LocalSelectionTransfer.getTransfer().nativeToJava(td);
    final TreeSelection s = (TreeSelection) sel;
    try {
      GlobalParameters.setSelection(s);
    } catch (final WranglerException e1) {
      e1.printStackTrace();
    }

    // get the target data
    String moduleName;
    IFile file;
    if (target instanceof IFile) {
      file = (IFile) target;
    } else {
      file = (IFile) ((IErlElement) target).getResource();
    }
    moduleName = file.getName();

    moduleName = moduleName.substring(0, moduleName.lastIndexOf("."));

    final MoveFunctionRefactoring refactoring = new MoveFunctionRefactoring();
    refactoring.setUserInput(moduleName);
    final RefactoringWizard wizard =
        new DefaultWranglerRefactoringWizard(
            refactoring,
            RefactoringWizard.DIALOG_BASED_USER_INTERFACE,
            new ArrayList<WranglerPage>());

    final Shell shell = PlatformUI.getWorkbench().getDisplay().getActiveShell();

    final RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);

    try {
      op.run(shell, refactoring.getName());
    } catch (final Exception e) {
      e.printStackTrace();
    }

    System.out.print("hand");

    return Status.OK_STATUS;
  }
  @Override
  public IStatus validateDrop(Object target, int operationCode, TransferData transferType) {
    TreeSelection selection = (TreeSelection) LocalSelectionTransfer.getTransfer().getSelection();

    String operation = getOperationType(selection);

    if (!UNSUPPORTED_OP.equals(operation)) {
      if (target instanceof GitModelWorkingTree) {
        if (UNSTAGE_OP.equals(operation)) return Status.OK_STATUS;
      } else if (STAGE_OP.equals(operation) && target instanceof GitModelCache)
        return Status.OK_STATUS;
    }

    return Status.CANCEL_STATUS;
  }
  @Override
  public IStatus validateDrop(Object target, int operation, TransferData transferType) {
    IStatus status = Status.CANCEL_STATUS;
    if (DND.DROP_MOVE == operation
        && target instanceof EObject
        && UMLPackage.eINSTANCE == ((EObject) target).eClass().getEPackage()) {
      Collection<EObject> extractDragSource =
          extractDragSource(LocalSelectionTransfer.getTransfer().getSelection());
      if (!extractDragSource.isEmpty()) {
        status = Status.OK_STATUS;
      }
    }

    return status;
  }
示例#17
0
 /**
  * Translate the transfer type from this element.
  *
  * @param name The attribute name.
  * @return The transfer instance.
  */
 private Transfer parseTransferType(String name) {
   if ("TextTransfer".equals(name)) { // $NON-NLS-1$
     return TextTransfer.getInstance();
   }
   if ("ImageTransfer".equals(name)) { // $NON-NLS-1$
     return ImageTransfer.getInstance();
   }
   if ("FileTransfer".equals(name)) { // $NON-NLS-1$
     return FileTransfer.getInstance();
   }
   if ("LocalSelectionTransfer".equals(name)) { // $NON-NLS-1$
     return LocalSelectionTransfer.getTransfer();
   }
   return null;
 }
示例#18
0
  @Override
  public IStatus validateDrop(
      final Object target, final int operation, final TransferData transferType) {
    final ISelection sel =
        (ISelection) LocalSelectionTransfer.getTransfer().nativeToJava(transferType);
    final TreeSelection s = (TreeSelection) sel;
    final IErlElement e = (IErlElement) s.getFirstElement();

    if (e instanceof IErlFunctionClause) {
      if (target instanceof IErlElement || target instanceof IFile) {
        return Status.OK_STATUS;
      }
    }
    return Status.CANCEL_STATUS;
  }
  /**
   * get the list of commands to drop an element
   *
   * @param target, can be null but do nothing
   * @param the role where there is a drop ( can be null)
   * @return the list of the commands
   */
  protected List<Command> getDropIntoCommand(final Object target, EReference eref) {

    // init
    ArrayList<Command> result = new ArrayList<Command>();
    EObject targetEObject = null;

    // target is an EObject?
    if (target instanceof EObject) {
      targetEObject = ((EObject) target);
    }
    if (target instanceof IAdaptable) {
      targetEObject = ((EObject) ((IAdaptable) target).getAdapter(EObject.class));
    }
    if (targetEObject == null) {
      return result;
    }

    // get Command from the selection
    ISelection selection = LocalSelectionTransfer.getTransfer().getSelection();
    if (selection instanceof IStructuredSelection) {
      List<?> selectedElements = ((IStructuredSelection) selection).toList();
      Iterator<?> it = selectedElements.iterator();
      while (it.hasNext()) {
        Object object = it.next();
        EObject eObjectchild = null;
        if (object instanceof IAdaptable) {
          eObjectchild = (EObject) ((IAdaptable) object).getAdapter(EObject.class);
        } else if (object instanceof EObject) {
          eObjectchild = (EObject) object;
        }

        if (eObjectchild instanceof Diagram) {
          // Do not allow diagram drag and drop, it is not supported yet.
          // result.addAll(getDropDiagramIntoCommand(getEditingDomain(), targetEObject,(Diagram)
          // eObjectchild));
        }
        // test if object is an eobject
        else if (eObjectchild != null) {

          result.addAll(getDropIntoCommand(getEditingDomain(), targetEObject, eObjectchild, eref));
        }
      }
    }

    return result;
  }
  private void addDragSupport(final TreeViewer viewer) {
    int ops = DND.DROP_COPY;

    final Transfer[] transfers = new Transfer[] {LocalSelectionTransfer.getTransfer()};

    DragSourceAdapter listener =
        new DragSourceAdapter() {

          //			@Override
          //			public void dragSetData(DragSourceEvent event) {
          //				IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
          //				event.data = selection.getFirstElement();
          //				LocalSelectionTransfer.getTransfer().setSelection(selection);
          //			}
          //
          //			@Override
          //			public void dragStart(DragSourceEvent event) {
          //				if (event.detail == DND.DROP_NONE || event.detail == DND.DROP_DEFAULT) {
          //					event.detail = DND.DROP_COPY;
          //				}
          //				dragSetData(event);
          //			}

          @Override
          public void dragSetData(DragSourceEvent event) {
            Set<BootDashElement> selection = getSelection().getValue();
            BootDashElement[] elements = selection.toArray(new BootDashElement[selection.size()]);
            LocalSelectionTransfer.getTransfer().setSelection(new StructuredSelection(elements));
            event.detail = DND.DROP_COPY;
          }

          @Override
          public void dragStart(DragSourceEvent event) {
            if (!canDeploySelection(getSelection().getValue())) {
              event.doit = false;
            } else {
              dragSetData(event);
            }
          }
        };
    viewer.addDragSupport(ops, transfers, listener);
  }
  private void createContextMenuFor(TreeViewer viewer) {
    MenuManager contextMenu = new MenuManager("#PopUp");
    contextMenu.add(new Separator("additions"));
    contextMenu.setRemoveAllWhenShown(true);
    contextMenu.addMenuListener(this);
    Menu menu = contextMenu.createContextMenu(viewer.getControl());
    viewer.getControl().setMenu(menu);
    getSite().registerContextMenu(contextMenu, new UnwrappingSelectionProvider(viewer));

    int dndOperations = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
    Transfer[] transfers =
        new Transfer[] {
          LocalTransfer.getInstance(),
          LocalSelectionTransfer.getTransfer(),
          FileTransfer.getInstance()
        };
    viewer.addDragSupport(dndOperations, transfers, new ViewerDragAdapter(viewer));
    viewer.addDropSupport(
        dndOperations, transfers, new EditingDomainViewerDropAdapter(editingDomain, viewer));
  }
示例#22
0
  /** @generated */
  @Override
  protected void initializeGraphicalViewer() {
    super.initializeGraphicalViewer();

    // Enable Drop
    getDiagramGraphicalViewer()
        .addDropTargetListener(
            new DropTargetListener(
                getDiagramGraphicalViewer(), LocalSelectionTransfer.getTransfer()) {

              @Override
              protected Object getJavaObject(TransferData data) {
                return LocalSelectionTransfer.getTransfer().nativeToJava(data);
              }

              @Override
              protected TransactionalEditingDomain getTransactionalEditingDomain() {
                return getEditingDomain();
              }
            });
  }
  /** @generated */
  protected void initializeGraphicalViewer() {
    super.initializeGraphicalViewer();
    getDiagramGraphicalViewer()
        .addDropTargetListener(
            new DropTargetListener(
                getDiagramGraphicalViewer(), LocalSelectionTransfer.getTransfer()) {

              protected Object getJavaObject(TransferData data) {
                System.out.println("Drop: " + data);
                return LocalSelectionTransfer.getTransfer().nativeToJava(data);
              }
            });
    getDiagramGraphicalViewer()
        .addDropTargetListener(
            new DropTargetListener(getDiagramGraphicalViewer(), LocalTransfer.getInstance()) {

              protected Object getJavaObject(TransferData data) {
                System.out.println("Drop: " + data);
                return LocalTransfer.getInstance().nativeToJava(data);
              }
            });
  }
  /**
   * get the list of commands to drop an element
   *
   * @param target, can be null but do nothing
   * @return the list of the commands
   */
  protected List<Command> getOrderChangeCommand(final Object target, boolean before) {

    // init
    ArrayList<Command> result = new ArrayList<Command>();
    EObject objectLocation = null;
    EObject objectOwner = null;

    // target is an EObject?
    if (target instanceof IAdaptable) {
      objectLocation = ((EObject) ((IAdaptable) target).getAdapter(EObject.class));
      objectOwner = objectLocation.eContainer();
    }
    if (objectLocation == null) {
      return result;
    }

    // get Command from the selection
    ISelection selection = LocalSelectionTransfer.getTransfer().getSelection();
    if (selection instanceof IStructuredSelection) {
      List<?> selectedElements = ((IStructuredSelection) selection).toList();
      Iterator<?> it = selectedElements.iterator();
      while (it.hasNext()) {
        Object object = it.next();
        if (object instanceof IAdaptable) {
          EObject eObjectchild = (EObject) ((IAdaptable) object).getAdapter(EObject.class);
          // test if object is an eobject
          if (eObjectchild != null && objectOwner != null) {

            result.addAll(
                getOrderChangeCommand(
                    getEditingDomain(), objectOwner, objectLocation, eObjectchild, before));
          }
        }
      }
    }
    return result;
  }
  /**
   * Validates if the drop is valid by validating the local selection transfer to ensure that a
   * watch expression can be created for each contained element.
   *
   * @param target target of the drop
   * @return whether the drop is valid
   */
  private boolean validateWatchAdaptableDrop(Object target) {
    // Target must be null or an IExpression, you cannot add a new watch expression inside another
    if (target != null && getTargetExpression(target) == null) {
      return false;
    }

    IStructuredSelection selection =
        (IStructuredSelection) LocalSelectionTransfer.getTransfer().getSelection();
    int enabled = 0;
    int size = -1;
    if (selection != null) {
      size = selection.size();
      Iterator iterator = selection.iterator();
      while (iterator.hasNext()) {
        Object element = iterator.next();
        if (isFactory2Enabled(element)) {
          enabled++;
        } else {
          break;
        }
      }
    }
    return enabled == size;
  }
示例#26
0
/** @author jliu [email protected] */
public abstract class DnDAdapterImpl implements DnDAdapter {

  static final int CARET_WIDTH = 2;
  private int dropCaretOffset = -1;
  private XWTEditor editor;
  private LocalSelectionTransfer transfer = LocalSelectionTransfer.getTransfer();

  /** */
  public DnDAdapterImpl(XWTEditor editor) {
    this.setEditor(editor);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.e4.xwt.ui.editor.dnd.DnDAdapter#drop(org.eclipse.swt.dnd.DropTargetEvent)
   */
  public void drop(DropTargetEvent event) {
    Object selection = getSelection();
    if (!isAccept()) {
      return;
    }

    Template template = createTemplate(selection);
    if (template == null) {
      return;
    }
    drop(template, getDropCaretOffset(), 0);
  }

  /** @param template */
  protected void drop(Template template, int dropCaretOffset, int length) {
    IDocument document = editor.getTextEditor().getTextViewer().getDocument();
    ContextTypeRegistry registry = XMLUIPlugin.getDefault().getTemplateContextRegistry();
    if (registry != null) {
      TemplateContextType type = registry.getContextType(template.getContextTypeId());

      DocumentTemplateContext templateContext =
          new DocumentTemplateContext(type, document, new Position(dropCaretOffset, length));
      if (templateContext.canEvaluate(template)) {
        try {
          TemplateBuffer templateBuffer = templateContext.evaluate(template);
          String templateString = templateBuffer.getString();
          document.replace(dropCaretOffset, length, templateString);

          StyledText styledText = editor.getTextWidget();
          int position = getCursorOffset(templateBuffer) + dropCaretOffset;
          styledText.setCaretOffset(position);
          styledText.setFocus();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    }
  }

  /**
   * @param selection TODO
   * @return
   */
  protected abstract Template createTemplate(Object selection);

  private int getCursorOffset(TemplateBuffer buffer) {
    TemplateVariable[] variables = buffer.getVariables();
    for (int i = 0; i != variables.length; i++) {
      TemplateVariable variable = variables[i];
      if (variable.getType().equals(GlobalTemplateVariables.Cursor.NAME))
        return variable.getOffsets()[0];
    }

    return buffer.getString().length();
  }

  public void dragOver(DropTargetEvent event) {
    if (!isAccept()) {
      return;
    }
    VEXContext context = editor.getContext();

    Node node = getCurrentNode(event);
    int position = context.findDropPosition(node, getScope(), getContextType(), getCursor(event));
    if (position < 0) {
      event.detail = DND.DROP_NONE;
    } else {
      StyledText styledText = editor.getTextWidget();
      setDropCaretOffset(position);
      refreshCaret(styledText, getDropCaretOffset());
    }
  }

  protected Node getCurrentNode(DropTargetEvent event) {
    StructuredTextViewer textViewer = editor.getTextEditor().getTextViewer();
    return VEXTextEditorHelper.getNode(textViewer, getCursor(event));
  }

  protected int getCursor(DropTargetEvent event) {
    StructuredTextViewer textViewer = editor.getTextEditor().getTextViewer();
    return VEXTextEditorHelper.getOffsetAtPoint(textViewer, new Point(event.x, event.y));
  }

  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.swt.dnd.DropTargetListener#dragEnter(org.eclipse.swt.dnd.DropTargetEvent)
   */
  public void dragEnter(DropTargetEvent event) {}

  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.swt.dnd.DropTargetListener#dragLeave(org.eclipse.swt.dnd.DropTargetEvent)
   */
  public void dragLeave(DropTargetEvent event) {
    StyledText styledText = editor.getTextWidget();
    if (getDropCaretOffset() != -1) {
      refreshCaret(styledText, getDropCaretOffset());
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.swt.dnd.DropTargetListener#dragOperationChanged(org.eclipse.swt.dnd.DropTargetEvent)
   */
  public void dragOperationChanged(DropTargetEvent event) {}

  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.swt.dnd.DropTargetListener#dropAccept(org.eclipse.swt.dnd.DropTargetEvent)
   */
  public void dropAccept(DropTargetEvent event) {}

  protected void refreshCaret(StyledText text, int newOffset) {
    if (newOffset != -1) {
      Point newPos = text.getLocationAtOffset(newOffset);
      int newHeight = text.getLineHeight(newOffset);
      text.redraw(newPos.x, newPos.y, CARET_WIDTH, newHeight, false);
    }
  }

  /** @param editor the editor to set */
  public void setEditor(XWTEditor editor) {
    this.editor = editor;
  }

  /** @return the editor */
  public XWTEditor getEditor() {
    return editor;
  }

  protected Object getSelection() {
    IStructuredSelection selection = (IStructuredSelection) transfer.getSelection();
    if (selection != null) {
      return selection.getFirstElement();
    }
    return null;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.e4.xwt.ui.editor.dnd.DnDAdapter#isAccept()
   */
  public boolean isAccept() {
    Object selection = getSelection();
    if (selection == null) {
      return false;
    }
    return isAccept(selection);
  }

  /**
   * @param selection
   * @return
   */
  protected abstract boolean isAccept(Object selection);

  /** @param dropCaretOffset the dropCaretOffset to set */
  public void setDropCaretOffset(int dropCaretOffset) {
    this.dropCaretOffset = dropCaretOffset;
  }

  /** @return the dropCaretOffset */
  public int getDropCaretOffset() {
    return dropCaretOffset;
  }
}
示例#27
0
  public void createPartControl(Composite parent) {
    listener =
        new WorkbenchWindowListener(
            new WorkbenchPageListener(
                new PartListener(new DropTemplateWorkflowModelEditorAction())));
    listener.register();

    FillLayout parentLayout = new FillLayout();
    parent.setLayout(parentLayout);
    SashForm sashForm = new SashForm(parent, SWT.HORIZONTAL);

    Tree tree = new Tree(sashForm, SWT.BORDER);
    tree.setLinesVisible(false);
    tree.setLayoutData(FormBuilder.createDefaultMultiLineWidgetGridData());
    Composite composite = FormBuilder.createComposite(sashForm, 1);
    Composite swingComposite = new Composite(composite, SWT.EMBEDDED);
    swingComposite.setLayoutData(FormBuilder.createDefaultMultiLineWidgetGridData());
    java.awt.Frame locationFrame = SWT_AWT.new_Frame(swingComposite);
    textPane = new JTextPane();
    JScrollPane scrollPane = new JScrollPane(textPane);
    locationFrame.add(scrollPane);
    textPane.setContentType("text/html"); // $NON-NLS-1$
    StyleSheet css = ((HTMLEditorKit) textPane.getEditorKit()).getStyleSheet();
    URL url = this.getClass().getResource("/html/carnot.css"); // $NON-NLS-1$
    css.importStyleSheet(url);
    textPane.setEditable(false);
    sashForm.setWeights(new int[] {1, 2});
    final TreeViewer viewer = new TreeViewer(tree);
    viewer.setContentProvider(new PatternsContentProvider());
    viewer.setLabelProvider(new PatternsLabelProvider());
    viewer.addSelectionChangedListener(
        new ISelectionChangedListener() {

          public void selectionChanged(SelectionChangedEvent event) {
            TreeSelection selection = (TreeSelection) event.getSelection();
            Object object = selection.getFirstElement();
            if (object instanceof ITemplate) {
              ITemplate template = (ITemplate) object;
              textPane.setEditorKit(new ExtendedHTMLEditorKit(template));
              textPane.setText(template.getDescription());
            } else {
              if (object instanceof ITemplateFactory) {
                ITemplateFactory templateFactory = (ITemplateFactory) object;
                textPane.setText(templateFactory.getDescription());
              }
            }
          }
        });

    viewer.addDragSupport(
        DND.DROP_COPY,
        new Transfer[] {LocalSelectionTransfer.getTransfer()},
        new DragSourceAdapter() {
          public void dragStart(DragSourceEvent event) {
            ISelection selection = viewer.getSelection();
            LocalSelectionTransfer.getTransfer().setSelection(selection);
            LocalSelectionTransfer.getTransfer().setSelectionSetTime(event.time & 0xFFFFFFFFL);
            event.doit = DropTemplateWorkflowModelEditorAction.isValidDndSelection(selection);
          }

          public void dragSetData(DragSourceEvent event) {
            event.data = LocalSelectionTransfer.getTransfer().getSelection();
          }

          public void dragFinished(DragSourceEvent event) {
            LocalSelectionTransfer.getTransfer().setSelection(null);
            LocalSelectionTransfer.getTransfer().setSelectionSetTime(0);
          }
        });

    // Add actions to the local tool bar
    IToolBarManager tbm = getViewSite().getActionBars().getToolBarManager();
    Action refreshAction =
        new Action(Diagram_Messages.LB_VersionRepository_Refresh) {
          public void run() {
            viewer.setInput(
                "org.eclipse.stardust.modeling.templates.templateProvider"); //$NON-NLS-1$
          }
        };
    tbm.add(refreshAction);

    refreshAction.run();
  }
示例#28
0
  @Override
  public void createPartControl(Composite parent) {

    fileManager = new FileManager(new SetupContextHelper());

    parent.setLayout(new GridLayout());
    viewer = new TableViewer(parent);
    viewer.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    viewer.setLabelProvider(new ViewLabelProvider());
    viewer.setContentProvider(new BasicContentProvider());
    viewer.setInput(fileManager);
    viewer.addSelectionChangedListener(
        new ISelectionChangedListener() {

          @Override
          public void selectionChanged(SelectionChangedEvent event) {
            if (event.getSelection() instanceof StructuredSelection) {
              inputData = null;
              eventManager.sendInputDataUpdate(null);
              selectedFile =
                  (String) ((StructuredSelection) event.getSelection()).getFirstElement();
              update(currentOperation);
            }
          }
        });
    ColumnViewerToolTipSupport.enableFor(viewer);

    DropTargetAdapter dropListener =
        new DropTargetAdapter() {
          @Override
          public void drop(DropTargetEvent event) {
            Object dropData = event.data;
            if (dropData instanceof TreeSelection) {
              TreeSelection selectedNode = (TreeSelection) dropData;
              Object obj[] = selectedNode.toArray();
              List<String> paths = new ArrayList<String>();
              for (int i = 0; i < obj.length; i++) {
                if (obj[i] instanceof IFile) {
                  IFile file = (IFile) obj[i];
                  paths.add(file.getLocation().toOSString());
                }
              }

              if (!paths.isEmpty()) fileManager.addFiles(paths.toArray(new String[paths.size()]));

            } else if (dropData instanceof String[]) {
              fileManager.addFiles((String[]) dropData);
            }
            viewer.setInput(fileManager);
          }
        };

    DropTarget dt =
        new DropTarget(viewer.getControl(), DND.DROP_MOVE | DND.DROP_DEFAULT | DND.DROP_COPY);
    dt.setTransfer(
        new Transfer[] {
          TextTransfer.getInstance(),
          FileTransfer.getInstance(),
          ResourceTransfer.getInstance(),
          LocalSelectionTransfer.getTransfer()
        });
    dt.addDropListener(dropListener);

    csw = new ChangeSliceWidget(parent);
    csw.addSliceChangeListener(
        new ISliceChangeListener() {

          @Override
          public void sliceChanged(SliceChangeEvent event) {
            inputData = null;
            eventManager.sendInputDataUpdate(null);
            String ss = Slice.createString(csw.getCurrentSlice());
            currentSliceLabel.setText("Current slice of data: [" + ss + "]");
            currentSliceLabel.getParent().layout(true);
            update(currentOperation);
          }
        });

    csw.disable();

    final MenuManager rightClick = new MenuManager();
    createActions(rightClick);
    viewer.getControl().setMenu(rightClick.createContextMenu(viewer.getControl()));

    getSite()
        .getPage()
        .addSelectionListener(
            "org.dawnsci.processing.ui.processingView",
            new ISelectionListener() {

              @Override
              public void selectionChanged(IWorkbenchPart part, ISelection selection) {

                if (selection instanceof StructuredSelection
                    && ((StructuredSelection) selection).getFirstElement()
                        instanceof OperationDescriptor) {
                  OperationDescriptor des =
                      (OperationDescriptor) ((StructuredSelection) selection).getFirstElement();
                  try {

                    currentOperation = des.getSeriesObject();
                    update(currentOperation);
                  } catch (InstantiationException e) {
                    logger.error(e.getMessage(), e);
                  }
                } else {
                  if (getOperations() == null || getOperations().length == 0) {
                    output.clear();
                  }
                }
              }
            });

    currentSliceLabel = new Label(parent, SWT.WRAP);
    currentSliceLabel.setText("Current slice of data: [ - - - - -]");

    IWorkbenchPage page = getSite().getPage();
    IViewPart view = page.findView("org.dawnsci.processing.ui.output");
    output = (IPlottingSystem<Composite>) view.getAdapter(IPlottingSystem.class);

    view = page.findView("org.dawnsci.processing.ui.input");
    input = (IPlottingSystem<Composite>) view.getAdapter(IPlottingSystem.class);

    fileManager.addFileListener(
        new IFilesAddedListener() {

          @Override
          public void filesAdded(FileAddedEvent event) {

            String[] paths = event.getPaths();
            boolean[] success = event.getSuccess();

            int first = -1;
            final List<String> failedPaths = new ArrayList<String>();
            for (int i = 0; i < success.length; i++) {
              if (success[i] && first < 0) first = i;
              if (!success[i]) failedPaths.add(paths[i]);
            }

            String dsName = "";

            try {
              dsName = " (" + fileManager.getContext().getDatasetNames().get(0) + ")";
            } catch (Exception e) {
              // ignore
            }

            final String dsn = dsName;

            final int f = first;

            Display.getDefault()
                .syncExec(
                    new Runnable() {

                      @Override
                      public void run() {
                        if (f < 0) {
                          MessageDialog.openError(
                              getSite().getShell(),
                              "Error loading files",
                              "None of the selected files contained suitable datasets" + dsn + "!");
                          return;
                        }

                        if (!failedPaths.isEmpty()) {
                          StringBuilder sb = new StringBuilder();
                          sb.append("Failed to load: ");
                          for (String p : failedPaths) sb.append(p + ", ");
                          sb.append("did not contain suitable datasets");
                          sb.append(dsn);

                          MessageDialog.openError(
                              getSite().getShell(), "Error loading some files", sb.toString());
                        }
                      }
                    });

            if (f < 0) return;

            final String path = paths[first];

            Display.getDefault()
                .syncExec(
                    new Runnable() {

                      @Override
                      public void run() {
                        viewer.refresh();
                        viewer.setSelection(new StructuredSelection(path), true);
                      }
                    });
          }
        });

    eventManager.addOperationRunnerListener(
        new IOperationGUIRunnerListener.Stub() {
          @Override
          public void updateRequested() {
            update(currentOperation);
          }
        });

    // hook up delete key to remove from list
    viewer
        .getTable()
        .addKeyListener(
            new KeyListener() {

              @Override
              public void keyReleased(KeyEvent e) {}

              @Override
              public void keyPressed(KeyEvent e) {
                if (e.keyCode == SWT.DEL) {
                  clearSelected();
                }
              }
            });
  }
 /**
  * DOC mhelleboid BusinessDiagramDropTargetListener constructor comment.
  *
  * @param viewer
  */
 public BusinessDiagramDropTargetListener(EditPartViewer viewer) {
   super(viewer, LocalSelectionTransfer.getTransfer());
 }
  void createSection(Section section, FormToolkit toolkit) {
    // Toolbar buttons
    ToolBar toolbar = new ToolBar(section, SWT.FLAT);
    section.setTextClient(toolbar);
    fillToolBar(toolbar);

    Composite composite = toolkit.createComposite(section);
    section.setClient(composite);

    table = toolkit.createTable(composite, SWT.FULL_SELECTION | SWT.MULTI | SWT.BORDER);

    viewer = new TableViewer(table);
    viewer.setContentProvider(new ArrayContentProvider());
    viewer.setLabelProvider(new VersionedClauseLabelProvider());

    // Listeners
    viewer.addSelectionChangedListener(
        new ISelectionChangedListener() {
          public void selectionChanged(SelectionChangedEvent event) {
            ToolItem remove = getRemoveItemTool();
            if (remove != null) remove.setEnabled(!viewer.getSelection().isEmpty());
          }
        });
    ViewerDropAdapter dropAdapter =
        new ViewerDropAdapter(viewer) {
          @Override
          public void dragEnter(DropTargetEvent event) {
            super.dragEnter(event);
            event.detail = DND.DROP_COPY;
          }

          @Override
          public boolean validateDrop(Object target, int operation, TransferData transferType) {
            if (FileTransfer.getInstance().isSupportedType(transferType)) {
              return true;
            } else if (ResourceTransfer.getInstance().isSupportedType(transferType)) {
              return true;
            } else {
              ISelection selection = LocalSelectionTransfer.getTransfer().getSelection();
              if (selection.isEmpty() || !(selection instanceof IStructuredSelection)) {
                return false;
              }

              Iterator<?> iterator = ((IStructuredSelection) selection).iterator();
              while (iterator.hasNext()) {
                Object element = iterator.next();
                if (!(element instanceof RepositoryBundle)
                    && !(element instanceof RepositoryBundleVersion)
                    && !(element instanceof ProjectBundle)) {
                  return false;
                }
              }
              return true;
            }
          }

          @Override
          public boolean performDrop(Object data) {
            if (data instanceof String[]) {
              return handleFileNameDrop((String[]) data);
            } else if (data instanceof IResource[]) {
              return handleResourceDrop((IResource[]) data);
            } else {
              return handleSelectionDrop();
            }
          }

          private boolean handleResourceDrop(IResource[] resources) {
            File[] files = new File[resources.length];
            for (int i = 0; i < resources.length; i++) {
              files[i] = resources[i].getLocation().toFile();
            }
            return handleFileDrop(files);
          }

          private boolean handleFileNameDrop(String[] paths) {
            File[] files = new File[paths.length];
            for (int i = 0; i < paths.length; i++) {
              files[i] = new File(paths[i]);
            }
            return handleFileDrop(files);
          }

          private boolean handleFileDrop(File[] files) {
            if (files.length > 0) {
              IPreferenceStore store = Plugin.getDefault().getPreferenceStore();
              boolean hideWarning = store.getBoolean(Plugin.PREF_HIDE_WARNING_EXTERNAL_FILE);
              if (!hideWarning) {
                MessageDialogWithToggle dialog =
                    MessageDialogWithToggle.openWarning(
                        getSection().getShell(),
                        "Add External Files",
                        "External files cannot be directly added to a project, they must be added to a local repository first.",
                        "Do not show this warning again.",
                        false,
                        null,
                        null);
                if (Window.CANCEL == dialog.getReturnCode()) return false;
                if (dialog.getToggleState()) {
                  store.setValue(Plugin.PREF_HIDE_WARNING_EXTERNAL_FILE, true);
                }
              }

              AddFilesToRepositoryWizard wizard = new AddFilesToRepositoryWizard(null, files);
              WizardDialog dialog = new WizardDialog(getSection().getShell(), wizard);
              if (Window.OK == dialog.open()) {
                List<Pair<String, String>> addingBundles = wizard.getSelectedBundles();
                List<VersionedClause> addingClauses =
                    new ArrayList<VersionedClause>(addingBundles.size());

                for (Pair<String, String> addingBundle : addingBundles) {
                  Map<String, String> attribs = new HashMap<String, String>();
                  attribs.put(Constants.VERSION_ATTRIBUTE, addingBundle.getSecond());
                  addingClauses.add(new VersionedClause(addingBundle.getFirst(), attribs));
                }

                if (!addingClauses.isEmpty()) {
                  bundles.addAll(addingClauses);
                  viewer.add(addingClauses.toArray(new Object[addingClauses.size()]));
                  markDirty();
                }
              }
              return true;
            }
            return false;
          }

          private boolean handleSelectionDrop() {
            ISelection selection = LocalSelectionTransfer.getTransfer().getSelection();
            if (selection.isEmpty() || !(selection instanceof IStructuredSelection)) {
              return false;
            }
            List<VersionedClause> adding = new LinkedList<VersionedClause>();
            Iterator<?> iterator = ((IStructuredSelection) selection).iterator();
            while (iterator.hasNext()) {
              Object item = iterator.next();
              if (item instanceof RepositoryBundle) {
                String bsn = ((RepositoryBundle) item).getBsn();
                adding.add(new VersionedClause(bsn, new HashMap<String, String>()));
              } else if (item instanceof RepositoryBundleVersion) {
                RepositoryBundleVersion bundleVersion = (RepositoryBundleVersion) item;
                Map<String, String> attribs = new HashMap<String, String>();
                attribs.put(Constants.VERSION_ATTRIBUTE, bundleVersion.getVersion().toString());
                adding.add(new VersionedClause(bundleVersion.getBundle().getBsn(), attribs));
              } else if (item instanceof ProjectBundle) {
                String bsn = ((ProjectBundle) item).getBsn();
                Map<String, String> attribs = new HashMap<String, String>();
                attribs.put(Constants.VERSION_ATTRIBUTE, "snapshot");
                adding.add(new VersionedClause(bsn, attribs));
              }
            }
            if (!adding.isEmpty()) {
              bundles.addAll(adding);
              viewer.add(adding.toArray(new Object[adding.size()]));
              markDirty();
            }
            return true;
          }
        };
    dropAdapter.setFeedbackEnabled(false);
    dropAdapter.setExpandEnabled(false);
    viewer.addDropSupport(
        DND.DROP_COPY | DND.DROP_MOVE,
        new Transfer[] {
          LocalSelectionTransfer.getTransfer(),
          FileTransfer.getInstance(),
          ResourceTransfer.getInstance()
        },
        dropAdapter);

    table.addKeyListener(
        new KeyAdapter() {
          @Override
          public void keyReleased(KeyEvent e) {
            if (e.character == SWT.DEL) {
              doRemove();
            } else if (e.character == '+') {;
              doAdd();
            }
          }
        });

    // Layout
    GridLayout layout = new GridLayout(1, false);
    layout.horizontalSpacing = 0;
    layout.verticalSpacing = 0;
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    composite.setLayout(layout);

    GridData gd = getTableLayoutData();
    table.setLayoutData(gd);
  }