Example usage for com.intellij.openapi.ui DialogWrapper OK_EXIT_CODE

List of usage examples for com.intellij.openapi.ui DialogWrapper OK_EXIT_CODE

Introduction

In this page you can find the example usage for com.intellij.openapi.ui DialogWrapper OK_EXIT_CODE.

Prototype

int OK_EXIT_CODE

To view the source code for com.intellij.openapi.ui DialogWrapper OK_EXIT_CODE.

Click Source Link

Document

The default exit code for "OK" action.

Usage

From source file:com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.java

License:Apache License

@Nullable
public static PsiClass createClass(final PsiJavaCodeReferenceElement referenceElement,
        final CreateClassKind classKind, final String superClassName) {
    assert !ApplicationManager.getApplication().isWriteAccessAllowed();
    final String name = referenceElement.getReferenceName();

    final PsiElement qualifierElement;
    if (referenceElement.getQualifier() instanceof PsiJavaCodeReferenceElement) {
        PsiJavaCodeReferenceElement qualifier = (PsiJavaCodeReferenceElement) referenceElement.getQualifier();
        qualifierElement = qualifier == null ? null : qualifier.resolve();
        if (qualifierElement instanceof PsiClass) {
            return ApplicationManager.getApplication().runWriteAction(new Computable<PsiClass>() {
                @Override/*from   w w  w .  j av a 2  s . co m*/
                public PsiClass compute() {
                    return createClassInQualifier((PsiClass) qualifierElement, classKind, name,
                            referenceElement);
                }
            });
        }
    } else {
        qualifierElement = null;
    }

    final PsiManager manager = referenceElement.getManager();
    final PsiFile sourceFile = referenceElement.getContainingFile();
    final Module module = ModuleUtilCore.findModuleForPsiElement(sourceFile);
    PsiJavaPackage aPackage = findTargetPackage(qualifierElement, manager, sourceFile);
    if (aPackage == null)
        return null;
    final PsiDirectory targetDirectory;
    if (!ApplicationManager.getApplication().isUnitTestMode()) {
        Project project = manager.getProject();
        String title = QuickFixBundle.message("create.class.title",
                StringUtil.capitalize(classKind.getDescription()));

        CreateClassDialog dialog = new CreateClassDialog(project, title, name, aPackage.getQualifiedName(),
                classKind, false, module) {
            @Override
            protected boolean reportBaseInSourceSelectionInTest() {
                return true;
            }
        };
        dialog.show();
        if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE)
            return null;

        targetDirectory = dialog.getTargetDirectory();
        if (targetDirectory == null)
            return null;
    } else {
        targetDirectory = null;
    }
    return createClass(classKind, targetDirectory, name, manager, referenceElement, sourceFile, superClassName);
}

From source file:com.intellij.codeInsight.daemon.impl.quickfix.ModifierFix.java

License:Apache License

@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file,
        @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement,
        @NotNull PsiElement endElement) {
    final PsiModifierList myModifierList = (PsiModifierList) startElement;
    final PsiVariable variable = myVariable == null ? null : myVariable.getElement();
    if (!FileModificationService.getInstance().preparePsiElementForWrite(myModifierList))
        return;/*  w  w  w  . j  a  v  a2 s  . c o  m*/
    final List<PsiModifierList> modifierLists = new ArrayList<PsiModifierList>();
    final PsiFile containingFile = myModifierList.getContainingFile();
    final PsiModifierList modifierList;
    if (variable != null && variable.isValid()) {
        ApplicationManager.getApplication().runWriteAction(new Runnable() {
            @Override
            public void run() {
                try {
                    variable.normalizeDeclaration();
                } catch (IncorrectOperationException e) {
                    LOG.error(e);
                }
            }
        });
        modifierList = variable.getModifierList();
        assert modifierList != null;
    } else {
        modifierList = myModifierList;
    }
    PsiElement owner = modifierList.getParent();
    if (owner instanceof PsiMethod) {
        PsiModifierList copy = (PsiModifierList) myModifierList.copy();
        changeModifierList(copy);
        final int accessLevel = PsiUtil.getAccessLevel(copy);

        OverridingMethodsSearch.search((PsiMethod) owner, owner.getResolveScope(), true)
                .forEach(new PsiElementProcessorAdapter<PsiMethod>(new PsiElementProcessor<PsiMethod>() {
                    @Override
                    public boolean execute(@NotNull PsiMethod inheritor) {
                        PsiModifierList list = inheritor.getModifierList();
                        if (inheritor.getManager().isInProject(inheritor)
                                && PsiUtil.getAccessLevel(list) < accessLevel) {
                            modifierLists.add(list);
                        }
                        return true;
                    }
                }));
    }

    if (!FileModificationService.getInstance().prepareFileForWrite(containingFile))
        return;

    if (!modifierLists.isEmpty()) {
        if (Messages.showYesNoDialog(project,
                QuickFixBundle.message("change.inheritors.visibility.warning.text"),
                QuickFixBundle.message("change.inheritors.visibility.warning.title"),
                Messages.getQuestionIcon()) == DialogWrapper.OK_EXIT_CODE) {
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                @Override
                public void run() {
                    if (!FileModificationService.getInstance().preparePsiElementsForWrite(modifierLists)) {
                        return;
                    }

                    for (final PsiModifierList modifierList : modifierLists) {
                        changeModifierList(modifierList);
                    }
                }
            });
        }
    }

    ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
            changeModifierList(modifierList);
            UndoUtil.markPsiFileForUndo(containingFile);
        }
    });
}

