/**
   * Creates a dialog used to select exactly <i>one</i> value from the input tree.
   *
   * @param shell The parent shell for the dialog.
   * @param labelProvider The label provider for the tree.
   * @param contentProvider The content provider for the tree.
   * @return The new dialog.
   */
  private ElementTreeSelectionDialog createElementTreeSelectionDialog(
      Shell shell, ILabelProvider labelProvider, ITreeContentProvider contentProvider) {

    // Create a custom selection listener to update the selected elements on
    // the fly.
    final ISelectionChangedListener selectionListener = createSelectionChangedListener();

    ElementTreeSelectionDialog treeDialog =
        new ElementTreeSelectionDialog(shell, labelProvider, contentProvider) {
          /*
           * (non-Javadoc)
           * @see org.eclipse.ui.dialogs.ElementTreeSelectionDialog#createTreeViewer(org.eclipse.swt.widgets.Composite)
           */
          @Override
          protected TreeViewer createTreeViewer(Composite parent) {
            TreeViewer viewer = super.createTreeViewer(parent);

            // Add the selection changed listener.
            viewer.addSelectionChangedListener(selectionListener);

            return viewer;
          }
        };

    // Do not allow multi-selection here.
    treeDialog.setAllowMultiple(false);

    return treeDialog;
  }
  @SuppressWarnings("rawtypes")
  public static ElementTreeSelectionDialog createSingle(
      Shell parent,
      String title,
      String message,
      Class[] filter,
      Object input,
      List selectedElements) {

    ElementTreeSelectionDialog diag =
        new ElementTreeSelectionDialog(
            parent, new WorkbenchLabelProvider(), new BaseWorkbenchContentProvider());

    configure(diag, title, message);

    if (filter.length > 0) {
      diag.addFilter(new TypedViewerFilter(filter));
    }

    diag.setInput(input);

    if (selectedElements != null) {
      diag.setInitialElementSelections(selectedElements);
    }
    return diag;
  }
  protected CPElement[] openWorkspacePathEntryDialog(CPElement existing) {
    Class<?>[] acceptedClasses =
        new Class[] {ICProject.class, IProject.class, IContainer.class, ICContainer.class};
    TypedElementSelectionValidator validator =
        new TypedElementSelectionValidator(acceptedClasses, existing == null);
    ViewerFilter filter = new TypedViewerFilter(acceptedClasses);

    String title =
        (existing == null)
            ? CPathEntryMessages.IncludeSymbolEntryPage_fromWorkspaceDialog_new_title
            : CPathEntryMessages.IncludeSymbolEntryPage_fromWorkspaceDialog_edit_title;
    String message =
        (existing == null)
            ? CPathEntryMessages.IncludeSymbolEntryPage_fromWorkspaceDialog_new_description
            : CPathEntryMessages.IncludeSymbolEntryPage_fromWorkspaceDialog_edit_description;

    ElementTreeSelectionDialog dialog =
        new ElementTreeSelectionDialog(
            getShell(), new WorkbenchLabelProvider(), new CElementContentProvider());
    dialog.setValidator(validator);
    dialog.setTitle(title);
    dialog.setMessage(message);
    dialog.addFilter(filter);
    dialog.setInput(CoreModel.getDefault().getCModel());
    if (existing == null) {
      dialog.setInitialSelection(fCurrCProject);
    } else {
      dialog.setInitialSelection(existing.getCProject());
    }

    if (dialog.open() == Window.OK) {
      Object[] elements = dialog.getResult();
      CPElement[] res = new CPElement[elements.length];
      for (int i = 0; i < res.length; i++) {
        IProject project;
        IPath includePath;
        if (elements[i] instanceof IResource) {
          project = ((IResource) elements[i]).getProject();
          includePath = ((IResource) elements[i]).getProjectRelativePath();
        } else {
          project = ((ICElement) elements[i]).getCProject().getProject();
          includePath = ((ICElement) elements[i]).getResource().getProjectRelativePath();
        }
        CPElementGroup group = getSelectedGroup();
        res[i] =
            new CPElement(
                fCurrCProject,
                IPathEntry.CDT_INCLUDE,
                group.getResource().getFullPath(),
                group.getResource());
        res[i].setAttribute(CPElement.BASE, project.getFullPath().makeRelative());
        res[i].setAttribute(CPElement.INCLUDE, includePath);
      }
      return res;
    }
    return null;
  }
  /**
   * Creates and opens a dialog enabling the user to select one or more elements from the specified
   * input tree.
   *
   * @param shell The parent shell for the dialog.
   * @param input The input for the dialog's tree.
   * @param allowMultipleSelections Whether or not to allow multiple items to be selected. If false,
   *     then only one item may be selected from the tree, otherwise the tree's selection will be
   *     determined by checkboxes.
   * @return The result of the dialog, usually either {@link Window#OK} or {@link Window#CANCEL}.
   */
  public int openDialog(Shell shell, Object input, boolean allowMultipleSelections) {

    // Create the dialog if necessary.
    final SelectionDialog dialog;

    // Set up the content and label providers. These are required for
    // any TreeViewer.
    ITreeContentProvider contentProvider = createContentProvider();
    ILabelProvider labelProvider = createLabelProvider();

    // Create a dialog with or without checkboxes in the tree.
    if (allowMultipleSelections) {
      dialog = createCheckedTreeSelectionDialog(shell, labelProvider, contentProvider);
    } else {
      dialog = createElementTreeSelectionDialog(shell, labelProvider, contentProvider);
    }

    // Set its title and message.
    dialog.setTitle(title);
    dialog.setMessage(message);

    setInput(input);

    // Set the input and refresh the viewer.
    if (allowMultipleSelections) {
      CheckedTreeSelectionDialog treeDialog = (CheckedTreeSelectionDialog) dialog;
      treeDialog.setInput(root);
      if (!initialSelection.isEmpty()) {
        treeDialog.setInitialSelections(initialSelection.toArray());
        newSelection.addAll(initialSelection);
      }
    } else {
      ElementTreeSelectionDialog treeDialog = (ElementTreeSelectionDialog) dialog;
      treeDialog.setInput(root);
      if (!initialSelection.isEmpty()) {
        Node initialNode = initialSelection.iterator().next();
        treeDialog.setInitialSelection(initialNode);
        newSelection.add(initialNode);
      }
    }

    // Return the result of opening the dialog.
    int result = dialog.open();

    // If the dialog was closed or cancelled, reset the selection to the
    // initial one.
    if (result != Window.OK) {
      newSelection.clear();
      for (Node node : initialSelection) {
        newSelection.add(node);
      }
    }

    return result;
  }
  protected void addNewPathResource() {
    Class<?>[] acceptedClasses =
        new Class[] {ICProject.class, ICContainer.class, ITranslationUnit.class};
    TypedElementSelectionValidator validator =
        new TypedElementSelectionValidator(acceptedClasses, false);
    ViewerFilter filter = new TypedViewerFilter(acceptedClasses);

    String title = CPathEntryMessages.IncludeSymbolEntryPage_newResource_title;
    String message = CPathEntryMessages.IncludeSymbolEntryPage_newResource_description;

    ElementTreeSelectionDialog dialog =
        new ElementTreeSelectionDialog(
            getShell(), new WorkbenchLabelProvider(), new CElementContentProvider());
    dialog.setValidator(validator);
    dialog.setTitle(title);
    dialog.setMessage(message);
    dialog.addFilter(filter);
    dialog.setInput(fCurrCProject);
    dialog.setInitialSelection(fCurrCProject);

    if (dialog.open() == Window.OK) {
      Object[] elements = dialog.getResult();
      IResource resource;
      if (elements[0] instanceof IResource) {
        resource = (IResource) elements[0];
      } else {
        resource = ((ICElement) elements[0]).getResource();
      }
      CPElementGroup newGroup = new CPElementGroup(resource);
      if (!fIncludeSymPathsList.getElements().contains(newGroup)) {
        List<CPElementGroup> groups = fIncludeSymPathsList.getElements();
        for (int i = 0; i < groups.size(); i++) {
          CPElementGroup group = groups.get(i);
          if (group.getPath().isPrefixOf(newGroup.getPath())) {
            CPElement[] cpelements = group.getChildren();
            for (CPElement cpelement : cpelements) {
              if (cpelement.getInherited() == null) {
                switch (cpelement.getEntryKind()) {
                  case IPathEntry.CDT_INCLUDE:
                  case IPathEntry.CDT_INCLUDE_FILE:
                  case IPathEntry.CDT_MACRO:
                  case IPathEntry.CDT_MACRO_FILE:
                    addPathToResourceGroup(cpelement, null, newGroup);
                }
              }
            }
          }
        }
        fIncludeSymPathsList.addElement(newGroup);
      }
      fIncludeSymPathsList.selectElements(new StructuredSelection(newGroup));
      fIncludeSymPathsList.expandElement(newGroup, 1);
    }
  }
