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;
  }
  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;
  }
  /**
   * 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);
    }
  }
 @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();
   }
 }
  @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();
  }
  /**
   * 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;
  }
  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;
  }
  @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;
  }