From source file:com.intellij.codeInsight.ExternalAnnotationsManagerImpl.java

License:Apache License

@Override
@NotNull//ww  w . j a  va  2  s .  c om
public AnnotationPlace chooseAnnotationsPlace(@NotNull final PsiElement element) {
    if (!element.isPhysical())
        return AnnotationPlace.IN_CODE; //element just created
    if (!element.getManager().isInProject(element))
        return AnnotationPlace.EXTERNAL;
    final Project project = myPsiManager.getProject();
    final PsiFile containingFile = element.getContainingFile();
    final VirtualFile virtualFile = containingFile.getVirtualFile();
    LOG.assertTrue(virtualFile != null);
    final List<OrderEntry> entries = ProjectRootManager.getInstance(project).getFileIndex()
            .getOrderEntriesForFile(virtualFile);
    if (!entries.isEmpty()) {
        for (OrderEntry entry : entries) {
            if (!(entry instanceof ModuleOrderEntry)) {
                if (entry.getFiles(AnnotationOrderRootType.getInstance()).length > 0) {
                    return AnnotationPlace.EXTERNAL;
                }
                break;
            }
        }
    }
    final MyExternalPromptDialog dialog = ApplicationManager.getApplication().isUnitTestMode()
            || ApplicationManager.getApplication().isHeadlessEnvironment() ? null
                    : new MyExternalPromptDialog(project);
    if (dialog != null && dialog.isToBeShown()) {
        final PsiElement highlightElement = element instanceof PsiNameIdentifierOwner
                ? ((PsiNameIdentifierOwner) element).getNameIdentifier()
                : element.getNavigationElement();
        LOG.assertTrue(highlightElement != null);
        final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        final List<RangeHighlighter> highlighters = new ArrayList<RangeHighlighter>();
        final boolean highlight = editor != null
                && editor.getDocument() == PsiDocumentManager.getInstance(project).getDocument(containingFile);
        try {
            if (highlight) { //do not highlight for batch inspections
                final EditorColorsManager colorsManager = EditorColorsManager.getInstance();
                final TextAttributes attributes = colorsManager.getGlobalScheme()
                        .getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
                final TextRange textRange = highlightElement.getTextRange();
                HighlightManager.getInstance(project).addRangeHighlight(editor, textRange.getStartOffset(),
                        textRange.getEndOffset(), attributes, true, highlighters);
                final LogicalPosition logicalPosition = editor
                        .offsetToLogicalPosition(textRange.getStartOffset());
                editor.getScrollingModel().scrollTo(logicalPosition, ScrollType.CENTER);
            }

            dialog.show();
            if (dialog.getExitCode() == 2) {
                return AnnotationPlace.EXTERNAL;
            } else if (dialog.getExitCode() == 1) {
                return AnnotationPlace.NOWHERE;
            }

        } finally {
            if (highlight) {
                HighlightManager.getInstance(project).removeSegmentHighlighter(editor, highlighters.get(0));
            }
        }
    } else if (dialog != null) {
        dialog.close(DialogWrapper.OK_EXIT_CODE);
    }
    return AnnotationPlace.IN_CODE;
}

