Search in sources :

Example 11 with IRunnableContext

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);
    }
}
Also used : SelectionDispatchAction(org.eclipse.jdt.ui.actions.SelectionDispatchAction) Arrays(java.util.Arrays) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) CoreException(org.eclipse.core.runtime.CoreException) ErrorDialog(org.eclipse.jface.dialogs.ErrorDialog) IStatus(org.eclipse.core.runtime.IStatus) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) Expression(org.eclipse.jdt.core.dom.Expression) JavaElementLabels(org.eclipse.jdt.ui.JavaElementLabels) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Bindings(org.eclipse.jdt.internal.corext.dom.Bindings) IEditorPart(org.eclipse.ui.IEditorPart) ITypeHierarchy(org.eclipse.jdt.core.ITypeHierarchy) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) IRegion(org.eclipse.jface.text.IRegion) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) JavaPlugin(org.eclipse.jdt.internal.ui.JavaPlugin) ASTNode(org.eclipse.jdt.core.dom.ASTNode) PlatformUI(org.eclipse.ui.PlatformUI) Messages(org.eclipse.jdt.internal.corext.util.Messages) Assert(org.eclipse.core.runtime.Assert) Status(org.eclipse.core.runtime.Status) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) SearchRequestor(org.eclipse.jdt.core.search.SearchRequestor) InvocationTargetException(java.lang.reflect.InvocationTargetException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IRunnableContext(org.eclipse.jface.operation.IRunnableContext) IType(org.eclipse.jdt.core.IType) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) JavaModelException(org.eclipse.jdt.core.JavaModelException) MethodOverrideTester(org.eclipse.jdt.internal.corext.util.MethodOverrideTester) IMember(org.eclipse.jdt.core.IMember) StructuredSelection(org.eclipse.jface.viewers.StructuredSelection) ArrayList(java.util.ArrayList) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) JdtFlags(org.eclipse.jdt.internal.corext.util.JdtFlags) ITextOperationTarget(org.eclipse.jface.text.ITextOperationTarget) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) IJavaSearchConstants(org.eclipse.jdt.core.search.IJavaSearchConstants) SearchParticipant(org.eclipse.jdt.core.search.SearchParticipant) IHyperlink(org.eclipse.jface.text.hyperlink.IHyperlink) NodeFinder(org.eclipse.jdt.core.dom.NodeFinder) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ITypeRoot(org.eclipse.jdt.core.ITypeRoot) IJavaElement(org.eclipse.jdt.core.IJavaElement) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) IMethod(org.eclipse.jdt.core.IMethod) SharedASTProviderCore(org.eclipse.jdt.core.manipulation.SharedASTProviderCore) IRunnableContext(org.eclipse.jface.operation.IRunnableContext) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) JavaModelException(org.eclipse.jdt.core.JavaModelException) IStatus(org.eclipse.core.runtime.IStatus) SimpleName(org.eclipse.jdt.core.dom.SimpleName) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) StructuredSelection(org.eclipse.jface.viewers.StructuredSelection) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) IType(org.eclipse.jdt.core.IType) SearchParticipant(org.eclipse.jdt.core.search.SearchParticipant) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) IMethod(org.eclipse.jdt.core.IMethod) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IJavaElement(org.eclipse.jdt.core.IJavaElement) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ITypeRoot(org.eclipse.jdt.core.ITypeRoot) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) InvocationTargetException(java.lang.reflect.InvocationTargetException) SearchRequestor(org.eclipse.jdt.core.search.SearchRequestor) CoreException(org.eclipse.core.runtime.CoreException) Expression(org.eclipse.jdt.core.dom.Expression)

