下面列出了怎么用org.eclipse.ui.dialogs.SelectionDialog的API类实例代码及写法,或者点击链接到github查看源代码。
protected void handleMainClassBrowseButtonPressed() {
List<IResource> resources= JarPackagerUtil.asResources(fJarPackage.getElements());
if (resources == null) {
setErrorMessage(JarPackagerMessages.JarManifestWizardPage_error_noResourceSelected);
return;
}
IJavaSearchScope searchScope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(resources.toArray(new IResource[resources.size()]), true);
SelectionDialog dialog= JavaUI.createMainTypeDialog(getContainer().getShell(), getContainer(), searchScope, 0, false, ""); //$NON-NLS-1$
dialog.setTitle(JarPackagerMessages.JarManifestWizardPage_mainTypeSelectionDialog_title);
dialog.setMessage(JarPackagerMessages.JarManifestWizardPage_mainTypeSelectionDialog_message);
if (fJarPackage.getManifestMainClass() != null)
dialog.setInitialSelections(new Object[] {fJarPackage.getManifestMainClass()});
if (dialog.open() == Window.OK) {
fJarPackage.setManifestMainClass((IType)dialog.getResult()[0]);
fMainClassText.setText(JarPackagerUtil.getMainClassName(fJarPackage));
} else if (!fJarPackage.isMainClassValid(getContainer())) {
// user did not cancel: no types were found
fJarPackage.setManifestMainClass(null);
fMainClassText.setText(JarPackagerUtil.getMainClassName(fJarPackage));
}
}
@Override
public void run() {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
SelectionDialog dialog= null;
try {
dialog= JavaUI.createTypeDialog(shell, new ProgressMonitorDialog(shell),
SearchEngine.createWorkspaceScope(), IJavaElementSearchConstants.CONSIDER_ALL_TYPES, false);
} catch (JavaModelException e) {
String title= getDialogTitle();
String message= PackagesMessages.GotoType_error_message;
ExceptionHandler.handle(e, title, message);
return;
}
dialog.setTitle(getDialogTitle());
dialog.setMessage(PackagesMessages.GotoType_dialog_message);
if (dialog.open() == IDialogConstants.CANCEL_ID) {
return;
}
Object[] types= dialog.getResult();
if (types != null && types.length > 0) {
gotoType((IType) types[0]);
}
}
/**
* Creates the type hierarchy for type selection.
*/
private void doBrowseTypes() {
IRunnableContext context= new BusyIndicatorRunnableContext();
IJavaSearchScope scope= SearchEngine.createWorkspaceScope();
int style= IJavaElementSearchConstants.CONSIDER_ALL_TYPES;
try {
SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), context, scope, style, false, fNameDialogField.getText());
dialog.setTitle(CallHierarchyMessages.CallHierarchyTypesOrMembersDialog_ChooseTypeDialog_title);
dialog.setMessage(CallHierarchyMessages.CallHierarchyTypesOrMembersDialog_ChooseTypeDialog_description);
if (dialog.open() == Window.OK) {
IType res= (IType)dialog.getResult()[0];
fNameDialogField.setText(res.getFullyQualifiedName('.'));
}
} catch (JavaModelException e) {
ExceptionHandler.handle(e, getShell(), CallHierarchyMessages.CallHierarchyTypesOrMembersDialog_ChooseTypeDialog_title,
CallHierarchyMessages.CallHierarchyTypesOrMembersDialog_ChooseTypeDialog_error_message);
}
}
private void browseForBuilderClass() {
try {
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { getType().getJavaProject() });
SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), PlatformUI.getWorkbench().getProgressService(), scope,
IJavaElementSearchConstants.CONSIDER_CLASSES, false, "*ToString", fExtension); //$NON-NLS-1$
dialog.setTitle(JavaUIMessages.GenerateToStringDialog_customBuilderConfig_classSelection_windowTitle);
dialog.setMessage(JavaUIMessages.GenerateToStringDialog_customBuilderConfig_classSelection_message);
dialog.open();
if (dialog.getReturnCode() == OK) {
IType type= (IType)dialog.getResult()[0];
fBuilderClassName.setText(type.getFullyQualifiedParameterizedName());
List<String> suggestions= fValidator.getAppendMethodSuggestions(type);
if (!suggestions.contains(fAppendMethodName.getText()))
fAppendMethodName.setText(suggestions.get(0));
suggestions= fValidator.getResultMethodSuggestions(type);
if (!suggestions.contains(fResultMethodName.getText()))
fResultMethodName.setText(suggestions.get(0));
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
private void doBrowseTypes() {
IRunnableContext context= new BusyIndicatorRunnableContext();
IJavaSearchScope scope= SearchEngine.createWorkspaceScope();
int style= IJavaElementSearchConstants.CONSIDER_ALL_TYPES;
try {
SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), context, scope, style, false, fNameDialogField.getText());
dialog.setTitle(PreferencesMessages.FavoriteStaticMemberInputDialog_ChooseTypeDialog_title);
dialog.setMessage(PreferencesMessages.FavoriteStaticMemberInputDialog_ChooseTypeDialog_description);
if (dialog.open() == Window.OK) {
IType res= (IType) dialog.getResult()[0];
fNameDialogField.setText(res.getFullyQualifiedName('.'));
}
} catch (JavaModelException e) {
ExceptionHandler.handle(e, getShell(), PreferencesMessages.FavoriteStaticMemberInputDialog_ChooseTypeDialog_title, PreferencesMessages.FavoriteStaticMemberInputDialog_ChooseTypeDialog_error_message);
}
}
private void doBrowseTypes(StringButtonDialogField dialogField) {
IRunnableContext context= new BusyIndicatorRunnableContext();
IJavaSearchScope scope= SearchEngine.createWorkspaceScope();
int style= IJavaElementSearchConstants.CONSIDER_ANNOTATION_TYPES;
try {
SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), context, scope, style, false, dialogField.getText());
dialog.setTitle(PreferencesMessages.NullAnnotationsConfigurationDialog_browse_title);
dialog.setMessage(PreferencesMessages.NullAnnotationsConfigurationDialog_choose_annotation);
if (dialog.open() == Window.OK) {
IType res= (IType) dialog.getResult()[0];
dialogField.setText(res.getFullyQualifiedName('.'));
}
} catch (JavaModelException e) {
ExceptionHandler.handle(e, getShell(), PreferencesMessages.NullAnnotationsConfigurationDialog_error_title, PreferencesMessages.NullAnnotationsConfigurationDialog_error_message);
}
}
private void doBrowseTypes() {
IRunnableContext context= new BusyIndicatorRunnableContext();
IJavaSearchScope scope= SearchEngine.createWorkspaceScope();
int style= IJavaElementSearchConstants.CONSIDER_ALL_TYPES;
try {
SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), context, scope, style, false, fNameDialogField.getText());
dialog.setTitle(PreferencesMessages.ImportOrganizeInputDialog_ChooseTypeDialog_title);
dialog.setMessage(PreferencesMessages.ImportOrganizeInputDialog_ChooseTypeDialog_description);
if (dialog.open() == Window.OK) {
IType res= (IType) dialog.getResult()[0];
fNameDialogField.setText(res.getFullyQualifiedName('.'));
}
} catch (JavaModelException e) {
ExceptionHandler.handle(e, getShell(), PreferencesMessages.ImportOrganizeInputDialog_ChooseTypeDialog_title, PreferencesMessages.ImportOrganizeInputDialog_ChooseTypeDialog_error_message);
}
}
public static SelectionDialog getSelectionDialog(String codeSystemName, Shell parent,
Object data){
java.util.List<IConfigurationElement> list =
Extensions.getExtensions(ExtensionPointConstantsUi.GENERICCODE); //$NON-NLS-1$
list.addAll(Extensions.getExtensions(ExtensionPointConstantsUi.VERRECHNUNGSCODE)); //$NON-NLS-1$
list.addAll(Extensions.getExtensions(ExtensionPointConstantsUi.DIAGNOSECODE)); //$NON-NLS-1$
if (list != null) {
for (IConfigurationElement ic : list) {
Optional<CodeSystemDescription> systemDescription = CodeSystemDescription.of(ic);
if (systemDescription.isPresent()) {
if (codeSystemName.equals(systemDescription.get().getCodeSystemName())) {
return systemDescription.get().getSelectionDialog(parent, data);
}
}
systemDescription.ifPresent(description -> {});
}
}
throw new IllegalStateException("Could not find code system " + codeSystemName);
}
@Override
public void run() {
// fail if the action hasn't been initialized
if (site == null) {
return;
}
final Object[] selectionElements = getStructuredSelection().toArray();
// get Iterable of selected project names
Iterable<String> selectionProjectNames = Arrays.asList(selectionElements)
.stream().filter(item -> item instanceof IProject)
.map(item -> ((IProject) item).getName())
.collect(Collectors.toList());
// double-check that the active Working Sets Manager is {@link ManualAssociationAwareWorkingSetManager}
if (!(broker.getActiveManager() instanceof ManualAssociationAwareWorkingSetManager)) {
return;
}
// open the dialog
SelectionDialog dialog = createDialog(Arrays.asList(((ManualAssociationAwareWorkingSetManager) broker
.getActiveManager()).getWorkingSets()), selectionElements.length);
dialog.open();
// Abort if user didn't press OK
if (dialog.getReturnCode() != Window.OK) {
return;
}
// perform specified working set updates
performWorkingSetUpdate(dialog.getResult(), selectionProjectNames);
}
protected List<FileOpener> selectOpeners(IWorkbenchPage page, Collection<FileOpener> openers) {
Shell shell = page.getWorkbenchWindow().getShell();
SelectionDialog dialog = new FileOpenerSelector(shell, openers);
if (dialog.open() == Window.OK) {
List<FileOpener> result = Lists.newArrayList();
for (Object item : dialog.getResult())
if (item instanceof FileOpener)
result.add((FileOpener) item);
return result;
}
return Collections.emptyList();
}
public static IProject openProjectDialog(String initialProject, Shell shell) {
SelectionDialog dialog = createFolderDialog(initialProject, null, true, false, shell);
if (dialog.open() != Window.OK) {
return null;
}
Object[] results = dialog.getResult();
if (results != null && results.length > 0) {
return (IProject) results[0];
}
return null;
}
public static IResource openFolderDialog(String initialFolder, IProject project, boolean showAllProjects,
Shell shell) {
SelectionDialog dialog = createFolderDialog(initialFolder, project, showAllProjects, true, shell);
if (dialog.open() != Window.OK) {
return null;
}
Object[] results = dialog.getResult();
if (results != null && results.length > 0) {
return (IResource) results[0];
}
return null;
}
/**
* Creates a selection dialog that lists all packages of the given Java project.
* The caller is responsible for opening the dialog with <code>Window.open</code>,
* and subsequently extracting the selected package (of type
* <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>.
*
* @param parent the parent shell of the dialog to be created
* @param project the Java project
* @param style flags defining the style of the dialog; the valid flags are:
* <code>IJavaElementSearchConstants.CONSIDER_BINARIES</code>, indicating that
* packages from binary package fragment roots should be included in addition
* to those from source package fragment roots;
* <code>IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS</code>, indicating that
* packages from required projects should be included as well.
* @param filter the initial pattern to filter the set of packages. For example "com" shows
* all packages starting with "com". The meta character '?' representing any character and
* '*' representing any string are supported. Clients can pass an empty string if no filtering
* is required.
* @return a new selection dialog
* @exception JavaModelException if the selection dialog could not be opened
*
* @since 2.0
*/
public static SelectionDialog createPackageDialog(Shell parent, IJavaProject project, int style, String filter) throws JavaModelException {
Assert.isTrue((style | IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) ==
(IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS));
IPackageFragmentRoot[] roots= null;
if ((style & IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) != 0) {
roots= project.getAllPackageFragmentRoots();
} else {
roots= project.getPackageFragmentRoots();
}
List<IPackageFragmentRoot> consideredRoots= null;
if ((style & IJavaElementSearchConstants.CONSIDER_BINARIES) != 0) {
consideredRoots= Arrays.asList(roots);
} else {
consideredRoots= new ArrayList<IPackageFragmentRoot>(roots.length);
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot root= roots[i];
if (root.getKind() != IPackageFragmentRoot.K_BINARY)
consideredRoots.add(root);
}
}
IJavaSearchScope searchScope= SearchEngine.createJavaSearchScope(consideredRoots.toArray(new IJavaElement[consideredRoots.size()]));
BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
if (style == 0 || style == IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) {
return createPackageDialog(parent, context, searchScope, false, true, filter);
} else {
return createPackageDialog(parent, context, searchScope, false, false, filter);
}
}
protected void handleSealPackagesDetailsButtonPressed() {
SelectionDialog dialog= createPackageDialog(getPackagesForSelectedResources());
dialog.setTitle(JarPackagerMessages.JarManifestWizardPage_sealedPackagesSelectionDialog_title);
dialog.setMessage(JarPackagerMessages.JarManifestWizardPage_sealedPackagesSelectionDialog_message);
dialog.setInitialSelections(fJarPackage.getPackagesToSeal());
if (dialog.open() == Window.OK)
fJarPackage.setPackagesToSeal(getPackagesFromDialog(dialog));
updateSealingInfo();
}
protected void handleUnSealPackagesDetailsButtonPressed() {
SelectionDialog dialog= createPackageDialog(getPackagesForSelectedResources());
dialog.setTitle(JarPackagerMessages.JarManifestWizardPage_unsealedPackagesSelectionDialog_title);
dialog.setMessage(JarPackagerMessages.JarManifestWizardPage_unsealedPackagesSelectionDialog_message);
dialog.setInitialSelections(fJarPackage.getPackagesToUnseal());
if (dialog.open() == Window.OK)
fJarPackage.setPackagesToUnseal(getPackagesFromDialog(dialog));
updateSealingInfo();
}
@Override
public void run() {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
SelectionDialog dialog= createAllPackagesDialog(shell);
dialog.setTitle(getDialogTitle());
dialog.setMessage(PackagesMessages.GotoPackage_dialog_message);
dialog.open();
Object[] res= dialog.getResult();
if (res != null && res.length == 1)
gotoPackage((IPackageFragment)res[0]);
}
private SelectionDialog createAllPackagesDialog(Shell shell) {
IProgressService progressService= PlatformUI.getWorkbench().getProgressService();
IJavaSearchScope scope= SearchEngine.createWorkspaceScope();
int flag= PackageSelectionDialog.F_HIDE_EMPTY_INNER;
PackageSelectionDialog dialog= new PackageSelectionDialog(shell, progressService, flag, scope);
dialog.setFilter(""); //$NON-NLS-1$
dialog.setIgnoreCase(false);
dialog.setMultipleSelection(false);
return dialog;
}
private void createRow(final Composite parent, Composite panel,
final Text text) {
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Button button = new Button(panel, SWT.BORDER);
button.setText("Browse...");
button.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event arg0) {
try {
AST ast = AST.newAST(3);
SelectionDialog dialog = JavaUI.createTypeDialog(parent.getShell(),
new ProgressMonitorDialog(parent.getShell()), SearchEngine
.createWorkspaceScope(),
IJavaElementSearchConstants.CONSIDER_CLASSES, false);
dialog.setMessage("Select Mapper type (implementing )");
dialog.setBlockOnOpen(true);
dialog.setTitle("Select Mapper Type");
dialog.open();
if ((dialog.getReturnCode() == Window.OK)
&& (dialog.getResult().length > 0)) {
IType type = (IType) dialog.getResult()[0];
text.setText(type.getFullyQualifiedName());
setDirty(true);
}
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/**
* Creates the dialog according to the Eclipse version we have (on 3.2, the old API is used)
* @param pythonNatures
*/
public static SelectionDialog create(Shell shell, List<AbstractAdditionalTokensInfo> additionalInfo,
String selectedText) {
boolean expectedError = true;
try {
GlobalsTwoPanelElementSelector2 newDialog = new GlobalsTwoPanelElementSelector2(shell, true, selectedText);
//If we were able to instance it, the error is no longer expected!
expectedError = false;
newDialog.setElements(additionalInfo);
return newDialog;
} catch (Throwable e) {
//That's OK: it's only available for Eclipse 3.3 onwards.
if (expectedError) {
Log.log(e);
}
}
//If it got here, we were unable to create the new dialog (show the old -- compatible with 3.2)
GlobalsTwoPaneElementSelector dialog;
dialog = new GlobalsTwoPaneElementSelector(shell);
dialog.setMessage("Filter");
if (selectedText != null && selectedText.length() > 0) {
dialog.setFilter(selectedText);
}
List<IInfo> lst = new ArrayList<IInfo>();
for (AbstractAdditionalTokensInfo info : additionalInfo) {
lst.addAll(info.getAllTokens());
}
dialog.setElements(lst.toArray());
return dialog;
}
private void createRow(final Composite parent, Composite panel,
final Text text) {
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Button button = new Button(panel, SWT.BORDER);
button.setText("Browse...");
button.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event arg0) {
try {
AST ast = AST.newAST(3);
SelectionDialog dialog = JavaUI.createTypeDialog(parent.getShell(),
new ProgressMonitorDialog(parent.getShell()), SearchEngine
.createWorkspaceScope(),
IJavaElementSearchConstants.CONSIDER_CLASSES, false);
dialog.setMessage("Select Mapper type (implementing )");
dialog.setBlockOnOpen(true);
dialog.setTitle("Select Mapper Type");
dialog.open();
if ((dialog.getReturnCode() == Window.OK)
&& (dialog.getResult().length > 0)) {
IType type = (IType) dialog.getResult()[0];
text.setText(type.getFullyQualifiedName());
setDirty(true);
}
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/**
* Creates a selection dialog that lists all packages under the given package
* fragment root.
* The caller is responsible for opening the dialog with <code>Window.open</code>,
* and subsequently extracting the selected packages (of type
* <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>.
*
* @param packageFragments the package fragments
* @return a new selection dialog
*/
protected SelectionDialog createPackageDialog(Set<IJavaElement> packageFragments) {
List<IPackageFragment> packages= new ArrayList<IPackageFragment>(packageFragments.size());
for (Iterator<IJavaElement> iter= packageFragments.iterator(); iter.hasNext();) {
IPackageFragment fragment= (IPackageFragment)iter.next();
boolean containsJavaElements= false;
int kind;
try {
kind= fragment.getKind();
containsJavaElements= fragment.getChildren().length > 0;
} catch (JavaModelException ex) {
ExceptionHandler.handle(ex, getContainer().getShell(), JarPackagerMessages.JarManifestWizardPage_error_jarPackageWizardError_title, Messages.format(JarPackagerMessages.JarManifestWizardPage_error_jarPackageWizardError_message, JavaElementLabels.getElementLabel(fragment, JavaElementLabels.ALL_DEFAULT)));
continue;
}
if (kind != IPackageFragmentRoot.K_BINARY && containsJavaElements)
packages.add(fragment);
}
StandardJavaElementContentProvider cp= new StandardJavaElementContentProvider() {
@Override
public boolean hasChildren(Object element) {
// prevent the + from being shown in front of packages
return !(element instanceof IPackageFragment) && super.hasChildren(element);
}
};
final DecoratingLabelProvider provider= new DecoratingLabelProvider(new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT), new ProblemsLabelDecorator(null));
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getContainer().getShell(), provider, cp);
dialog.setDoubleClickSelects(false);
dialog.setComparator(new JavaElementComparator());
dialog.setInput(JavaCore.create(JavaPlugin.getWorkspace().getRoot()));
dialog.addFilter(new EmptyInnerPackageFilter());
dialog.addFilter(new LibraryFilter());
dialog.addFilter(new SealPackagesFilter(packages));
dialog.setValidator(new ISelectionStatusValidator() {
public IStatus validate(Object[] selection) {
StatusInfo res= new StatusInfo();
for (int i= 0; i < selection.length; i++) {
if (!(selection[i] instanceof IPackageFragment)) {
res.setError(JarPackagerMessages.JarManifestWizardPage_error_mustContainPackages);
return res;
}
}
res.setOK();
return res;
}
});
return dialog;
}
private Text createBrowseClassControl(final Composite composite,
final String string, String browseButtonLabel,
final String baseClassName, final String dialogTitle) {
Label label = new Label(composite, SWT.NONE);
GridData data = new GridData(GridData.FILL_HORIZONTAL);
label.setText(string);
label.setLayoutData(data);
final Text text = new Text(composite, SWT.SINGLE | SWT.BORDER);
GridData data2 = new GridData(GridData.FILL_HORIZONTAL);
data2.horizontalSpan = 2;
text.setLayoutData(data2);
Button browse = new Button(composite, SWT.NONE);
browse.setText(browseButtonLabel);
GridData data3 = new GridData(GridData.FILL_HORIZONTAL);
browse.setLayoutData(data3);
browse.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
IType baseType;
try {
baseType = getPackageFragmentRoot().getJavaProject().findType(
baseClassName);
// edit this to limit the scope
SelectionDialog dialog = JavaUI.createTypeDialog(
composite.getShell(), new ProgressMonitorDialog(composite
.getShell()), SearchEngine.createHierarchyScope(baseType),
IJavaElementSearchConstants.CONSIDER_CLASSES, false);
dialog.setMessage("&Choose a type:");
dialog.setBlockOnOpen(true);
dialog.setTitle(dialogTitle);
dialog.open();
if ((dialog.getReturnCode() == Window.OK)
&& (dialog.getResult().length > 0)) {
IType type = (IType) dialog.getResult()[0];
text.setText(type.getFullyQualifiedName());
}
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
if (!showContainerSelector) {
label.setEnabled(false);
text.setEnabled(false);
browse.setEnabled(false);
}
return text;
}
public void restoreInterpreterInfos(boolean editorChanged,
Shell shell, IInterpreterManager iInterpreterManager) {
final Set<String> interpreterNamesToRestore = this.getInterpreterExeOrJarToRestoreAndClear();
final IInterpreterInfo[] exesList = this.getExesList();
if (!editorChanged && interpreterNamesToRestore.size() == 0) {
IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
SelectionDialog listDialog = AbstractInterpreterPreferencesPage.createChooseIntepreterInfoDialog(
workbenchWindow, exesList,
"Select interpreters to be restored", true);
int open = listDialog.open();
if (open != ListDialog.OK) {
return;
}
Object[] result = listDialog.getResult();
if (result == null || result.length == 0) {
return;
}
for (Object o : result) {
interpreterNamesToRestore.add(((IInterpreterInfo) o).getExecutableOrJar());
}
}
//this is the default interpreter
ProgressMonitorDialog monitorDialog = new AsynchronousProgressMonitorDialog(shell);
monitorDialog.setBlockOnOpen(false);
try {
IRunnableWithProgress operation = new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask("Restoring PYTHONPATH", IProgressMonitor.UNKNOWN);
try {
pushExpectedSetInfos();
//clear all but the ones that appear
iInterpreterManager.setInfos(exesList, interpreterNamesToRestore, monitor);
} finally {
popExpectedSetInfos();
monitor.done();
}
}
};
monitorDialog.run(true, true, operation);
} catch (Exception e) {
Log.log(e);
}
}
@Override
public void run(IAction action) {
try {
PyEdit editor = getPyEdit();
IPythonNature nature = editor.getPythonNature();
if (nature != null) {
IInterpreterManager interpreterManager = nature.getRelatedInterpreterManager();
final IInterpreterInfo[] interpreterInfos = interpreterManager.getInterpreterInfos();
if (interpreterInfos == null || interpreterInfos.length == 0) {
PyDialogHelpers.openWarning("No interpreters available",
"Unable to change default interpreter because no interpreters are available (add more interpreters in the related preferences page).");
return;
}
if (interpreterInfos.length == 1) {
PyDialogHelpers.openWarning("Only 1 interpreters available",
"Unable to change default interpreter because only 1 interpreter is configured (add more interpreters in the related preferences page).");
return;
}
// Ok, more than 1 found.
IWorkbenchWindow workbenchWindow = EditorUtils.getActiveWorkbenchWindow();
Assert.isNotNull(workbenchWindow);
SelectionDialog listDialog = AbstractInterpreterPreferencesPage.createChooseIntepreterInfoDialog(
workbenchWindow, interpreterInfos,
"Select interpreter to be made the default.", false);
int open = listDialog.open();
if (open != ListDialog.OK || listDialog.getResult().length != 1) {
return;
}
Object[] result = listDialog.getResult();
if (result == null || result.length == 0) {
return;
}
final IInterpreterInfo selectedInterpreter = ((IInterpreterInfo) result[0]);
if (selectedInterpreter != interpreterInfos[0]) {
// Ok, some interpreter (which wasn't already the default) was selected.
Arrays.sort(interpreterInfos, (a, b) -> {
if (a == selectedInterpreter) {
return -1;
}
if (b == selectedInterpreter) {
return 1;
}
return 0; // Don't change order for the others.
});
Shell shell = EditorUtils.getShell();
setInterpreterInfosWithProgressDialog(interpreterManager, interpreterInfos, shell);
}
}
} catch (Exception e) {
Log.log(e);
}
}
/**
* Selects a list of strings from a list of strings
*
* @param history the history that may be selected for execution
* @return null if none was selected or a list of strings with the commands to be executed
*/
public static List<String> select(final ScriptConsoleHistory history) {
//created the HistoryElementListSelectionDialog instead of using the ElementListSelectionDialog directly because:
//1. No sorting should be enabled for choosing the history
//2. The last element should be the one selected by default
//3. The list should be below the commands
//4. The up arrow should be the one used to get focus in the elements
HistoryElementListSelectionDialog dialog = new HistoryElementListSelectionDialog(Display.getDefault()
.getActiveShell(), getLabelProvider()) {
private static final int CLEAR_HISTORY_ID = IDialogConstants.CLIENT_ID + 1;
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
createButton(parent, CLEAR_HISTORY_ID, "Clear History", false); //$NON-NLS-1$
}
@Override
protected void buttonPressed(int buttonId) {
if (buttonId == CLEAR_HISTORY_ID) {
history.clear();
// After deleting the history, close the dialog with a cancel return code
cancelPressed();
}
super.buttonPressed(buttonId);
}
};
dialog.setTitle("Command history");
final List<String> selectFrom = history.getAsList();
dialog.setElements(selectFrom.toArray(new String[0]));
dialog.setEmptySelectionMessage("No command selected");
dialog.setAllowDuplicates(true);
dialog.setBlockOnOpen(true);
dialog.setSize(100, 25); //in number of chars
dialog.setMessage("Select command(s) to be executed");
dialog.setMultipleSelection(true);
if (dialog.open() == SelectionDialog.OK) {
Object[] result = dialog.getResult();
if (result != null) {
ArrayList<String> list = new ArrayList<String>();
for (Object o : result) {
list.add(o.toString());
}
return list;
}
}
return null;
}
@Override
public void handleEvent(Event event) {
valueChanged = false;
OperationalProperties ops = getOperationalProperties();
if (event.widget == findButton) {
String className = null;
try {
String implKind = editor.getAeDescription().getFrameworkImplementation();
if (Constants.CPP_FRAMEWORK_NAME.equals(implKind)) {
FileDialog dialog = new FileDialog(getSection().getShell(), SWT.NONE);
String[] extensions = { "*.dll" };
dialog.setFilterExtensions(extensions);
String sStartDir = Platform.getLocation().toString();
dialog.setFilterPath(sStartDir);
className = dialog.open();
} else {
SelectionDialog typeDialog = JavaUI.createTypeDialog(getSection().getShell(), editor
.getEditorSite().getWorkbenchWindow(), editor.getSearchScopeForDescriptorType(),
IJavaElementSearchConstants.CONSIDER_CLASSES, false, "*");
typeDialog.setTitle(MessageFormat.format("Choose the {0} implementation class",
new Object[] { editor.descriptorTypeString() }));
typeDialog.setMessage("Filter/mask:");
if (typeDialog.open() == Window.CANCEL)
return;
Object[] result = typeDialog.getResult();
if (result != null && result.length > 0)
className = ((IType) result[0]).getFullyQualifiedName();
}
if (className == null || className.equals("")) //$NON-NLS-1$
return;
implName.setText(className);
editor.getAeDescription().setAnnotatorImplementationName(className);
valueChanged = true;
} catch (JavaModelException e) {
throw new InternalErrorCDE("unexpected Exception", e);
}
} else if (event.widget == modifiesCas) {
ops.setModifiesCas(setValueChangedBoolean(modifiesCas.getSelection(), ops.getModifiesCas()));
} else if (event.widget == multipleDeploymentAllowed) {
ops.setMultipleDeploymentAllowed(setValueChangedBoolean(multipleDeploymentAllowed
.getSelection(), ops.isMultipleDeploymentAllowed()));
} else if (event.widget == outputsNewCASes) {
ops.setOutputsNewCASes(setValueChangedBoolean(outputsNewCASes.getSelection(), ops
.getOutputsNewCASes()));
} else if (event.widget == implName) {
editor.getAeDescription().setAnnotatorImplementationName(
setValueChanged(implName.getText(), editor.getAeDescription()
.getAnnotatorImplementationName()));
}
if (valueChanged)
editor.setFileDirty();
}
@Override
public SelectionDialog getSelectionDialog(Shell parent, Object data){
return new BlockSelektor(parent, data);
}
public SelectionDialog getSelectionDialog(Shell parent, Object data){
return codeSelectorFactory.getSelectionDialog(parent, data);
}
public SelectionDialog getSelectionDialog(Shell parent, Object data){
throw new UnsupportedOperationException(
"SelectionDialog for code system " + getCodeSystemName() + " not implemented");
}
private Text createBrowseClassControl(final Composite composite,
final String string, String browseButtonLabel,
final String baseClassName, final String dialogTitle) {
Label label = new Label(composite, SWT.NONE);
GridData data = new GridData(GridData.FILL_HORIZONTAL);
label.setText(string);
label.setLayoutData(data);
final Text text = new Text(composite, SWT.SINGLE | SWT.BORDER);
GridData data2 = new GridData(GridData.FILL_HORIZONTAL);
data2.horizontalSpan = 2;
text.setLayoutData(data2);
Button browse = new Button(composite, SWT.NONE);
browse.setText(browseButtonLabel);
GridData data3 = new GridData(GridData.FILL_HORIZONTAL);
browse.setLayoutData(data3);
browse.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
IType baseType;
try {
baseType = getPackageFragmentRoot().getJavaProject().findType(
baseClassName);
// edit this to limit the scope
SelectionDialog dialog = JavaUI.createTypeDialog(
composite.getShell(), new ProgressMonitorDialog(composite
.getShell()), SearchEngine.createHierarchyScope(baseType),
IJavaElementSearchConstants.CONSIDER_CLASSES, false);
dialog.setMessage("&Choose a type:");
dialog.setBlockOnOpen(true);
dialog.setTitle(dialogTitle);
dialog.open();
if ((dialog.getReturnCode() == Window.OK)
&& (dialog.getResult().length > 0)) {
IType type = (IType) dialog.getResult()[0];
text.setText(type.getFullyQualifiedName());
}
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
if (!showContainerSelector) {
label.setEnabled(false);
text.setEnabled(false);
browse.setEnabled(false);
}
return text;
}