From source file:com.intellij.codeInsight.generation.GenerateDelegateHandler.java

License:Apache License

@Nullable
private PsiMethodMember[] chooseMethods(PsiElementClassMember targetMember, PsiFile file, Editor editor,
        Project project) {/*ww  w  .  j ava2s .  co  m*/
    PsiClassType.ClassResolveResult resolveResult = null;
    final PsiDocCommentOwner target = targetMember.getElement();
    if (target instanceof PsiField) {
        resolveResult = PsiUtil.resolveGenericsClassInType(
                targetMember.getSubstitutor().substitute(((PsiField) target).getType()));
    } else if (target instanceof PsiMethod) {
        resolveResult = PsiUtil.resolveGenericsClassInType(
                targetMember.getSubstitutor().substitute(((PsiMethod) target).getReturnType()));
    }

    if (resolveResult == null || resolveResult.getElement() == null)
        return null;
    PsiClass targetClass = resolveResult.getElement();
    PsiSubstitutor substitutor = resolveResult.getSubstitutor();

    int offset = editor.getCaretModel().getOffset();
    PsiElement element = file.findElementAt(offset);
    if (element == null)
        return null;
    PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
    if (aClass == null)
        return null;

    List<PsiMethodMember> methodInstances = new ArrayList<PsiMethodMember>();

    final PsiMethod[] allMethods = targetClass.getAllMethods();
    final Set<MethodSignature> signatures = new HashSet<MethodSignature>();
    final Set<MethodSignature> existingSignatures = new HashSet<MethodSignature>(aClass.getVisibleSignatures());
    final Set<PsiMethodMember> selection = new HashSet<PsiMethodMember>();
    Map<PsiClass, PsiSubstitutor> superSubstitutors = new HashMap<PsiClass, PsiSubstitutor>();
    JavaPsiFacade facade = JavaPsiFacade.getInstance(target.getProject());
    for (PsiMethod method : allMethods) {
        final PsiClass superClass = method.getContainingClass();
        if (CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName()))
            continue;
        if (method.isConstructor())
            continue;
        PsiSubstitutor superSubstitutor = superSubstitutors.get(superClass);
        if (superSubstitutor == null) {
            superSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, targetClass,
                    substitutor);
            superSubstitutors.put(superClass, superSubstitutor);
        }
        PsiSubstitutor methodSubstitutor = OverrideImplementUtil.correctSubstitutor(method, superSubstitutor);
        MethodSignature signature = method.getSignature(methodSubstitutor);
        if (!signatures.contains(signature)) {
            signatures.add(signature);
            if (facade.getResolveHelper().isAccessible(method, target, aClass)) {
                final PsiMethodMember methodMember = new PsiMethodMember(method, methodSubstitutor);
                methodInstances.add(methodMember);
                if (!existingSignatures.contains(signature)) {
                    selection.add(methodMember);
                }
            }
        }
    }

    PsiMethodMember[] result;
    if (!ApplicationManager.getApplication().isUnitTestMode()) {
        MemberChooser<PsiElementClassMember> chooser = new MemberChooser<PsiElementClassMember>(
                methodInstances.toArray(new PsiMethodMember[methodInstances.size()]), false, true, project);
        chooser.setTitle(CodeInsightBundle.message("generate.delegate.method.chooser.title"));
        chooser.setCopyJavadocVisible(true);
        if (!selection.isEmpty()) {
            chooser.selectElements(selection.toArray(new ClassMember[selection.size()]));
        }
        chooser.show();

        if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE)
            return null;

        myToCopyJavaDoc = chooser.isCopyJavadoc();
        final List<PsiElementClassMember> list = chooser.getSelectedElements();
        result = list.toArray(new PsiMethodMember[list.size()]);
    } else {
        result = methodInstances.isEmpty() ? new PsiMethodMember[0]
                : new PsiMethodMember[] { methodInstances.get(0) };
    }

    return result;
}

From source file:com.intellij.codeInsight.generation.GenerateDelegateHandler.java

License:Apache License

