/*
   * @see org.eclipse.jface.dialogs.TitleAreaDialog#createDialogArea(org.eclipse.swt.widgets.Composite)
   */
  @Override
  protected Control createDialogArea(Composite parent) {
    Composite container = createContainer(parent);

    Label infoLabel = new Label(container, SWT.None);
    infoLabel.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false, 2, 1));
    infoLabel.setText(Messages.CustomizeToolbarDialog_DIALOG_INFO);

    /* Table showing Tool Items */
    Composite tableContainer = new Composite(container, SWT.NONE);
    tableContainer.setLayout(LayoutUtils.createGridLayout(1, 0, 0));
    tableContainer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    CTable cTable = new CTable(tableContainer, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);

    fItemViewer = new TableViewer(cTable.getControl());
    fItemViewer.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    fItemViewer.getTable().setHeaderVisible(false);
    ((GridData) fItemViewer.getTable().getLayoutData()).heightHint =
        fItemViewer.getTable().getItemHeight() * 24;
    fItemViewer.getTable().setFocus();
    fItemViewer
        .getTable()
        .setData(ApplicationWorkbenchWindowAdvisor.FOCUSLESS_SCROLL_HOOK, new Object());

    /* Custom Owner Drawn Category */
    if (!OwlUI.isHighContrast()) {
      fItemViewer
          .getControl()
          .addListener(
              SWT.EraseItem,
              new Listener() {
                public void handleEvent(Event event) {
                  ToolBarItem item = (ToolBarItem) event.item.getData();
                  if (item.item == CoolBarItem.SEPARATOR) {
                    Scrollable scrollable = (Scrollable) event.widget;
                    GC gc = event.gc;

                    Rectangle area = scrollable.getClientArea();
                    Rectangle rect = event.getBounds();

                    /* Paint the selection beyond the end of last column */
                    OwlUI.codExpandRegion(event, scrollable, gc, area);

                    /* Draw Gradient Rectangle */
                    Color oldForeground = gc.getForeground();
                    Color oldBackground = gc.getBackground();

                    /* Gradient */
                    gc.setBackground(fSeparatorBg);
                    gc.fillRectangle(0, rect.y, area.width, rect.height);

                    /* Top / Bottom Line */
                    gc.setForeground(fSeparatorBorderFg);
                    gc.drawLine(0, rect.y + rect.height - 1, area.width, rect.y + rect.height - 1);
                    gc.drawLine(0, rect.y, area.width, rect.y);

                    gc.setForeground(oldForeground);
                    gc.setBackground(oldBackground);

                    /* Mark as Background being handled */
                    event.detail &= ~SWT.BACKGROUND;
                  }
                }
              });
    }

    TableColumn nameCol = new TableColumn(fItemViewer.getTable(), SWT.NONE);

    CColumnLayoutData data = new CColumnLayoutData(Size.FILL, 100);
    cTable.manageColumn(
        nameCol, data, Messages.CustomizeToolbarDialog_VISIBLE_ITEMS, null, null, false, false);

    /* ContentProvider returns all selected Items */
    fItemViewer.setContentProvider(
        new IStructuredContentProvider() {
          public Object[] getElements(Object inputElement) {
            int[] itemIds = fPreferences.getIntegers(DefaultPreferences.TOOLBAR_ITEMS);
            ToolBarItem[] items = new ToolBarItem[itemIds.length];
            for (int i = 0; i < itemIds.length; i++) {
              items[i] = new ToolBarItem(CoolBarItem.values()[itemIds[i]]);
            }
            return items;
          }

          public void dispose() {}

          public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {}
        });

    /* Label Provider */
    fItemViewer.setLabelProvider(
        new CellLabelProvider() {
          @Override
          public void update(ViewerCell cell) {
            CoolBarItem item = ((ToolBarItem) cell.getElement()).item;
            cell.setText(item.getName());

            if (item.getImg() != null) cell.setImage(fResources.createImage(item.getImg()));

            if (!OwlUI.isHighContrast() && item == CoolBarItem.SPACER)
              cell.setForeground(getShell().getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
          }
        });

    /* Selection */
    fItemViewer.addSelectionChangedListener(
        new ISelectionChangedListener() {
          public void selectionChanged(SelectionChangedEvent event) {
            updateButtonEnablement();
          }
        });

    /* Support Keyboard Remove */
    fItemViewer
        .getTable()
        .addKeyListener(
            new KeyAdapter() {
              @Override
              public void keyPressed(KeyEvent e) {
                if (e.keyCode == SWT.DEL || (Application.IS_MAC && e.keyCode == SWT.BS)) onRemove();
              }
            });

    /* Drag Support */
    fItemViewer.addDragSupport(
        DND.DROP_MOVE,
        new Transfer[] {LocalSelectionTransfer.getTransfer()},
        new DragSourceAdapter() {
          @Override
          public void dragStart(final DragSourceEvent event) {
            SafeRunnable.run(
                new LoggingSafeRunnable() {
                  public void run() throws Exception {
                    IStructuredSelection selection =
                        (IStructuredSelection) fItemViewer.getSelection();
                    event.doit = (selection.size() < fItemViewer.getTable().getItemCount());

                    if (event.doit) {
                      LocalSelectionTransfer.getTransfer().setSelection(selection);
                      LocalSelectionTransfer.getTransfer()
                          .setSelectionSetTime(event.time & 0xFFFFFFFFL);
                    }
                    ;
                  }
                });
          }

          @Override
          public void dragSetData(final DragSourceEvent event) {
            SafeRunnable.run(
                new LoggingSafeRunnable() {
                  public void run() throws Exception {
                    if (LocalSelectionTransfer.getTransfer().isSupportedType(event.dataType))
                      event.data = LocalSelectionTransfer.getTransfer().getSelection();
                  }
                });
          }

          @Override
          public void dragFinished(DragSourceEvent event) {
            SafeRunnable.run(
                new LoggingSafeRunnable() {
                  public void run() throws Exception {
                    LocalSelectionTransfer.getTransfer().setSelection(null);
                    LocalSelectionTransfer.getTransfer().setSelectionSetTime(0);
                  }
                });
          }
        });

    /* Drop Support */
    ViewerDropAdapter dropSupport =
        new ViewerDropAdapter(fItemViewer) {

          @Override
          public boolean validateDrop(Object target, int operation, TransferData transferType) {
            return true;
          }

          @Override
          public boolean performDrop(Object data) {
            ToolBarItem target = (ToolBarItem) getCurrentTarget();
            if (target != null) {
              onMove((StructuredSelection) data, target, getCurrentLocation());
              return true;
            }

            return false;
          }
        };
    dropSupport.setFeedbackEnabled(true);
    dropSupport.setScrollEnabled(true);
    dropSupport.setSelectionFeedbackEnabled(true);
    fItemViewer.addDropSupport(
        DND.DROP_MOVE, new Transfer[] {LocalSelectionTransfer.getTransfer()}, dropSupport);

    /* Set Dummy Input */
    fItemViewer.setInput(this);

    /* Container for the Buttons to Manage Providers */
    Composite buttonContainer = new Composite(container, SWT.None);
    buttonContainer.setLayout(LayoutUtils.createGridLayout(1, 0, 0));
    buttonContainer.setLayoutData(new GridData(SWT.BEGINNING, SWT.FILL, false, false));

    /* Add */
    fAddMenu = new Menu(getShell(), SWT.POP_UP);
    fAddMenu.addMenuListener(
        new MenuListener() {
          public void menuShown(MenuEvent e) {
            MenuItem[] items = fAddMenu.getItems();
            for (MenuItem item : items) {
              item.dispose();
            }

            /* Fill not yet visible Items */
            int[] toolbarItemIds = fPreferences.getIntegers(DefaultPreferences.TOOLBAR_ITEMS);
            List<CoolBarItem> visibleItems = new ArrayList<CoolBarItem>();
            for (int toolbarItemId : toolbarItemIds) {
              visibleItems.add(CoolBarItem.values()[toolbarItemId]);
            }

            CoolBarItem[] toolItems = getSortedItems();
            int currentGroup = -1;
            for (final CoolBarItem toolItem : toolItems) {
              if (!visibleItems.contains(toolItem)
                  || toolItem == CoolBarItem.SEPARATOR
                  || toolItem == CoolBarItem.SPACER) {

                /* Divide Groups by Separators */
                if (currentGroup >= 0 && currentGroup != toolItem.getGroup())
                  new MenuItem(fAddMenu, SWT.SEPARATOR);

                /* Create Menu Item */
                MenuItem item = new MenuItem(fAddMenu, SWT.PUSH);
                if (StringUtils.isSet(toolItem.getTooltip())) item.setText(toolItem.getTooltip());
                else item.setText(toolItem.getName());
                if (toolItem.getImg() != null)
                  item.setImage(fResources.createImage(toolItem.getImg()));

                item.addSelectionListener(
                    new SelectionAdapter() {
                      @Override
                      public void widgetSelected(SelectionEvent e) {

                        /* Add Item */
                        onAdd(toolItem);

                        /* Re-Open Menu for More */
                        JobRunner.runInUIThread(
                            fAddMenu,
                            new Runnable() {
                              public void run() {
                                fAddMenu.setVisible(true);
                              };
                            });
                      }
                    });

                currentGroup = toolItem.getGroup();
              }
            }
          }

          public void menuHidden(MenuEvent e) {}
        });

    fAddButton = new Button(buttonContainer, SWT.DOWN);
    fAddButton.setText(Messages.CustomizeToolbarDialog_ADD);
    applyDialogFont(fAddButton);
    setButtonLayoutData(fAddButton);
    fAddButton.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            Rectangle rect = fAddButton.getBounds();
            Point pt = new Point(rect.x, rect.y + rect.height);
            pt = fAddButton.toDisplay(pt);
            fAddMenu.setLocation(pt.x, pt.y);
            fAddMenu.setVisible(true);
          }
        });

    /* Remove */
    fRemoveButton = new Button(buttonContainer, SWT.PUSH);
    fRemoveButton.setText(Messages.CustomizeToolbarDialog_REMOVE);
    fRemoveButton.setEnabled(false);
    applyDialogFont(fRemoveButton);
    setButtonLayoutData(fRemoveButton);
    fRemoveButton.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            onRemove();
          }
        });

    /* Move Provider Up */
    fMoveUpButton = new Button(buttonContainer, SWT.PUSH);
    fMoveUpButton.setText(Messages.CustomizeToolbarDialog_MOVE_UP);
    fMoveUpButton.setEnabled(false);
    applyDialogFont(fMoveUpButton);
    setButtonLayoutData(fMoveUpButton);
    ((GridData) fMoveUpButton.getLayoutData()).verticalIndent = 10;
    fMoveUpButton.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            onMove(true);
          }
        });

    /* Move Provider Down */
    fMoveDownButton = new Button(buttonContainer, SWT.PUSH);
    fMoveDownButton.setText(Messages.CustomizeToolbarDialog_MOVE_DOWN);
    fMoveDownButton.setEnabled(false);
    applyDialogFont(fMoveDownButton);
    setButtonLayoutData(fMoveDownButton);
    fMoveDownButton.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            onMove(false);
          }
        });

    /* Restore Defaults */
    fRestoreDefaults = new Button(buttonContainer, SWT.PUSH);
    fRestoreDefaults.setText(Messages.CustomizeToolbarDialog_RESTORE_DEFAULTS);
    applyDialogFont(fRestoreDefaults);
    setButtonLayoutData(fRestoreDefaults);
    ((GridData) fRestoreDefaults.getLayoutData()).grabExcessVerticalSpace = true;
    ((GridData) fRestoreDefaults.getLayoutData()).verticalAlignment = SWT.END;
    fRestoreDefaults.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            onRestoreDefaults();
          }
        });

    /* Toolbar Mode */
    Composite modeContainer = new Composite(container, SWT.None);
    modeContainer.setLayout(LayoutUtils.createGridLayout(2, 5, 0));
    modeContainer.setLayoutData(new GridData(SWT.BEGINNING, SWT.FILL, false, false, 2, 1));

    Label showLabel = new Label(modeContainer, SWT.NONE);
    showLabel.setText(Messages.CustomizeToolbarDialog_SHOW);

    fModeViewer = new ComboViewer(modeContainer, SWT.READ_ONLY | SWT.BORDER);
    fModeViewer.setContentProvider(new ArrayContentProvider());
    fModeViewer.setLabelProvider(
        new LabelProvider() {
          @Override
          public String getText(Object element) {
            if (element instanceof CoolBarMode) {
              switch ((CoolBarMode) element) {
                case IMAGE:
                  return Messages.CustomizeToolbarDialog_ICONS;
                case TEXT:
                  return Messages.CustomizeToolbarDialog_TEXT;
                case IMAGE_TEXT_VERTICAL:
                  return Messages.CustomizeToolbarDialog_ICONS_AND_TEXT;
                case IMAGE_TEXT_HORIZONTAL:
                  return Messages.CustomizeToolbarDialog_ICONS_AND_TEXT_SMALL;
              }
            }

            return super.getText(element);
          }
        });

    fModeViewer.addSelectionChangedListener(
        new ISelectionChangedListener() {
          public void selectionChanged(SelectionChangedEvent event) {
            Object selection = ((IStructuredSelection) event.getSelection()).getFirstElement();
            CoolBarMode mode = (CoolBarMode) selection;
            fPreferences.putInteger(DefaultPreferences.TOOLBAR_MODE, mode.ordinal());
          }
        });

    fModeViewer.setInput(CoolBarAdvisor.CoolBarMode.values());
    fModeViewer.setSelection(
        new StructuredSelection(
            CoolBarMode.values()[fPreferences.getInteger(DefaultPreferences.TOOLBAR_MODE)]));

    /* Separator */
    new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL)
        .setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));

    applyDialogFont(container);

    return container;
  }
  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);
  }