Ejemplo n.º 6
0
  @Override
  protected void buttonPressed(int buttonId) {
    if (buttonId == 1) {
      FileDialog dialog = new FileDialog(this.getShell(), SWT.OPEN);
      dialog.setText(GprofLaunchMessages.GprofNoGmonDialog_OpenGmon);
      if (project != null) {
        dialog.setFilterPath(project.getLocation().toOSString());
      }
      String s = dialog.open();
      if (s != null) {
        gmonPath = s;
      }
    } else if (buttonId == 2) {
      ElementTreeSelectionDialog dialog =
          new ElementTreeSelectionDialog(
              getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider());
      dialog.setTitle(GprofLaunchMessages.GprofNoGmonDialog_OpenGmon);
      dialog.setMessage(GprofLaunchMessages.GprofNoGmonDialog_OpenGmon);
      dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
      dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
      dialog.setAllowMultiple(false);
      dialog.setInitialSelection(project);
      dialog.setValidator(
          new ISelectionStatusValidator() {
            @Override
            public IStatus validate(Object[] selection) {
              if (selection.length != 1) {
                return new Status(IStatus.ERROR, GprofLaunch.PLUGIN_ID, 0, "", null); // $NON-NLS-1$
              }
              if (!(selection[0] instanceof IFile)) {
                return new Status(IStatus.ERROR, GprofLaunch.PLUGIN_ID, 0, "", null); // $NON-NLS-1$
              }
              return new Status(IStatus.OK, GprofLaunch.PLUGIN_ID, 0, "", null); // $NON-NLS-1$
            }
          });
      if (dialog.open() == IDialogConstants.OK_ID) {
        IResource resource = (IResource) dialog.getFirstResult();
        gmonPath = resource.getLocation().toOSString();
      }
    }

    if (gmonPath == null) {
      setReturnCode(0);
    } else {
      setReturnCode(buttonId);
    }
    close();
  }
  @Override
  protected Control createDialogArea(Composite parent) {
    Composite panel = new Composite(parent, SWT.NONE);
    panel.setLayout(new GridLayout());
    GridData panelData = new GridData(GridData.FILL_BOTH);
    panel.setLayoutData(panelData);

    Group selectedGroup =
        WidgetFactory.createGroup(
            panel, "Selected Translator", GridData.FILL_HORIZONTAL); // $NON-NLS-1$
    selectedGroup.setLayout(new GridLayout(2, false));

    this.translatorNameText =
        WidgetFactory.createTextField(selectedGroup, GridData.FILL_HORIZONTAL, UNDEFINED);
    GridData data = new GridData(GridData.FILL_HORIZONTAL);
    data.heightHint = convertHeightInCharsToPixels(1);
    this.translatorNameText.setLayoutData(data);
    this.translatorNameText.setEditable(false);
    this.translatorNameText.setBackground(panel.getBackground());
    this.translatorNameText.setText(UNDEFINED);

    super.createDialogArea(panel);

    this.statusMessageLabel = new MessageLabel(panel);
    GridData statusData = new GridData(GridData.FILL_HORIZONTAL);
    data.heightHint = convertHeightInCharsToPixels(1);
    this.statusMessageLabel.setLayoutData(statusData);
    this.statusMessageLabel.setEnabled(false);
    this.statusMessageLabel.setText(UNDEFINED);

    getTreeViewer().expandToLevel(3);

    return panel;
  }
  /**
   * View directory selection dialog.<br>
   * It is called when you press p> [Detail] search folder the "Browse" button.<br>
   * Set the path to the folder you want to display a tree dialog to select a folder, the selected.
   * <br>
   *
   * @return Folder path
   */
  private IFolder folderBrowse() {
    String directryPath = StringUtil.getText(searchTargetText);

    // Create dialog
    ElementTreeSelectionDialog dialog =
        new ElementTreeSelectionDialog(
            null, new WorkbenchLabelProvider(), new WorkbenchContentProvider());

    // Set the resources that are displayed in the dialog
    IProject project = PluginUtil.getProject(directryPath);
    dialog.setInput(getDialogInput(project));
    dialog.setMessage(getDialogMessage(project));
    dialog.setTitle(ResourceUtil.DIR_SELECT_TITLE);
    dialog.setHelpAvailable(false);

    // If the folder name has already been entered into the textbox initial
    // value
    if (!StringUtil.isEmpty(directryPath)) {
      IContainer container = ResourcesPlugin.getWorkspace().getRoot();
      dialog.setInitialSelection(PluginUtil.createIFolder(container, directryPath));
    }
    // Add ViewerFileter
    dialog.addFilter(
        new ViewerFilter() {

          /** {@inheritDoc} */
          @Override
          public boolean select(Viewer viewer, Object parentElement, Object element) {
            if (element instanceof IFolder) {
              return true;
            } else if (element instanceof IFile) {
              return false;
            }
            return true;
          }
        });

    // Open the dialog.
    if (dialog.open() == Window.OK) {
      Object result = dialog.getFirstResult();
      if (result instanceof IFolder) {
        return (IFolder) result;
      }
    }
    return null;
  }