@Nullable
private static PsiElementClassMember chooseTarget(PsiFile file, Editor editor, Project project) {
    final PsiElementClassMember[] targetElements = getTargetElements(file, editor);
    if (targetElements == null || targetElements.length == 0)
        return null;
    if (!ApplicationManager.getApplication().isUnitTestMode()) {
        MemberChooser<PsiElementClassMember> chooser = new MemberChooser<PsiElementClassMember>(targetElements,
                false, false, project);//w w  w  . ja v a  2s.  c  o m
        chooser.setTitle(CodeInsightBundle.message("generate.delegate.target.chooser.title"));
        chooser.setCopyJavadocVisible(false);
        chooser.show();

        if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE)
            return null;

        final List<PsiElementClassMember> selectedElements = chooser.getSelectedElements();

        if (selectedElements != null && selectedElements.size() > 0)
            return selectedElements.get(0);
    } else {
        return targetElements[0];
    }
    return null;
}

From source file:com.intellij.codeInsight.generation.GenerateEqualsHandler.java

License:Apache License

@Override
protected ClassMember[] chooseOriginalMembers(PsiClass aClass, Project project, Editor editor) {
    myEqualsFields = null;/* w w w .  ja  v  a  2 s . c o m*/
    myHashCodeFields = null;
    myNonNullFields = PsiField.EMPTY_ARRAY;

    GlobalSearchScope scope = aClass.getResolveScope();
    final PsiMethod equalsMethod = GenerateEqualsHelper.findMethod(aClass,
            GenerateEqualsHelper.getEqualsSignature(project, scope));
    final PsiMethod hashCodeMethod = GenerateEqualsHelper.findMethod(aClass,
            GenerateEqualsHelper.getHashCodeSignature());

    boolean needEquals = equalsMethod == null;
    boolean needHashCode = hashCodeMethod == null;
    if (!needEquals && !needHashCode) {
        String text = aClass instanceof PsiAnonymousClass
                ? CodeInsightBundle.message("generate.equals.and.hashcode.already.defined.warning.anonymous")
                : CodeInsightBundle.message("generate.equals.and.hashcode.already.defined.warning",
                        aClass.getQualifiedName());

        if (Messages.showYesNoDialog(project, text,
                CodeInsightBundle.message("generate.equals.and.hashcode.already.defined.title"),
                Messages.getQuestionIcon()) == DialogWrapper.OK_EXIT_CODE) {
            if (!ApplicationManager.getApplication().runWriteAction(new Computable<Boolean>() {
                @Override
                public Boolean compute() {
                    try {
                        equalsMethod.delete();
                        hashCodeMethod.delete();
                        return Boolean.TRUE;
                    } catch (IncorrectOperationException e) {
                        LOG.error(e);
                        return Boolean.FALSE;
                    }
                }
            }).booleanValue()) {
                return null;
            } else {
                needEquals = needHashCode = true;
            }
        } else {
            return null;
        }
    }
    boolean hasNonStaticFields = false;
    for (PsiField field : aClass.getFields()) {
        if (!field.hasModifierProperty(PsiModifier.STATIC)) {
            hasNonStaticFields = true;
            break;
        }
    }
    if (!hasNonStaticFields) {
        HintManager.getInstance().showErrorHint(editor,
                "No fields to include in equals/hashCode have been found");
        return null;
    }

    GenerateEqualsWizard wizard = new GenerateEqualsWizard(project, aClass, needEquals, needHashCode);
    wizard.show();
    if (!wizard.isOK())
        return null;
    myEqualsFields = wizard.getEqualsFields();
    myHashCodeFields = wizard.getHashCodeFields();
    myNonNullFields = wizard.getNonNullFields();
    return DUMMY_RESULT;
}

From source file:com.intellij.codeInsight.generation.OverrideImplementUtil.java

License:Apache License