Example 12 with IRunnableContext

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);
            }
        }
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) Arrays(java.util.Arrays) JavaModelException(org.eclipse.jdt.core.JavaModelException) ArrayList(java.util.ArrayList) IElementChangedListener(org.eclipse.jdt.core.IElementChangedListener) IJavaElementDelta(org.eclipse.jdt.core.IJavaElementDelta) IStatus(org.eclipse.core.runtime.IStatus) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ElementChangedEvent(org.eclipse.jdt.core.ElementChangedEvent) ITypeHierarchyChangedListener(org.eclipse.jdt.core.ITypeHierarchyChangedListener) ITypeHierarchy(org.eclipse.jdt.core.ITypeHierarchy) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) JavaPlugin(org.eclipse.jdt.internal.ui.JavaPlugin) IJavaProject(org.eclipse.jdt.core.IJavaProject) Job(org.eclipse.core.runtime.jobs.Job) IOrdinaryClassFile(org.eclipse.jdt.core.IOrdinaryClassFile) Messages(org.eclipse.jdt.internal.corext.util.Messages) JavaCore(org.eclipse.jdt.core.JavaCore) Status(org.eclipse.core.runtime.Status) IRegion(org.eclipse.jdt.core.IRegion) Display(org.eclipse.swt.widgets.Display) InvocationTargetException(java.lang.reflect.InvocationTargetException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) JavaModelUtil(org.eclipse.jdt.internal.corext.util.JavaModelUtil) IRunnableContext(org.eclipse.jface.operation.IRunnableContext) IType(org.eclipse.jdt.core.IType) List(java.util.List) IJavaElement(org.eclipse.jdt.core.IJavaElement) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) IWorkbenchSiteProgressService(org.eclipse.ui.progress.IWorkbenchSiteProgressService) IJavaElement(org.eclipse.jdt.core.IJavaElement) JavaModelException(org.eclipse.jdt.core.JavaModelException) IStatus(org.eclipse.core.runtime.IStatus) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IWorkbenchSiteProgressService(org.eclipse.ui.progress.IWorkbenchSiteProgressService) Job(org.eclipse.core.runtime.jobs.Job)

Example 13 with IRunnableContext

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);
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) IRunnableContext(org.eclipse.jface.operation.IRunnableContext) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) HashMap(java.util.HashMap) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) ArrayList(java.util.ArrayList) BusyIndicatorRunnableContext(org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) IRewriteTarget(org.eclipse.jface.text.IRewriteTarget) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) GenerateConstructorUsingFieldsSelectionDialog(org.eclipse.jdt.internal.ui.actions.GenerateConstructorUsingFieldsSelectionDialog) GenerateConstructorUsingFieldsContentProvider(org.eclipse.jdt.internal.ui.actions.GenerateConstructorUsingFieldsContentProvider) WorkbenchRunnableAdapter(org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter) IEditorPart(org.eclipse.ui.IEditorPart) IField(org.eclipse.jdt.core.IField) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) AddCustomConstructorOperation(org.eclipse.jdt.internal.corext.codemanipulation.AddCustomConstructorOperation) InvocationTargetException(java.lang.reflect.InvocationTargetException) BindingLabelProvider(org.eclipse.jdt.internal.ui.viewsupport.BindingLabelProvider) GenerateConstructorUsingFieldsValidator(org.eclipse.jdt.internal.ui.actions.GenerateConstructorUsingFieldsValidator)

