use of org.eclipse.jface.operation.IRunnableContext in project eclipse.jdt.ui by eclipse-jdt.
the class JavaElementImplementationHyperlink method openImplementations.
/**
* Finds the implementations for the method or type.
* <p>
* If there's only one implementor that element is opened in the editor, otherwise the Quick
* Hierarchy is opened.
* </p>
*
* @param editor the editor
* @param region the region of the selection
* @param javaElement the method or type
* @param openAction the action to use to open the elements
* @since 3.6
*/
public static void openImplementations(IEditorPart editor, IRegion region, final IJavaElement javaElement, SelectionDispatchAction openAction) {
final boolean[] isMethodAbstract = new boolean[1];
// $NON-NLS-1$
final String dummyString = "";
final ArrayList<IJavaElement> links = new ArrayList<>();
IRunnableWithProgress runnable;
if (javaElement instanceof IMethod) {
IMethod method = (IMethod) javaElement;
try {
if (cannotBeOverriddenMethod(method)) {
openAction.run(new StructuredSelection(method));
return;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
return;
}
ITypeRoot editorInput = EditorUtility.getEditorInputJavaElement(editor, false);
CompilationUnit ast = SharedASTProviderCore.getAST(editorInput, SharedASTProviderCore.WAIT_ACTIVE_ONLY, null);
if (ast == null) {
openQuickHierarchy(editor);
return;
}
ASTNode node = NodeFinder.perform(ast, region.getOffset(), region.getLength());
ITypeBinding parentTypeBinding = null;
if (node instanceof SimpleName) {
ASTNode parent = node.getParent();
if (parent instanceof MethodInvocation) {
Expression expression = ((MethodInvocation) parent).getExpression();
if (expression == null) {
parentTypeBinding = Bindings.getBindingOfParentType(node);
} else {
parentTypeBinding = expression.resolveTypeBinding();
}
} else if (parent instanceof SuperMethodInvocation) {
// Directly go to the super method definition
openAction.run(new StructuredSelection(method));
return;
} else if (parent instanceof MethodDeclaration) {
parentTypeBinding = Bindings.getBindingOfParentType(node);
}
}
final IType receiverType = getType(parentTypeBinding);
if (receiverType == null) {
openQuickHierarchy(editor);
return;
}
runnable = monitor -> {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
try {
String methodLabel = JavaElementLabels.getElementLabel(method, JavaElementLabels.DEFAULT_QUALIFIED);
monitor.beginTask(Messages.format(JavaEditorMessages.JavaElementImplementationHyperlink_search_method_implementors, methodLabel), 10);
SearchRequestor requestor = new SearchRequestor() {
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
if (match.getAccuracy() == SearchMatch.A_ACCURATE) {
Object element = match.getElement();
if (element instanceof IMethod) {
IMethod methodFound = (IMethod) element;
if (!JdtFlags.isAbstract(methodFound)) {
links.add(methodFound);
if (links.size() > 1) {
throw new OperationCanceledException(dummyString);
}
}
}
}
}
};
IJavaSearchScope hierarchyScope;
if (receiverType.isInterface()) {
hierarchyScope = SearchEngine.createHierarchyScope(method.getDeclaringType());
} else {
if (isFullHierarchyNeeded(new SubProgressMonitor(monitor, 3), method, receiverType))
hierarchyScope = SearchEngine.createHierarchyScope(receiverType);
else {
isMethodAbstract[0] = JdtFlags.isAbstract(method);
hierarchyScope = SearchEngine.createStrictHierarchyScope(null, receiverType, true, !isMethodAbstract[0], null);
}
}
int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE;
SearchPattern pattern = SearchPattern.createPattern(method, limitTo);
Assert.isNotNull(pattern);
SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
SearchEngine engine = new SearchEngine();
engine.search(pattern, participants, hierarchyScope, requestor, new SubProgressMonitor(monitor, 7));
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
};
} else if (javaElement instanceof IType) {
IType type = (IType) javaElement;
runnable = monitor -> {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
try {
String typeLabel = JavaElementLabels.getElementLabel(type, JavaElementLabels.DEFAULT_QUALIFIED);
monitor.beginTask(Messages.format(JavaEditorMessages.JavaElementImplementationHyperlink_search_method_implementors, typeLabel), 10);
links.addAll(Arrays.asList(type.newTypeHierarchy(monitor).getAllSubtypes(type)));
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
};
} else {
return;
}
try {
IRunnableContext context = editor.getSite().getWorkbenchWindow();
context.run(true, true, runnable);
} catch (InvocationTargetException e) {
IStatus status = new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, Messages.format(JavaEditorMessages.JavaElementImplementationHyperlink_error_status_message, javaElement.getElementName()), e.getCause());
JavaPlugin.log(status);
ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), JavaEditorMessages.JavaElementImplementationHyperlink_hyperlinkText, JavaEditorMessages.JavaElementImplementationHyperlink_error_no_implementations_found_message, status);
} catch (InterruptedException e) {
if (e.getMessage() != null && !e.getMessage().isEmpty()) {
return;
}
}
if (links.isEmpty() && (javaElement instanceof IMethod && isMethodAbstract[0] || javaElement instanceof IType)) {
openAction.run(new StructuredSelection(javaElement));
} else if (links.size() == 1) {
openAction.run(new StructuredSelection(links.get(0)));
} else {
openQuickHierarchy(editor);
}
}
use of org.eclipse.jface.operation.IRunnableContext in project eclipse.jdt.ui by eclipse-jdt.
the class TypeHierarchyLifeCycle method ensureRefreshedTypeHierarchy.
/**
* Refreshes the type hierarchy for the java elements if they exist.
*
* @param elements the java elements for which the type hierarchy is computed
* @param context the runnable context
* @throws InterruptedException thrown from the <code>OperationCanceledException</code> when the monitor is canceled
* @throws InvocationTargetException thrown from the <code>JavaModelException</code> if a java element does not exist or if an exception occurs while accessing its corresponding resource
* @since 3.7
*/
public void ensureRefreshedTypeHierarchy(final IJavaElement[] elements, IRunnableContext context) throws InvocationTargetException, InterruptedException {
synchronized (this) {
if (fRefreshHierarchyJob != null) {
fRefreshHierarchyJob.cancel();
fRefreshJobCanceledExplicitly = false;
try {
fRefreshHierarchyJob.join();
} catch (InterruptedException e) {
// ignore
} finally {
fRefreshHierarchyJob = null;
fRefreshJobCanceledExplicitly = true;
}
}
}
if (elements == null || elements.length == 0) {
freeHierarchy();
return;
}
for (IJavaElement element : elements) {
if (element == null || !element.exists()) {
freeHierarchy();
return;
}
}
boolean hierachyCreationNeeded = (fHierarchy == null || !Arrays.equals(elements, fInputElements));
if (hierachyCreationNeeded || fHierarchyRefreshNeeded) {
if (fTypeHierarchyViewPart == null) {
IRunnableWithProgress op = pm -> {
try {
doHierarchyRefresh(elements, pm);
} catch (JavaModelException e1) {
throw new InvocationTargetException(e1);
} catch (OperationCanceledException e2) {
throw new InterruptedException();
}
};
fHierarchyRefreshNeeded = true;
context.run(true, true, op);
fHierarchyRefreshNeeded = false;
} else {
final String label = Messages.format(TypeHierarchyMessages.TypeHierarchyLifeCycle_computeInput, HistoryAction.getElementLabel(elements));
synchronized (this) {
fRefreshHierarchyJob = new Job(label) {
/*
* @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public IStatus run(IProgressMonitor pm) {
pm.beginTask(label, LONG);
try {
doHierarchyRefreshBackground(elements, pm);
} catch (OperationCanceledException e) {
if (fRefreshJobCanceledExplicitly) {
fTypeHierarchyViewPart.showEmptyViewer();
}
return Status.CANCEL_STATUS;
} catch (JavaModelException e) {
return e.getStatus();
} finally {
fHierarchyRefreshNeeded = true;
pm.done();
}
return Status.OK_STATUS;
}
};
fRefreshHierarchyJob.setUser(true);
IWorkbenchSiteProgressService progressService = fTypeHierarchyViewPart.getSite().getAdapter(IWorkbenchSiteProgressService.class);
progressService.schedule(fRefreshHierarchyJob, 0);
}
}
}
}
use of org.eclipse.jface.operation.IRunnableContext in project eclipse.jdt.ui by eclipse-jdt.
the class GenerateNewConstructorUsingFieldsAction method run.
// ---- Helpers -------------------------------------------------------------------
void run(IType type, IField[] selectedFields, boolean activated) throws CoreException {
if (!ElementValidator.check(type, getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, activated)) {
notifyResult(false);
return;
}
if (!ActionUtil.isEditable(fEditor, getShell(), type)) {
notifyResult(false);
return;
}
ICompilationUnit cu = type.getCompilationUnit();
if (cu == null) {
MessageDialog.openInformation(getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateNewConstructorUsingFieldsAction_error_not_a_source_file);
notifyResult(false);
return;
}
List<IField> allSelected = Arrays.asList(selectedFields);
CompilationUnit astRoot = SharedASTProviderCore.getAST(cu, SharedASTProviderCore.WAIT_YES, new NullProgressMonitor());
ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
if (typeBinding == null) {
MessageDialog.openInformation(getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateNewConstructorUsingFieldsAction_error_not_a_source_file);
notifyResult(false);
return;
}
HashMap<IJavaElement, IVariableBinding> fieldsToBindings = new HashMap<>();
ArrayList<IVariableBinding> selected = new ArrayList<>();
for (IVariableBinding curr : typeBinding.getDeclaredFields()) {
if (curr.isSynthetic()) {
continue;
}
if (Modifier.isStatic(curr.getModifiers())) {
continue;
}
if (Modifier.isFinal(curr.getModifiers())) {
ASTNode declaringNode = astRoot.findDeclaringNode(curr);
if (declaringNode instanceof VariableDeclarationFragment && ((VariableDeclarationFragment) declaringNode).getInitializer() != null) {
// Do not add final fields which have been set in the <clinit>
continue;
}
}
IJavaElement javaElement = curr.getJavaElement();
fieldsToBindings.put(javaElement, curr);
if (allSelected.contains(javaElement)) {
selected.add(curr);
}
}
if (fieldsToBindings.isEmpty()) {
MessageDialog.openInformation(getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_typeContainsNoFields_message);
notifyResult(false);
return;
}
ArrayList<IVariableBinding> fields = new ArrayList<>();
for (IField field : type.getFields()) {
IVariableBinding fieldBinding = fieldsToBindings.remove(field);
if (fieldBinding != null) {
fields.add(fieldBinding);
}
}
// paranoia code, should not happen
fields.addAll(fieldsToBindings.values());
final GenerateConstructorUsingFieldsContentProvider provider = new GenerateConstructorUsingFieldsContentProvider(fields, selected);
IMethodBinding[] bindings = null;
if (typeBinding.isAnonymous()) {
MessageDialog.openInformation(getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_error_anonymous_class);
notifyResult(false);
return;
}
if (typeBinding.isEnum()) {
bindings = new IMethodBinding[] { getObjectConstructor(astRoot.getAST()) };
} else {
bindings = StubUtility2Core.getVisibleConstructors(typeBinding, false, true);
if (bindings.length == 0) {
MessageDialog.openInformation(getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_error_nothing_found);
notifyResult(false);
return;
}
}
GenerateConstructorUsingFieldsSelectionDialog dialog = new GenerateConstructorUsingFieldsSelectionDialog(getShell(), new BindingLabelProvider(), provider, fEditor, type, bindings);
dialog.setCommentString(ActionMessages.SourceActionDialog_createConstructorComment);
dialog.setTitle(ActionMessages.GenerateConstructorUsingFieldsAction_dialog_title);
dialog.setInitialSelections(provider.getInitiallySelectedElements());
dialog.setContainerMode(true);
dialog.setSize(60, 18);
dialog.setInput(new Object());
dialog.setMessage(ActionMessages.GenerateConstructorUsingFieldsAction_dialog_label);
dialog.setValidator(new GenerateConstructorUsingFieldsValidator(dialog, typeBinding, fields.size()));
final int dialogResult = dialog.open();
if (dialogResult == Window.OK) {
Object[] elements = dialog.getResult();
if (elements == null) {
notifyResult(false);
return;
}
ArrayList<IVariableBinding> result = new ArrayList<>(elements.length);
for (Object element : elements) {
if (element instanceof IVariableBinding) {
result.add((IVariableBinding) element);
}
}
IVariableBinding[] variables = result.toArray(new IVariableBinding[result.size()]);
IEditorPart editor = JavaUI.openInEditor(cu);
CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(type.getJavaProject());
settings.createComments = dialog.getGenerateComment();
IMethodBinding constructor = dialog.getSuperConstructorChoice();
IRewriteTarget target = editor != null ? (IRewriteTarget) editor.getAdapter(IRewriteTarget.class) : null;
if (target != null)
target.beginCompoundChange();
try {
AddCustomConstructorOperation operation = new AddCustomConstructorOperation(astRoot, typeBinding, variables, constructor, dialog.getElementPosition(), settings, true, false);
operation.setVisibility(dialog.getVisibilityModifier());
if (constructor.getParameterTypes().length == 0)
operation.setOmitSuper(dialog.isOmitSuper());
IRunnableContext context = JavaPlugin.getActiveWorkbenchWindow();
if (context == null)
context = new BusyIndicatorRunnableContext();
PlatformUI.getWorkbench().getProgressService().runInUI(context, new WorkbenchRunnableAdapter(operation, operation.getSchedulingRule()), operation.getSchedulingRule());
} catch (InvocationTargetException exception) {
ExceptionHandler.handle(exception, getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_error_actionfailed);
} catch (InterruptedException exception) {
// Do nothing. Operation has been canceled by user.
} finally {
if (target != null) {
target.endCompoundChange();
}
}
}
notifyResult(dialogResult == Window.OK);
}
use of org.eclipse.jface.operation.IRunnableContext in project eclipse.jdt.ui by eclipse-jdt.
the class RefactoringPropertyPage method createContents.
@Override
protected Control createContents(final Composite parent) {
initializeDialogUnits(parent);
final IPreferencePageContainer container = getContainer();
if (container instanceof IWorkbenchPreferenceContainer)
fManager = ((IWorkbenchPreferenceContainer) container).getWorkingCopyManager();
else
fManager = new WorkingCopyManager();
final Composite composite = new Composite(parent, SWT.NONE);
final GridLayout layout = new GridLayout();
layout.marginWidth = 0;
composite.setLayout(layout);
fHistoryControl = new ShowRefactoringHistoryControl(composite, new RefactoringHistoryControlConfiguration(getCurrentProject(), true, false) {
@Override
public String getProjectPattern() {
return RefactoringUIMessages.RefactoringPropertyPage_project_pattern;
}
});
fHistoryControl.createControl();
boolean sortProjects = true;
final IDialogSettings settings = fSettings;
if (settings != null)
sortProjects = settings.getBoolean(SETTING_SORT);
if (sortProjects)
fHistoryControl.sortByProjects();
else
fHistoryControl.sortByDate();
fHistoryControl.getDeleteAllButton().addSelectionListener(new SelectionAdapter() {
@Override
public final void widgetSelected(final SelectionEvent event) {
final IProject project = getCurrentProject();
if (project != null) {
final IRunnableContext context = new ProgressMonitorDialog(getShell());
final IPreferenceStore store = RefactoringUIPlugin.getDefault().getPreferenceStore();
MessageDialogWithToggle dialog = null;
if (!store.getBoolean(PREFERENCE_DO_NOT_WARN_DELETE_ALL) && !fHistoryControl.getInput().isEmpty()) {
dialog = MessageDialogWithToggle.openYesNoQuestion(getShell(), RefactoringUIMessages.RefactoringPropertyPage_confirm_delete_all_caption, Messages.format(RefactoringUIMessages.RefactoringPropertyPage_confirm_delete_all_pattern, BasicElementLabels.getResourceName(project)), RefactoringUIMessages.RefactoringHistoryWizard_do_not_show_message, false, null, null);
store.setValue(PREFERENCE_DO_NOT_WARN_DELETE_ALL, dialog.getToggleState());
}
if (dialog == null || dialog.getReturnCode() == IDialogConstants.YES_ID)
promptDeleteHistory(context, project);
}
}
});
fHistoryControl.getDeleteButton().addSelectionListener(new SelectionAdapter() {
@Override
public final void widgetSelected(final SelectionEvent event) {
final RefactoringDescriptorProxy[] selection = fHistoryControl.getCheckedDescriptors();
if (selection.length > 0) {
final IRunnableContext context = new ProgressMonitorDialog(getShell());
final IProject project = getCurrentProject();
if (project != null) {
final Shell shell = getShell();
RefactoringHistoryEditHelper.promptRefactoringDelete(shell, context, fHistoryControl, new RefactoringDescriptorDeleteQuery(shell, getCurrentProject(), selection.length), monitor -> RefactoringHistoryService.getInstance().getProjectHistory(project, monitor), selection);
}
}
}
});
fShareHistoryButton = new Button(composite, SWT.CHECK);
fShareHistoryButton.setText(RefactoringUIMessages.RefactoringPropertyPage_share_message);
fShareHistoryButton.setData(RefactoringPreferenceConstants.PREFERENCE_SHARED_REFACTORING_HISTORY);
final GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
data.verticalIndent = convertHeightInCharsToPixels(1) / 2;
fShareHistoryButton.setLayoutData(data);
fShareHistoryButton.setSelection(hasSharedRefactoringHistory());
new Label(composite, SWT.NONE);
final IProject project = getCurrentProject();
if (project != null) {
IRunnableContext context = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (context == null)
context = PlatformUI.getWorkbench().getProgressService();
handleInputEvent(context, project);
}
applyDialogFont(composite);
PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IRefactoringHelpContextIds.REFACTORING_PROPERTY_PAGE);
return composite;
}
use of org.eclipse.jface.operation.IRunnableContext in project eclipse.jdt.ui by eclipse-jdt.
the class CreateRefactoringScriptAction method showCreateScriptWizard.
/**
* Shows the create script wizard.
*
* @param window
* the workbench window
*/
private static void showCreateScriptWizard(final IWorkbenchWindow window) {
Assert.isNotNull(window);
final CreateRefactoringScriptWizard wizard = new CreateRefactoringScriptWizard();
try {
IRunnableContext context = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (context == null)
context = PlatformUI.getWorkbench().getProgressService();
context.run(false, true, monitor -> {
final IRefactoringHistoryService service = RefactoringCore.getHistoryService();
try {
service.connect();
wizard.setRefactoringHistory(service.getWorkspaceHistory(monitor));
} finally {
service.disconnect();
}
});
} catch (InvocationTargetException exception) {
RefactoringUIPlugin.log(exception);
} catch (InterruptedException exception) {
return;
}
final WizardDialog dialog = new WizardDialog(window.getShell(), wizard) {
@Override
protected final void createButtonsForButtonBar(final Composite parent) {
super.createButtonsForButtonBar(parent);
getButton(IDialogConstants.FINISH_ID).setText(ScriptingMessages.CreateRefactoringScriptAction_finish_button_label);
}
};
dialog.create();
dialog.getShell().setSize(Math.max(SIZING_WIZARD_WIDTH, dialog.getShell().getSize().x), SIZING_WIZARD_HEIGHT);
PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IRefactoringHelpContextIds.REFACTORING_CREATE_SCRIPT_PAGE);
dialog.open();
}
Aggregations