@Nullable
public static MemberChooser<PsiMethodMember> showOverrideImplementChooser(Editor editor,
        final PsiElement aClass, final boolean toImplement, Collection<CandidateInfo> candidates,
        Collection<CandidateInfo> secondary) {
    Project project = aClass.getProject();
    if (candidates.isEmpty() && secondary.isEmpty()) {
        return null;
    }//from ww w  .  j ava2 s .  co  m

    final PsiMethodMember[] onlyPrimary = convertToMethodMembers(candidates);
    final PsiMethodMember[] all = ArrayUtil.mergeArrays(onlyPrimary, convertToMethodMembers(secondary));

    final Ref<Boolean> merge = Ref.create(
            PropertiesComponent.getInstance(project).getBoolean(PROP_COMBINED_OVERRIDE_IMPLEMENT, true));
    final MemberChooser<PsiMethodMember> chooser = new MemberChooser<PsiMethodMember>(
            toImplement || merge.get() ? all : onlyPrimary, false, true, project,
            PsiUtil.isLanguageLevel5OrHigher(aClass)) {
        @Override
        protected void fillToolbarActions(DefaultActionGroup group) {
            super.fillToolbarActions(group);
            if (toImplement) {
                return;
            }

            final ToggleAction mergeAction = new ToggleAction("Show methods to implement",
                    "Show methods to implement", AllIcons.General.Show_to_implement) {
                @Override
                public boolean isSelected(AnActionEvent e) {
                    return merge.get().booleanValue();
                }

                @Override
                public void setSelected(AnActionEvent e, boolean state) {
                    merge.set(state);
                    resetElements(state ? all : onlyPrimary);
                    setTitle(getChooserTitle(false, merge));
                }
            };
            mergeAction.registerCustomShortcutSet(
                    new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.ALT_MASK)), myTree);

            Shortcut[] shortcuts = KeymapManager.getInstance().getActiveKeymap()
                    .getShortcuts("OverrideMethods");
            mergeAction.registerCustomShortcutSet(new CustomShortcutSet(shortcuts), myTree);

            group.add(mergeAction);
        }
    };
    chooser.setTitle(getChooserTitle(toImplement, merge));
    registerHandlerForComplementaryAction(project, editor, aClass, toImplement, chooser);

    chooser.setCopyJavadocVisible(true);

    if (toImplement) {
        chooser.selectElements(onlyPrimary);
    }

    if (ApplicationManager.getApplication().isUnitTestMode()) {
        if (!toImplement || onlyPrimary.length == 0) {
            chooser.selectElements(all);
        }
        chooser.close(DialogWrapper.OK_EXIT_CODE);
        return chooser;
    }

    chooser.show();
    if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE) {
        return null;
    }

    PropertiesComponent.getInstance(project).setValue(PROP_COMBINED_OVERRIDE_IMPLEMENT, merge.get().toString());
    return chooser;
}

From source file:com.intellij.codeInsight.intention.impl.BindFieldsFromParametersAction.java

License:Apache License

@NotNull
private static Iterable<PsiParameter> selectParameters(@NotNull Project project, @NotNull PsiMethod method,
        @NotNull Collection<SmartPsiElementPointer<PsiParameter>> unboundedParams, boolean isInteractive) {
    if (unboundedParams.size() < 2 || !isInteractive) {
        return revealPointers(unboundedParams);
    }/*from www .j  a  v  a2  s .  co  m*/

    final ParameterClassMember[] members = sortByParameterIndex(toClassMemberArray(unboundedParams), method);

    final MemberChooser<ParameterClassMember> chooser = showChooser(project, method, members);

    final List<ParameterClassMember> selectedElements = chooser.getSelectedElements();
    if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE || selectedElements == null) {
        return Collections.emptyList();
    }

    return revealParameterClassMembers(selectedElements);
}

From source file:com.intellij.codeInspection.inferNullity.InferNullityAnnotationsAction.java

License:Apache License