Example 14 with IRunnableContext

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;
}
Also used : RefactoringHistoryControlConfiguration(org.eclipse.ltk.ui.refactoring.history.RefactoringHistoryControlConfiguration) IRunnableContext(org.eclipse.jface.operation.IRunnableContext) IPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) RefactoringCore(org.eclipse.ltk.core.refactoring.RefactoringCore) CoreException(org.eclipse.core.runtime.CoreException) WorkbenchRunnableAdapter(org.eclipse.ltk.internal.ui.refactoring.WorkbenchRunnableAdapter) IDialogConstants(org.eclipse.jface.dialogs.IDialogConstants) IDialogSettings(org.eclipse.jface.dialogs.IDialogSettings) Messages(org.eclipse.ltk.internal.ui.refactoring.Messages) IScopeContext(org.eclipse.core.runtime.preferences.IScopeContext) IPreferencePageContainer(org.eclipse.jface.preference.IPreferencePageContainer) BackingStoreException(org.osgi.service.prefs.BackingStoreException) RefactoringPreferenceConstants(org.eclipse.ltk.internal.core.refactoring.RefactoringPreferenceConstants) IStatus(org.eclipse.core.runtime.IStatus) Composite(org.eclipse.swt.widgets.Composite) IEclipsePreferences(org.eclipse.core.runtime.preferences.IEclipsePreferences) MessageDialog(org.eclipse.jface.dialogs.MessageDialog) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) IWorkbenchPreferenceContainer(org.eclipse.ui.preferences.IWorkbenchPreferenceContainer) Button(org.eclipse.swt.widgets.Button) PlatformUI(org.eclipse.ui.PlatformUI) ProgressMonitorDialog(org.eclipse.jface.dialogs.ProgressMonitorDialog) RefactoringUIPlugin(org.eclipse.ltk.internal.ui.refactoring.RefactoringUIPlugin) Assert(org.eclipse.core.runtime.Assert) RefactoringHistoryService(org.eclipse.ltk.internal.core.refactoring.history.RefactoringHistoryService) Status(org.eclipse.core.runtime.Status) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) RefactoringDescriptorProxy(org.eclipse.ltk.core.refactoring.RefactoringDescriptorProxy) InvocationTargetException(java.lang.reflect.InvocationTargetException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IRunnableContext(org.eclipse.jface.operation.IRunnableContext) RefactoringHistory(org.eclipse.ltk.core.refactoring.history.RefactoringHistory) SWT(org.eclipse.swt.SWT) Label(org.eclipse.swt.widgets.Label) RefactoringUIMessages(org.eclipse.ltk.internal.ui.refactoring.RefactoringUIMessages) IProject(org.eclipse.core.resources.IProject) BasicElementLabels(org.eclipse.ltk.internal.ui.refactoring.BasicElementLabels) ProjectScope(org.eclipse.core.resources.ProjectScope) MessageDialogWithToggle(org.eclipse.jface.dialogs.MessageDialogWithToggle) GridData(org.eclipse.swt.layout.GridData) IRefactoringHistoryService(org.eclipse.ltk.core.refactoring.history.IRefactoringHistoryService) Shell(org.eclipse.swt.widgets.Shell) PropertyPage(org.eclipse.ui.dialogs.PropertyPage) Job(org.eclipse.core.runtime.jobs.Job) IRefactoringHelpContextIds(org.eclipse.ltk.internal.ui.refactoring.IRefactoringHelpContextIds) RefactoringHistoryControlConfiguration(org.eclipse.ltk.ui.refactoring.history.RefactoringHistoryControlConfiguration) IOException(java.io.IOException) IWorkingCopyManager(org.eclipse.ui.preferences.IWorkingCopyManager) RefactoringCoreMessages(org.eclipse.ltk.internal.core.refactoring.RefactoringCoreMessages) SelectionEvent(org.eclipse.swt.events.SelectionEvent) Control(org.eclipse.swt.widgets.Control) GridLayout(org.eclipse.swt.layout.GridLayout) WorkingCopyManager(org.eclipse.ui.preferences.WorkingCopyManager) Composite(org.eclipse.swt.widgets.Composite) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) ProgressMonitorDialog(org.eclipse.jface.dialogs.ProgressMonitorDialog) Label(org.eclipse.swt.widgets.Label) IProject(org.eclipse.core.resources.IProject) IPreferencePageContainer(org.eclipse.jface.preference.IPreferencePageContainer) IWorkingCopyManager(org.eclipse.ui.preferences.IWorkingCopyManager) WorkingCopyManager(org.eclipse.ui.preferences.WorkingCopyManager) GridLayout(org.eclipse.swt.layout.GridLayout) Shell(org.eclipse.swt.widgets.Shell) IDialogSettings(org.eclipse.jface.dialogs.IDialogSettings) Button(org.eclipse.swt.widgets.Button) IWorkbenchPreferenceContainer(org.eclipse.ui.preferences.IWorkbenchPreferenceContainer) SelectionEvent(org.eclipse.swt.events.SelectionEvent) GridData(org.eclipse.swt.layout.GridData) MessageDialogWithToggle(org.eclipse.jface.dialogs.MessageDialogWithToggle) IPreferenceStore(org.eclipse.jface.preference.IPreferenceStore)

Example 15 with IRunnableContext

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();
}
Also used : IRunnableContext(org.eclipse.jface.operation.IRunnableContext) IRefactoringHistoryService(org.eclipse.ltk.core.refactoring.history.IRefactoringHistoryService) Composite(org.eclipse.swt.widgets.Composite) WizardDialog(org.eclipse.jface.wizard.WizardDialog) InvocationTargetException(java.lang.reflect.InvocationTargetException) CreateRefactoringScriptWizard(org.eclipse.ltk.internal.ui.refactoring.scripting.CreateRefactoringScriptWizard)

Aggregations

IRunnableContext (org.eclipse.jface.operation.IRunnableContext)48 InvocationTargetException (java.lang.reflect.InvocationTargetException)30 CoreException (org.eclipse.core.runtime.CoreException)20 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)16 ArrayList (java.util.ArrayList)12 IStatus (org.eclipse.core.runtime.IStatus)10 JavaModelException (org.eclipse.jdt.core.JavaModelException)10 IRunnableWithProgress (org.eclipse.jface.operation.IRunnableWithProgress)10 ProgressMonitorDialog (org.eclipse.jface.dialogs.ProgressMonitorDialog)9 Shell (org.eclipse.swt.widgets.Shell)9 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)8 BusyIndicatorRunnableContext (org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext)8 PlatformUI (org.eclipse.ui.PlatformUI)7 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)6 Status (org.eclipse.core.runtime.Status)6 IJavaSearchScope (org.eclipse.jdt.core.search.IJavaSearchScope)6 Composite (org.eclipse.swt.widgets.Composite)6 Assert (org.eclipse.core.runtime.Assert)5 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)5 IType (org.eclipse.jdt.core.IType)5