Esempio n. 3
0
  @Override
  public void createPartControl(Composite parent) {
    // CREATE CONTROLS
    Composite mainPanel = new Composite(parent, SWT.NONE);
    Control filterPanel = filterPart.createControl(mainPanel, 5, 5);
    Tree tree = new Tree(mainPanel, SWT.FULL_SELECTION | SWT.MULTI);
    filterPanel.setBackground(tree.getBackground());

    viewer = new TreeViewer(tree);
    viewer.setContentProvider(contentProvider);
    ColumnViewerToolTipSupport.enableFor(viewer);

    viewer.setLabelProvider(new RepositoryTreeLabelProvider(false));
    getViewSite().setSelectionProvider(viewer);

    createActions();

    JpmPreferences jpmPrefs = new JpmPreferences();
    final boolean showJpmOnClick =
        jpmPrefs.getBrowserSelection() != JpmPreferences.PREF_BROWSER_EXTERNAL;

    // LISTENERS
    filterPart.addPropertyChangeListener(
        new PropertyChangeListener() {
          @Override
          public void propertyChange(PropertyChangeEvent event) {
            String filter = (String) event.getNewValue();
            updatedFilter(filter);
          }
        });
    ViewerDropAdapter dropAdapter =
        new ViewerDropAdapter(viewer) {
          @Override
          public boolean validateDrop(Object target, int operation, TransferData transferType) {
            if (canDrop(target, transferType)) return true;

            boolean valid = false;
            if (target instanceof RepositoryPlugin) {
              if (((RepositoryPlugin) target).canWrite()) {

                if (URLTransfer.getInstance().isSupportedType(transferType)) return true;

                if (LocalSelectionTransfer.getTransfer().isSupportedType(transferType)) {
                  ISelection selection = LocalSelectionTransfer.getTransfer().getSelection();
                  if (selection instanceof IStructuredSelection) {
                    for (Iterator<?> iter = ((IStructuredSelection) selection).iterator();
                        iter.hasNext(); ) {
                      Object element = iter.next();
                      if (element instanceof RepositoryBundle
                          || element instanceof RepositoryBundleVersion) {
                        valid = true;
                        break;
                      }
                      if (element instanceof IFile) {
                        valid = true;
                        break;
                      }
                      if (element instanceof IAdaptable) {
                        IFile file = (IFile) ((IAdaptable) element).getAdapter(IFile.class);
                        if (file != null) {
                          valid = true;
                          break;
                        }
                      }
                    }
                  }
                } else {
                  valid = true;
                }
              }
            }
            return valid;
          }

          @Override
          public void dragEnter(DropTargetEvent event) {
            super.dragEnter(event);
            event.detail = DND.DROP_COPY;
          }

          @Override
          public boolean performDrop(Object data) {
            if (RepositoriesView.this.performDrop(
                getCurrentTarget(), getCurrentEvent().currentDataType)) {
              viewer.refresh(getCurrentTarget(), true);
              return true;
            }

            boolean copied = false;
            if (URLTransfer.getInstance().isSupportedType(getCurrentEvent().currentDataType)) {
              try {
                URL url =
                    new URL(
                        (String)
                            URLTransfer.getInstance()
                                .nativeToJava(getCurrentEvent().currentDataType));
                File tmp = File.createTempFile("dwnl", ".jar");
                IO.copy(url, tmp);
                copied =
                    addFilesToRepository((RepositoryPlugin) getCurrentTarget(), new File[] {tmp});
              } catch (Exception e) {
                return false;
              }
            } else if (data instanceof String[]) {
              String[] paths = (String[]) data;
              File[] files = new File[paths.length];
              for (int i = 0; i < paths.length; i++) {
                files[i] = new File(paths[i]);
              }
              copied = addFilesToRepository((RepositoryPlugin) getCurrentTarget(), files);
            } else if (data instanceof IResource[]) {
              IResource[] resources = (IResource[]) data;
              File[] files = new File[resources.length];
              for (int i = 0; i < resources.length; i++) {
                files[i] = resources[i].getLocation().toFile();
              }
              copied = addFilesToRepository((RepositoryPlugin) getCurrentTarget(), files);
            } else if (data instanceof IStructuredSelection) {
              File[] files = convertSelectionToFiles((IStructuredSelection) data);
              if (files != null && files.length > 0)
                copied = addFilesToRepository((RepositoryPlugin) getCurrentTarget(), files);
            }
            return copied;
          }
        };
    dropAdapter.setFeedbackEnabled(false);
    dropAdapter.setExpandEnabled(false);

    viewer.addDropSupport(
        DND.DROP_COPY | DND.DROP_MOVE,
        new Transfer[] {
          URLTransfer.getInstance(),
          FileTransfer.getInstance(),
          ResourceTransfer.getInstance(),
          LocalSelectionTransfer.getTransfer()
        },
        dropAdapter);
    viewer.addDragSupport(
        DND.DROP_COPY | DND.DROP_MOVE,
        new Transfer[] {LocalSelectionTransfer.getTransfer()},
        new SelectionDragAdapter(viewer));

    viewer.addSelectionChangedListener(
        new ISelectionChangedListener() {
          @Override
          public void selectionChanged(SelectionChangedEvent event) {
            boolean writableRepoSelected = false;
            IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
            Object element = selection.getFirstElement();
            if (element instanceof RepositoryPlugin) {
              RepositoryPlugin repo = (RepositoryPlugin) element;
              writableRepoSelected = repo.canWrite();
            }
            addBundlesAction.setEnabled(writableRepoSelected);
          }
        });
    tree.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseUp(MouseEvent ev) {
            Object element = ((IStructuredSelection) viewer.getSelection()).getFirstElement();
            if (element instanceof ContinueSearchElement) {
              try {
                getViewSite()
                    .getPage()
                    .showView(
                        Plugin.JPM_BROWSER_VIEW_ID,
                        null,
                        showJpmOnClick ? IWorkbenchPage.VIEW_ACTIVATE : IWorkbenchPage.VIEW_CREATE);
              } catch (PartInitException e) {
                Plugin.getDefault().getLog().log(e.getStatus());
              }
            }
          }
        });
    viewer.addDoubleClickListener(
        new IDoubleClickListener() {
          @Override
          public void doubleClick(DoubleClickEvent event) {
            if (!event.getSelection().isEmpty()) {
              IStructuredSelection selection = (IStructuredSelection) event.getSelection();
              Object element = selection.getFirstElement();
              if (element instanceof IAdaptable) {
                URI uri = (URI) ((IAdaptable) element).getAdapter(URI.class);
                if (uri != null) {
                  IWorkbenchPage page = getSite().getPage();
                  try {
                    IFileStore fileStore = EFS.getLocalFileSystem().getStore(uri);
                    IDE.openEditorOnFileStore(page, fileStore);
                  } catch (PartInitException e) {
                    logger.logError("Error opening editor for " + uri, e);
                  }
                }
              } else if (element instanceof ContinueSearchElement) {
                ContinueSearchElement searchElement = (ContinueSearchElement) element;
                try {
                  JpmPreferences jpmPrefs = new JpmPreferences();
                  if (jpmPrefs.getBrowserSelection() == JpmPreferences.PREF_BROWSER_EXTERNAL)
                    getViewSite()
                        .getWorkbenchWindow()
                        .getWorkbench()
                        .getBrowserSupport()
                        .getExternalBrowser()
                        .openURL(new URL("https://www.jpm4j.org/" + searchElement.getFilter()));
                  else
                    getViewSite()
                        .getPage()
                        .showView(Plugin.JPM_BROWSER_VIEW_ID, null, IWorkbenchPage.VIEW_VISIBLE);
                } catch (PartInitException e) {
                  Plugin.getDefault().getLog().log(e.getStatus());
                } catch (MalformedURLException e) {
                  // ignore
                }
              }
            }
          }
        });

    createContextMenu();

    // LOAD
    Central.onWorkspaceInit(
        new Function<Workspace, Void>() {
          @Override
          public Void run(Workspace a) {
            final List<RepositoryPlugin> repositories = RepositoryUtils.listRepositories(true);
            SWTConcurrencyUtil.execForControl(
                viewer.getControl(),
                true,
                new Runnable() {
                  @Override
                  public void run() {
                    viewer.setInput(repositories);
                  }
                });
            return null;
          }
        });

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

    tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    filterPanel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));

    // Toolbar
    createActions();
    fillToolBar(getViewSite().getActionBars().getToolBarManager());

    // Register as repository listener
    registration =
        Activator.getDefault()
            .getBundleContext()
            .registerService(RepositoryListenerPlugin.class, this, null);
  }