@Override
protected void analyze(@NotNull final Project project, final AnalysisScope scope) {
    final ProgressManager progressManager = ProgressManager.getInstance();
    final int totalFiles = scope.getFileCount();

    final Set<Module> modulesWithoutAnnotations = new HashSet<Module>();
    final Set<Module> modulesWithLL = new HashSet<Module>();
    if (!progressManager.runProcessWithProgressSynchronously(new Runnable() {
        @Override/*from ww  w  .j  a  v a  2s .co  m*/
        public void run() {

            scope.accept(new PsiElementVisitor() {
                private int myFileCount = 0;
                final private Set<Module> processed = new HashSet<Module>();

                @Override
                public void visitFile(PsiFile file) {
                    myFileCount++;
                    final ProgressIndicator progressIndicator = ProgressManager.getInstance()
                            .getProgressIndicator();
                    if (progressIndicator != null) {
                        final VirtualFile virtualFile = file.getVirtualFile();
                        if (virtualFile != null) {
                            progressIndicator
                                    .setText2(ProjectUtil.calcRelativeToProjectPath(virtualFile, project));
                        }
                        progressIndicator.setFraction(((double) myFileCount) / totalFiles);
                    }
                    final Module module = ModuleUtil.findModuleForPsiElement(file);
                    if (module != null && !processed.contains(module)) {
                        processed.add(module);
                        if (JavaPsiFacade.getInstance(project).findClass(
                                NullableNotNullManager.getInstance(project).getDefaultNullable(),
                                GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module)) == null) {
                            modulesWithoutAnnotations.add(module);
                        }
                        if (PsiUtil.getLanguageLevel(file).compareTo(LanguageLevel.JDK_1_5) < 0) {
                            modulesWithLL.add(module);
                        }
                    }
                }
            });
        }
    }, "Check applicability...", true, project)) {
        return;
    }
    if (!modulesWithLL.isEmpty()) {
        Messages.showErrorDialog(project,
                "Infer Nullity Annotations requires the project language level be set to 1.5 or greater.",
                INFER_NULLITY_ANNOTATIONS);
        return;
    }
    if (!modulesWithoutAnnotations.isEmpty()) {
        final Library annotationsLib = LibraryUtil
                .findLibraryByClass(NullableNotNullManager.getInstance(project).getDefaultNullable(), project);
        if (annotationsLib != null) {
            String message = "Module" + (modulesWithoutAnnotations.size() == 1 ? " " : "s ");
            message += StringUtil.join(modulesWithoutAnnotations, new Function<Module, String>() {
                @Override
                public String fun(Module module) {
                    return module.getName();
                }
            }, ", ");
            message += (modulesWithoutAnnotations.size() == 1 ? " doesn't" : " don't");
            message += " refer to the existing '" + annotationsLib.getName()
                    + "' library with IDEA nullity annotations. Would you like to add the dependenc";
            message += (modulesWithoutAnnotations.size() == 1 ? "y" : "ies") + " now?";
            if (Messages.showOkCancelDialog(project, message, INFER_NULLITY_ANNOTATIONS,
                    Messages.getErrorIcon()) == DialogWrapper.OK_EXIT_CODE) {
                ApplicationManager.getApplication().runWriteAction(new Runnable() {
                    @Override
                    public void run() {
                        for (Module module : modulesWithoutAnnotations) {
                            ModuleRootModificationUtil.addDependency(module, annotationsLib);
                        }
                    }
                });
            }
        } else if (Messages.showOkCancelDialog(project,
                "Infer Nullity Annotations requires that the nullity annotations"
                        + " be available in all your project sources.\n\nYou will need to add annotations.jar as a library. "
                        + "It is possible to configure custom jar in e.g. Constant Conditions & Exceptions inspection or use JetBrains annotations available in installation. "
                        + " IntelliJ IDEA nullity annotations are freely usable and redistributable under the Apache 2.0 license. Would you like to do it now?",
                INFER_NULLITY_ANNOTATIONS, Messages.getErrorIcon()) == DialogWrapper.OK_EXIT_CODE) {
            ApplicationManager.getApplication().invokeLater(new Runnable() {
                @Override
                public void run() {
                    final LocateLibraryDialog dialog = new LocateLibraryDialog(
                            modulesWithoutAnnotations.iterator().next(), PathManager.getLibPath(),
                            "annotations.jar", QuickFixBundle.message("add.library.annotations.description"));
                    dialog.show();
                    if (dialog.isOK()) {
                        final String path = dialog.getResultingLibraryPath();
                        new WriteCommandAction(project) {
                            @Override
                            protected void run(final Result result) throws Throwable {
                                for (Module module : modulesWithoutAnnotations) {
                                    OrderEntryFix.addBundledJarToRoots(project, null, module, null,
                                            AnnotationUtil.NOT_NULL, path);
                                }
                            }
                        }.execute();
                    }
                }
            });
        }
        return;
    }
    if (scope.checkScopeWritable(project))
        return;
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    final NullityInferrer inferrer = new NullityInferrer(myAnnotateLocalVariablesCb.isSelected(), project);
    final PsiManager psiManager = PsiManager.getInstance(project);
    if (!progressManager.runProcessWithProgressSynchronously(new Runnable() {
        @Override
        public void run() {
            scope.accept(new PsiElementVisitor() {
                int myFileCount = 0;

                @Override
                public void visitFile(final PsiFile file) {
                    myFileCount++;
                    final VirtualFile virtualFile = file.getVirtualFile();
                    final FileViewProvider viewProvider = psiManager.findViewProvider(virtualFile);
                    final Document document = viewProvider == null ? null : viewProvider.getDocument();
                    if (document == null || virtualFile.getFileType().isBinary())
                        return; //do not inspect binary files
                    final ProgressIndicator progressIndicator = ProgressManager.getInstance()
                            .getProgressIndicator();
                    if (progressIndicator != null) {
                        if (virtualFile != null) {
                            progressIndicator
                                    .setText2(ProjectUtil.calcRelativeToProjectPath(virtualFile, project));
                        }
                        progressIndicator.setFraction(((double) myFileCount) / totalFiles);
                    }
                    if (file instanceof PsiJavaFile) {
                        inferrer.collect(file);
                    }
                }
            });
        }
    }, INFER_NULLITY_ANNOTATIONS, true, project)) {
        return;
    }

    final Runnable applyRunnable = new Runnable() {
        @Override
        public void run() {
            new WriteCommandAction(project, INFER_NULLITY_ANNOTATIONS) {
                @Override
                protected void run(Result result) throws Throwable {
                    if (!inferrer.nothingFoundMessage(project)) {
                        final SequentialModalProgressTask progressTask = new SequentialModalProgressTask(
                                project, INFER_NULLITY_ANNOTATIONS, false);
                        progressTask.setMinIterationTime(200);
                        progressTask.setTask(new AnnotateTask(project, inferrer, progressTask));
                        ProgressManager.getInstance().run(progressTask);
                    }
                }
            }.execute();
        }
    };
    SwingUtilities.invokeLater(applyRunnable);
}