Ejemplo n.º 9
0
  private IJavaElement chooseContainer(IJavaElement initElement) {

    StandardJavaElementContentProvider provider = new StandardJavaElementContentProvider();
    ILabelProvider labelProvider =
        new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
    ElementTreeSelectionDialog dialog =
        new ElementTreeSelectionDialog(getShell(), labelProvider, provider);
    dialog.setTitle("Elements");
    dialog.setMessage("Choose a project,package or folder");
    dialog.addFilter(new ContainerViewerFilter());
    dialog.setInput(JavaCore.create(getWorkspaceRoot()));
    dialog.setInitialSelection(initElement);
    dialog.setAllowMultiple(false);

    if (dialog.open() == Window.OK) {
      Object element = dialog.getFirstResult();

      return (IJavaElement) element;
    }
    return null;
  }
  /**
   * View the file selection dialog.<br>
   * Called when the know-how of creating XML files "Browse" button is pressed.<br>
   *
   * @return File
   */
  private IFolder folderBrowse() {
    String filePath = page.outputFilePath();
    String filePathExcludeProjectName = page.getOutputFilePathExcludeProjectName();
    if (CmnStringUtil.isEmpty(filePath)) {
      return null;
    }
    // Create dialog
    final ElementTreeSelectionDialog dialog =
        new ElementTreeSelectionDialog(
            PluginUtil.getActiveWorkbenchShell(),
            new WorkbenchLabelProvider(),
            new WorkbenchContentProvider());

    // Set the resources that are displayed in the dialog
    //        IProject project = PluginUtil.getProject(filePath);
    //        this.page.getSelectionProject();
    IProject selectionProject = this.page.getSelectionProject();
    dialog.setInput(selectionProject);
    dialog.setMessage(getDialogMessage(this.page.getSelectionProject()));
    dialog.setTitle(ResourceUtil.selectOutput);
    dialog.setHelpAvailable(false);
    // Add ViewerFileter
    dialog.addFilter(
        new ViewerFilter() {
          /** {@inheritDoc} */
          @Override
          public boolean select(Viewer viewer, Object parentElement, Object element) {
            if (element instanceof IFolder) {
              return true;
            }
            return false;
          }
        });
    //        dialog.getFirstResult();
    // Open the dialog.
    if (dialog.open() == Window.OK) {
      Object result = dialog.getFirstResult();
      if (result instanceof IFolder) {
        return (IFolder) result;
      }
    }

    return null;
  }
  protected void handleFileBrowseButton(final Text text) {
    ISelectionStatusValidator validator = getContainerDialogSelectionValidator();

    ViewerFilter filter = getContainerDialogViewerFilter();

    ITreeContentProvider contentProvider = new WorkbenchContentProvider();

    ILabelProvider labelProvider =
        new DecoratingLabelProvider(
            new WorkbenchLabelProvider(),
            PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator());

    ElementTreeSelectionDialog dialog =
        new ElementTreeSelectionDialog(getShell(), labelProvider, contentProvider);
    dialog.setValidator(validator);
    dialog.setTitle(J2EEUIMessages.CONTAINER_SELECTION_DIALOG_TITLE);
    dialog.setMessage(J2EEUIMessages.CONTAINER_SELECTION_DIALOG_DESC);
    dialog.addFilter(filter);
    dialog.setInput(CoreUtil.getWorkspaceRoot());

    if (dialog.open() == Window.OK) {
      Object element = dialog.getFirstResult();

      try {
        if (element instanceof IFolder) {
          IFolder folder = (IFolder) element;

          if (folder.equals(
              CoreUtil.getFirstSrcFolder(getDataModel().getStringProperty(PROJECT_NAME)))) {
            folder = folder.getFolder("content"); // $NON-NLS-1$
          }

          text.setText(folder.getFullPath().toPortableString());
        }
      } catch (Exception ex) {
        // Do nothing
      }
    }
  }
  public static IPath[] chooseExclusionPattern(
      Shell shell,
      IContainer currentSourceFolder,
      String title,
      String message,
      IPath initialPath,
      boolean multiSelection) {
    Class[] acceptedClasses = new Class[] {IFolder.class, IFile.class};
    ISelectionStatusValidator validator =
        new TypedElementSelectionValidator(acceptedClasses, multiSelection);
    ViewerFilter filter = new TypedViewerFilter(acceptedClasses);

    ILabelProvider lp = new WorkbenchLabelProvider();
    ITreeContentProvider cp = new WorkbenchContentProvider();

    IResource initialElement = null;
    if (initialPath != null) {
      IContainer curr = currentSourceFolder;
      int nSegments = initialPath.segmentCount();
      for (int i = 0; i < nSegments; i++) {
        IResource elem = curr.findMember(initialPath.segment(i));
        if (elem != null) {
          initialElement = elem;
        }
        if (elem instanceof IContainer) {
          curr = (IContainer) elem;
        } else {
          break;
        }
      }
    }

    ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(shell, lp, cp);
    dialog.setTitle(title);
    dialog.setValidator(validator);
    dialog.setMessage(message);
    dialog.addFilter(filter);
    dialog.setInput(currentSourceFolder);
    dialog.setInitialSelection(initialElement);
    dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
    dialog.setHelpAvailable(false);

    if (dialog.open() == Window.OK) {
      Object[] objects = dialog.getResult();
      int existingSegments = currentSourceFolder.getFullPath().segmentCount();

      IPath[] resArr = new IPath[objects.length];
      for (int i = 0; i < objects.length; i++) {
        IResource currRes = (IResource) objects[i];
        IPath path = currRes.getFullPath().removeFirstSegments(existingSegments).makeRelative();
        if (currRes instanceof IContainer) {
          path = path.addTrailingSeparator();
        }
        resArr[i] = path;
      }
      return resArr;
    }
    return null;
  }
 /** {@inheritDoc} */
 protected void buttonPressed(int buttonId) {
   if (buttonId == newInformationItemButton_ID) newInformationItemButtonPressed();
   else super.buttonPressed(buttonId);
 }
 /** {@inheritDoc} */
 protected void createButtonsForButtonBar(Composite parent) {
   createButton(parent, newInformationItemButton_ID, "New InformationItem", false);
   super.createButtonsForButtonBar(parent);
 }
 @Override
 public String selectScript(Shell shell, String current) {
   final ElementTreeSelectionDialog dialog =
       new ElementTreeSelectionDialog(
           shell, new WorkbenchLabelProvider(), new BaseWorkbenchContentProvider());
   dialog.setTitle(Messages.WORKSPACE_SCRIPT_SELECTION_BUTTON_DIALOG__TITLE.getText());
   dialog.setMessage(Messages.WORKSPACE_SCRIPT_SELECTION_BUTTON_DIALOG_PROMPT.getText());
   dialog.setEmptyListMessage(
       Messages.WORKSPACE_SCRIPT_SELECTION_BUTTON_EMPTY_WORKSPACE.getText());
   dialog.setAllowMultiple(false);
   dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
   if (current != null) {
     if (current.startsWith(PLATFORM_RESOURCE_URL_PREFIX)) {
       dialog.setInitialSelection(
           ResourcesPlugin.getWorkspace()
               .getRoot()
               .getFile(new Path(current.substring(PLATFORM_RESOURCE_URL_PREFIX.length()))));
     }
   }
   dialog.addFilter(
       new ViewerFilter() {
         @Override
         public boolean select(Viewer viewer, Object parentElement, Object element) {
           if (element instanceof IFile) {
             // filter dotfiles
             return !(((IFile) element).getName()).startsWith("."); // $NON-NLS-1$
           }
           return true;
         }
       });
   dialog.setValidator(
       new ISelectionStatusValidator() {
         @Override
         public IStatus validate(Object[] selection) {
           // only accept files
           if (selection.length > 0 && selection[0] instanceof IFile) {
             return new Status(IStatus.OK, StrategyEngineWorkspaceUI.PLUGIN_ID, null, null);
           } else {
             return new Status(IStatus.ERROR, StrategyEngineWorkspaceUI.PLUGIN_ID, null, null);
           }
         }
       });
   dialog.open();
   IFile result = (IFile) dialog.getFirstResult();
   if (result == null) {
     return null;
   } else {
     return PLATFORM_RESOURCE_URL_PREFIX + result.getFullPath().toString();
   }
 }
  /**
   *
   *
   * <pre>
   *  The method executes the creation :
   *  - opens a selection dialog to choose a {@link ConnectableElement} reference as a role by the {@link CollaborationUse} type
   *  - created a dependency between the selected role and the {@link ConnectableElement} that will be bind to it
   *
   * {@inheritDoc}
   * </pre>
   */
  @Override
  protected CommandResult doExecuteWithResult(final IProgressMonitor monitor, final IAdaptable info)
      throws ExecutionException {

    if (!canExecute()) {
      throw new ExecutionException(Messages.RoleBindingCreateCommand_INVALID_ARGS_MSG);
    }

    // Retrieve the graphical source of the binding.
    // This differs from the semantic source of the binding which is a role of the
    // CollaborationUse type.
    CollaborationUse graphicalSource = (CollaborationUse) getSource();

    // Create and open the selection dialog
    ComposedAdapterFactory adapterFactory =
        new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
    Shell currentShell = new Shell(Display.getCurrent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
    ElementTreeSelectionDialog dialog =
        new ElementTreeSelectionDialog(
            currentShell,
            new AdapterFactoryLabelProvider(adapterFactory),
            new CollaborationRoleTreeContentProvider());

    try {
      // Set dialog parameters
      dialog.setTitle(Messages.RoleBindingRoleSelectionDialog_Title);
      dialog.setMessage(Messages.RoleBindingRoleSelectionDialog_Message);
      dialog.setAllowMultiple(false);
      dialog.setHelpAvailable(false);
      // The source CollaborationUse is set as input for the selection dialog,
      // the CollaborationRoleTreeContentProvider provides the roles that can possibly be
      // selected.
      dialog.setInput(graphicalSource);

      dialog.open();
    } finally {
      adapterFactory.dispose();
    }

    // If a ConnectableElement has been selected, complete command execution
    // using selection as the "newly created" element and make the edited
    // Collaboration reference it in the CollaborationRoles eReference.
    if (dialog.getReturnCode() == ElementTreeSelectionDialog.OK) {

      ConnectableElement roleToBind = (ConnectableElement) dialog.getFirstResult();
      // Create a Dependency (the binding) between selected role and a ConnectableElement
      // (the target)
      Dependency newBinding = UMLFactory.eINSTANCE.createDependency();
      getContainer().getPackagedElements().add(newBinding);
      newBinding.getClients().add(roleToBind);
      newBinding.setName("binding_" + roleToBind.getName() + "_" + getTarget().getName());
      newBinding.getSuppliers().add(getTarget());
      graphicalSource.getRoleBindings().add(newBinding);

      doConfigure(newBinding, monitor, info);

      ((CreateElementRequest) getRequest()).setNewElement(newBinding);

      return CommandResult.newOKCommandResult(newBinding);
    }

    // No role selected: abort element creation
    return CommandResult.newCancelledCommandResult();
  }
Ejemplo n.º 17
0
 /**
  * The user has pressed the add button. Opens the configuration selection dialog and adds the
  * selected configuration.
  */
 private void handleAddButtonPressed() {
   SelectionStatusDialog dialog;
   if (SpringCoreUtils.isEclipseSameOrNewer(3, 2)) {
     FilteredElementTreeSelectionDialog selDialog =
         new FilteredElementTreeSelectionDialog(
             SpringUIUtils.getStandardDisplay().getActiveShell(),
             new LabelProvider(),
             new NonJavaResourceContentProvider());
     selDialog.addFilter(new ConfigFileFilter(project.getConfigSuffixes()));
     selDialog.setValidator(new StorageSelectionValidator(true));
     selDialog.setInput(project.getProject());
     selDialog.setSorter(new JavaElementSorter());
     dialog = selDialog;
   } else {
     ElementTreeSelectionDialog selDialog =
         new ElementTreeSelectionDialog(
             SpringUIUtils.getStandardDisplay().getActiveShell(),
             new LabelProvider(),
             new NonJavaResourceContentProvider());
     selDialog.addFilter(new ConfigFileFilter(project.getConfigSuffixes()));
     selDialog.setValidator(new StorageSelectionValidator(true));
     selDialog.setInput(project.getProject());
     selDialog.setSorter(new JavaElementSorter());
     dialog = selDialog;
   }
   dialog.setTitle(BeansUIPlugin.getResourceString(DIALOG_TITLE));
   dialog.setMessage(BeansUIPlugin.getResourceString(DIALOG_MESSAGE));
   if (dialog.open() == Window.OK) {
     Object[] selection = dialog.getResult();
     if (selection != null && selection.length > 0) {
       for (Object element : selection) {
         String config = null;
         if (element instanceof ZipEntryStorage) {
           ZipEntryStorage storage = (ZipEntryStorage) element;
           config = storage.getFullName();
         } else if (element instanceof IFile) {
           IFile file = (IFile) element;
           config = file.getProjectRelativePath().toString();
         } else if (element instanceof JarEntryFile) {
           IPath fullPath =
               ((JarPackageFragmentRoot) ((JarEntryFile) element).getPackageFragmentRoot())
                   .getPath();
           String entryName = ((JarEntryFile) element).getFullPath().toString();
           for (String name : JavaCore.getClasspathVariableNames()) {
             IPath variablePath = JavaCore.getClasspathVariable(name);
             if (variablePath != null && variablePath.isPrefixOf(fullPath)) {
               if (MessageDialog.openQuestion(
                   SpringUIUtils.getStandardDisplay().getActiveShell(),
                   "Use classpath variable",
                   "Do you want to use the classpath variable '"
                       + name
                       + "' to refer to the config file\n'"
                       + entryName
                       + "'?")) {
                 fullPath =
                     new Path(name)
                         .append(fullPath.removeFirstSegments(variablePath.segmentCount()));
               }
               break;
             }
           }
           config =
               IBeansConfig.EXTERNAL_FILE_NAME_PREFIX
                   + fullPath.toString()
                   + ZipEntryStorage.DELIMITER
                   + entryName;
         }
         if (config != null) {
           project.addConfig(config, IBeansConfig.Type.MANUAL);
         }
       }
       configsViewer.refresh(false);
       hasUserMadeChanges = true;
     }
   }
 }
  @Override
  protected String browse(final SapphireRenderingContext context) {
    final Property property = property();
    final List<Path> roots = getBasePaths();
    String selectedAbsolutePath = null;

    final List<String> extensions;

    if (this.fileExtensionService == null) {
      extensions = this.staticFileExtensionsList;
    } else {
      extensions = this.fileExtensionService.extensions();
    }

    if (enclosed()) {
      final List<IContainer> baseContainers = new ArrayList<IContainer>();

      for (Path path : roots) {
        final IContainer baseContainer = getWorkspaceContainer(path.toFile());

        if (baseContainer != null) {
          baseContainers.add(baseContainer);
        } else {
          break;
        }
      }

      final ITreeContentProvider contentProvider;
      final ILabelProvider labelProvider;
      final ViewerComparator viewerComparator;
      final Object input;

      if (roots.size() == baseContainers.size()) {
        // All paths are in the Eclipse Workspace. Use the available content and label
        // providers.

        contentProvider = new WorkspaceContentProvider(baseContainers);
        labelProvider = new WorkbenchLabelProvider();
        viewerComparator = new ResourceComparator();
        input = ResourcesPlugin.getWorkspace().getRoot();
      } else {
        // At least one of the roots is not in the Eclipse Workspace. Use custom file
        // system content and label providers.

        contentProvider = new FileSystemContentProvider(roots);
        labelProvider = new FileSystemLabelProvider(context);
        viewerComparator = new FileSystemNodeComparator();
        input = new Object();
      }

      final ElementTreeSelectionDialog dialog =
          new ElementTreeSelectionDialog(context.getShell(), labelProvider, contentProvider);

      dialog.setTitle(property.definition().getLabel(false, CapitalizationType.TITLE_STYLE, false));
      dialog.setMessage(
          createBrowseDialogMessage(
              property.definition().getLabel(true, CapitalizationType.NO_CAPS, false)));
      dialog.setAllowMultiple(false);
      dialog.setHelpAvailable(false);
      dialog.setInput(input);
      dialog.setComparator(viewerComparator);

      final Path currentPathAbsolute = convertToAbsolute((Path) ((Value<?>) property).content());

      if (currentPathAbsolute != null) {
        Object initialSelection = null;

        if (contentProvider instanceof WorkspaceContentProvider) {
          final URI uri = currentPathAbsolute.toFile().toURI();
          final IWorkspaceRoot wsroot = ResourcesPlugin.getWorkspace().getRoot();

          final IFile[] files = wsroot.findFilesForLocationURI(uri);

          if (files.length > 0) {
            final IFile file = files[0];

            if (file.exists()) {
              initialSelection = file;
            }
          }

          if (initialSelection == null) {
            final IContainer[] containers = wsroot.findContainersForLocationURI(uri);

            if (containers.length > 0) {
              final IContainer container = containers[0];

              if (container.exists()) {
                initialSelection = container;
              }
            }
          }
        } else {
          initialSelection =
              ((FileSystemContentProvider) contentProvider).find(currentPathAbsolute);
        }

        if (initialSelection != null) {
          dialog.setInitialSelection(initialSelection);
        }
      }

      if (this.type == FileSystemResourceType.FILE) {
        dialog.setValidator(new FileSelectionStatusValidator());
      } else if (this.type == FileSystemResourceType.FOLDER) {
        dialog.addFilter(new ContainersOnlyViewerFilter());
      }

      if (!extensions.isEmpty()) {
        dialog.addFilter(new ExtensionBasedViewerFilter(extensions));
      }

      if (dialog.open() == Window.OK) {
        final Object firstResult = dialog.getFirstResult();

        if (firstResult instanceof IResource) {
          selectedAbsolutePath = ((IResource) firstResult).getLocation().toString();
        } else {
          selectedAbsolutePath = ((FileSystemNode) firstResult).getFile().getPath();
        }
      }
    } else if (this.type == FileSystemResourceType.FOLDER) {
      final DirectoryDialog dialog = new DirectoryDialog(context.getShell());
      dialog.setText(
          property.definition().getLabel(true, CapitalizationType.FIRST_WORD_ONLY, false));
      dialog.setMessage(
          createBrowseDialogMessage(
              property.definition().getLabel(true, CapitalizationType.NO_CAPS, false)));

      final Value<?> value = (Value<?>) property;
      final Path path = (Path) value.content();

      if (path != null) {
        dialog.setFilterPath(path.toOSString());
      } else if (roots.size() > 0) {
        dialog.setFilterPath(roots.get(0).toOSString());
      }

      selectedAbsolutePath = dialog.open();
    } else {
      final FileDialog dialog = new FileDialog(context.getShell());
      dialog.setText(
          property.definition().getLabel(true, CapitalizationType.FIRST_WORD_ONLY, false));

      final Value<?> value = (Value<?>) property;
      final Path path = (Path) value.content();

      if (path != null && path.segmentCount() > 1) {
        dialog.setFilterPath(path.removeLastSegments(1).toOSString());
        dialog.setFileName(path.lastSegment());
      } else if (roots.size() > 0) {
        dialog.setFilterPath(roots.get(0).toOSString());
      }

      if (!extensions.isEmpty()) {
        final StringBuilder buf = new StringBuilder();

        for (String extension : extensions) {
          if (buf.length() > 0) {
            buf.append(';');
          }

          buf.append("*.");
          buf.append(extension);
        }

        dialog.setFilterExtensions(new String[] {buf.toString()});
      }

      selectedAbsolutePath = dialog.open();
    }

    if (selectedAbsolutePath != null) {
      final Path relativePath = convertToRelative(new Path(selectedAbsolutePath));

      if (relativePath != null) {
        String result = relativePath.toPortableString();

        if (this.includeLeadingSlash) {
          result = "/" + result;
        }

        return result;
      }
    }

    return null;
  }
  /**
   * Opens a selection dialog that allows to select a source container.
   *
   * @return returns the selected package fragment root or <code>null</code> if the dialog has been
   *     canceled. The caller typically sets the result to the container input field.
   *     <p>Clients can override this method if they want to offer a different dialog.
   * @since 3.2
   */
  protected IPackageFragmentRoot chooseContainer() {
    IJavaElement initElement = getPackageFragmentRoot();
    Class<?>[] acceptedClasses = new Class[] {IPackageFragmentRoot.class, IJavaProject.class};
    TypedElementSelectionValidator validator =
        new TypedElementSelectionValidator(acceptedClasses, false) {
          @Override
          public boolean isSelectedValid(Object element) {
            try {
              if (element instanceof IJavaProject) {
                IJavaProject jproject = (IJavaProject) element;
                IPath path = jproject.getProject().getFullPath();
                return (jproject.findPackageFragmentRoot(path) != null);
              } else if (element instanceof IPackageFragmentRoot) {
                return (((IPackageFragmentRoot) element).getKind()
                    == IPackageFragmentRoot.K_SOURCE);
              }
              return true;
            } catch (JavaModelException e) {
              JavaPlugin.log(e.getStatus()); // just log, no UI in validation
            }
            return false;
          }
        };

    acceptedClasses =
        new Class[] {IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class};
    ViewerFilter filter =
        new TypedViewerFilter(acceptedClasses) {
          @Override
          public boolean select(Viewer viewer, Object parent, Object element) {
            if (element instanceof IPackageFragmentRoot) {
              try {
                return (((IPackageFragmentRoot) element).getKind()
                    == IPackageFragmentRoot.K_SOURCE);
              } catch (JavaModelException e) {
                JavaPlugin.log(e.getStatus()); // just log, no UI in validation
                return false;
              }
            }
            return super.select(viewer, parent, element);
          }
        };

    StandardJavaElementContentProvider provider = new StandardJavaElementContentProvider();
    ILabelProvider labelProvider =
        new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
    ElementTreeSelectionDialog dialog =
        new ElementTreeSelectionDialog(getShell(), labelProvider, provider);
    dialog.setValidator(validator);
    dialog.setComparator(new JavaElementComparator());
    dialog.setTitle(NewWizardMessages.NewContainerWizardPage_ChooseSourceContainerDialog_title);
    dialog.setMessage(
        NewWizardMessages.NewContainerWizardPage_ChooseSourceContainerDialog_description);
    dialog.addFilter(filter);
    dialog.setInput(JavaCore.create(fWorkspaceRoot));
    dialog.setInitialSelection(initElement);
    dialog.setHelpAvailable(false);

    if (dialog.open() == Window.OK) {
      Object element = dialog.getFirstResult();
      if (element instanceof IJavaProject) {
        IJavaProject jproject = (IJavaProject) element;
        return jproject.getPackageFragmentRoot(jproject.getProject());
      } else if (element instanceof IPackageFragmentRoot) {
        return (IPackageFragmentRoot) element;
      }
      return null;
    }
    return null;
  }