From source file:com.intellij.debugger.actions.AdjustArrayRangeAction.java

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    DebuggerContextImpl debuggerContext = DebuggerAction.getDebuggerContext(e.getDataContext());
    if (debuggerContext == null) {
        return;//from ww w  . ja va2  s  .co  m
    }

    DebugProcessImpl debugProcess = debuggerContext.getDebugProcess();
    if (debugProcess == null) {
        return;
    }

    final Project project = debuggerContext.getProject();

    final DebuggerTreeNodeImpl selectedNode = getSelectedNode(e.getDataContext());
    if (selectedNode == null) {
        return;
    }
    NodeDescriptorImpl descriptor = selectedNode.getDescriptor();
    if (!(descriptor instanceof ValueDescriptorImpl /*&& ((ValueDescriptorImpl)descriptor).isArray()*/)) {
        return;
    }

    final ArrayRenderer renderer = getArrayRenderer(
            (ValueDescriptorImpl) descriptor)/*(ArrayRenderer)((ValueDescriptorImpl)selectedNode
                                             .getDescriptor()).getLastRenderer()*/;
    if (renderer == null) {
        return;
    }

    String title = createNodeTitle("", selectedNode);
    String label = selectedNode.toString();
    int index = label.indexOf('=');
    if (index > 0) {
        title = title + " " + label.substring(index);
    }
    final ArrayRenderer clonedRenderer = renderer.clone();
    final NamedArrayConfigurable configurable = new NamedArrayConfigurable(title, clonedRenderer);
    SingleConfigurableEditor editor = new SingleConfigurableEditor(project, configurable,
            ShowSettingsUtilImpl.createDimensionKey(configurable), false);
    editor.show();

    if (editor.getExitCode() == DialogWrapper.OK_EXIT_CODE) {
        debugProcess.getManagerThread()
                .schedule(new SuspendContextCommandImpl(debuggerContext.getSuspendContext()) {
                    @Override
                    public void contextAction() throws Exception {
                        final ValueDescriptorImpl nodeDescriptor = (ValueDescriptorImpl) selectedNode
                                .getDescriptor();
                        final Renderer lastRenderer = nodeDescriptor.getLastRenderer();
                        if (lastRenderer instanceof ArrayRenderer) {
                            selectedNode.setRenderer(clonedRenderer);
                        } else if (lastRenderer instanceof CompoundNodeRenderer) {
                            final CompoundNodeRenderer compoundRenderer = (CompoundNodeRenderer) lastRenderer;
                            final ChildrenRenderer childrenRenderer = compoundRenderer.getChildrenRenderer();
                            if (childrenRenderer instanceof ExpressionChildrenRenderer) {
                                ExpressionChildrenRenderer.setPreferableChildrenRenderer(nodeDescriptor,
                                        clonedRenderer);
                                selectedNode.calcRepresentation();
                            }
                        }
                    }
                });
    }
}