Search in sources :

Example 36 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project intellij-community by JetBrains.

the class ExpandStaticImportAction method invoke.

public void invoke(final Project project, final PsiFile file, final Editor editor, PsiElement element) {
    final PsiJavaCodeReferenceElement refExpr = (PsiJavaCodeReferenceElement) element.getParent();
    final PsiImportStaticStatement staticImport = (PsiImportStaticStatement) getImportStaticStatement(refExpr);
    final List<PsiJavaCodeReferenceElement> expressionToExpand = collectReferencesThrough(file, refExpr, staticImport);
    if (expressionToExpand.isEmpty()) {
        expand(refExpr, staticImport);
        staticImport.delete();
    } else {
        if (ApplicationManager.getApplication().isUnitTestMode() || refExpr instanceof PsiImportStaticReferenceElement) {
            replaceAllAndDeleteImport(expressionToExpand, refExpr, staticImport);
        } else {
            final BaseListPopupStep<String> step = new BaseListPopupStep<String>("Multiple Usages of the Static Import Found", REPLACE_THIS_OCCURRENCE, REPLACE_ALL_AND_DELETE_IMPORT) {

                @Override
                public PopupStep onChosen(final String selectedValue, boolean finalChoice) {
                    new WriteCommandAction(project, ExpandStaticImportAction.this.getText()) {

                        @Override
                        protected void run(@NotNull Result result) throws Throwable {
                            if (selectedValue == REPLACE_THIS_OCCURRENCE) {
                                expand(refExpr, staticImport);
                            } else {
                                replaceAllAndDeleteImport(expressionToExpand, refExpr, staticImport);
                            }
                        }
                    }.execute();
                    return FINAL_CHOICE;
                }
            };
            JBPopupFactory.getInstance().createListPopup(step).showInBestPositionFor(editor);
        }
    }
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) BaseListPopupStep(com.intellij.openapi.ui.popup.util.BaseListPopupStep) Result(com.intellij.openapi.application.Result)

Example 37 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project intellij-community by JetBrains.

the class InlineParameterHandler method inlineElement.

public void inlineElement(final Project project, final Editor editor, final PsiElement psiElement) {
    final PsiParameter psiParameter = (PsiParameter) psiElement;
    final PsiParameterList parameterList = (PsiParameterList) psiParameter.getParent();
    if (!(parameterList.getParent() instanceof PsiMethod)) {
        return;
    }
    final int index = parameterList.getParameterIndex(psiParameter);
    final PsiMethod method = (PsiMethod) parameterList.getParent();
    String errorMessage = getCannotInlineMessage(psiParameter, method);
    if (errorMessage != null) {
        CommonRefactoringUtil.showErrorHint(project, editor, errorMessage, RefactoringBundle.message("inline.parameter.refactoring"), null);
        return;
    }
    final Ref<PsiExpression> refInitializer = new Ref<>();
    final Ref<PsiExpression> refConstantInitializer = new Ref<>();
    final Ref<PsiCallExpression> refMethodCall = new Ref<>();
    final List<PsiReference> occurrences = Collections.synchronizedList(new ArrayList<PsiReference>());
    final Collection<PsiFile> containingFiles = Collections.synchronizedSet(new HashSet<PsiFile>());
    containingFiles.add(psiParameter.getContainingFile());
    boolean[] result = new boolean[1];
    if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> {
        result[0] = ReferencesSearch.search(method).forEach(psiReference -> {
            PsiElement element = psiReference.getElement();
            final PsiElement parent = element.getParent();
            if (parent instanceof PsiCallExpression) {
                final PsiCallExpression methodCall = (PsiCallExpression) parent;
                occurrences.add(psiReference);
                containingFiles.add(element.getContainingFile());
                final PsiExpression[] expressions = methodCall.getArgumentList().getExpressions();
                if (expressions.length <= index)
                    return false;
                PsiExpression argument = expressions[index];
                if (!refInitializer.isNull()) {
                    return argument != null && PsiEquivalenceUtil.areElementsEquivalent(refInitializer.get(), argument) && PsiEquivalenceUtil.areElementsEquivalent(refMethodCall.get(), methodCall);
                }
                if (InlineToAnonymousConstructorProcessor.isConstant(argument) || getReferencedFinalField(argument) != null) {
                    if (refConstantInitializer.isNull()) {
                        refConstantInitializer.set(argument);
                    } else if (!isSameConstant(argument, refConstantInitializer.get())) {
                        return false;
                    }
                } else if (!isRecursiveReferencedParameter(argument, psiParameter)) {
                    if (!refConstantInitializer.isNull())
                        return false;
                    refInitializer.set(argument);
                    refMethodCall.set(methodCall);
                }
            }
            return true;
        });
    }, "Searching for Method Usages", true, project)) {
        return;
    }
    final PsiReference reference = TargetElementUtil.findReference(editor);
    final PsiReferenceExpression refExpr = reference instanceof PsiReferenceExpression ? ((PsiReferenceExpression) reference) : null;
    final PsiCodeBlock codeBlock = PsiTreeUtil.getParentOfType(refExpr, PsiCodeBlock.class);
    if (codeBlock != null) {
        final PsiElement[] defs = DefUseUtil.getDefs(codeBlock, psiParameter, refExpr);
        if (defs.length == 1) {
            final PsiElement def = defs[0];
            if (def instanceof PsiReferenceExpression && PsiUtil.isOnAssignmentLeftHand((PsiExpression) def)) {
                final PsiExpression rExpr = ((PsiAssignmentExpression) def.getParent()).getRExpression();
                if (rExpr != null) {
                    PsiExpression toInline = InlineLocalHandler.getDefToInline(psiParameter, refExpr, codeBlock);
                    if (toInline != null) {
                        final PsiElement[] refs = DefUseUtil.getRefs(codeBlock, psiParameter, toInline);
                        if (InlineLocalHandler.checkRefsInAugmentedAssignmentOrUnaryModified(refs, def) == null) {
                            new WriteCommandAction(project) {

                                @Override
                                protected void run(@NotNull Result result) throws Throwable {
                                    for (final PsiElement ref : refs) {
                                        InlineUtil.inlineVariable(psiParameter, rExpr, (PsiJavaCodeReferenceElement) ref);
                                    }
                                    def.getParent().delete();
                                }
                            }.execute();
                            return;
                        }
                    }
                }
            }
        }
    }
    if (occurrences.isEmpty()) {
        CommonRefactoringUtil.showErrorHint(project, editor, "Method has no usages", RefactoringBundle.message("inline.parameter.refactoring"), null);
        return;
    }
    if (!result[0]) {
        CommonRefactoringUtil.showErrorHint(project, editor, "Cannot find constant initializer for parameter", RefactoringBundle.message("inline.parameter.refactoring"), null);
        return;
    }
    if (!refInitializer.isNull()) {
        if (ApplicationManager.getApplication().isUnitTestMode()) {
            final InlineParameterExpressionProcessor processor = new InlineParameterExpressionProcessor(refMethodCall.get(), method, psiParameter, refInitializer.get(), method.getProject().getUserData(InlineParameterExpressionProcessor.CREATE_LOCAL_FOR_TESTS));
            processor.run();
        } else {
            final boolean createLocal = ReferencesSearch.search(psiParameter).findAll().size() > 1;
            InlineParameterDialog dlg = new InlineParameterDialog(refMethodCall.get(), method, psiParameter, refInitializer.get(), createLocal);
            dlg.show();
        }
        return;
    }
    if (refConstantInitializer.isNull()) {
        CommonRefactoringUtil.showErrorHint(project, editor, "Cannot find constant initializer for parameter", RefactoringBundle.message("inline.parameter.refactoring"), null);
        return;
    }
    final Ref<Boolean> isNotConstantAccessible = new Ref<>();
    final PsiExpression constantExpression = refConstantInitializer.get();
    constantExpression.accept(new JavaRecursiveElementVisitor() {

        @Override
        public void visitReferenceExpression(PsiReferenceExpression expression) {
            super.visitReferenceExpression(expression);
            final PsiElement resolved = expression.resolve();
            if (resolved instanceof PsiMember && !PsiUtil.isAccessible((PsiMember) resolved, method, null)) {
                isNotConstantAccessible.set(Boolean.TRUE);
            }
        }
    });
    if (!isNotConstantAccessible.isNull() && isNotConstantAccessible.get()) {
        CommonRefactoringUtil.showErrorHint(project, editor, "Constant initializer is not accessible in method body", RefactoringBundle.message("inline.parameter.refactoring"), null);
        return;
    }
    for (PsiReference psiReference : ReferencesSearch.search(psiParameter)) {
        final PsiElement element = psiReference.getElement();
        if (element instanceof PsiExpression && PsiUtil.isAccessedForWriting((PsiExpression) element)) {
            CommonRefactoringUtil.showErrorHint(project, editor, "Inline parameter which has write usages is not supported", RefactoringBundle.message("inline.parameter.refactoring"), null);
            return;
        }
    }
    if (!ApplicationManager.getApplication().isUnitTestMode()) {
        String occurencesString = RefactoringBundle.message("occurrences.string", occurrences.size());
        String question = RefactoringBundle.message("inline.parameter.confirmation", psiParameter.getName(), constantExpression.getText()) + " " + occurencesString;
        RefactoringMessageDialog dialog = new RefactoringMessageDialog(REFACTORING_NAME, question, HelpID.INLINE_VARIABLE, "OptionPane.questionIcon", true, project);
        if (!dialog.showAndGet()) {
            return;
        }
    }
    final RefactoringEventData data = new RefactoringEventData();
    data.addElement(psiElement.copy());
    CommandProcessor.getInstance().executeCommand(project, () -> {
        project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(REFACTORING_ID, data);
        SameParameterValueInspection.InlineParameterValueFix.inlineSameParameterValue(method, psiParameter, constantExpression);
        project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(REFACTORING_ID, null);
    }, REFACTORING_NAME, null);
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) Result(com.intellij.openapi.application.Result) RefactoringEventData(com.intellij.refactoring.listeners.RefactoringEventData) RefactoringMessageDialog(com.intellij.refactoring.util.RefactoringMessageDialog) Ref(com.intellij.openapi.util.Ref)

Example 38 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project intellij-community by JetBrains.

the class InplaceIntroduceFieldPopup method performIntroduce.

protected void performIntroduce() {
    ourLastInitializerPlace = myIntroduceFieldPanel.getInitializerPlace();
    final PsiType forcedType = getType();
    LOG.assertTrue(forcedType == null || forcedType.isValid(), forcedType);
    final BaseExpressionToFieldHandler.Settings settings = new BaseExpressionToFieldHandler.Settings(getInputName(), getExpr(), getOccurrences(), myIntroduceFieldPanel.isReplaceAllOccurrences(), myStatic, myIntroduceFieldPanel.isDeclareFinal(), myIntroduceFieldPanel.getInitializerPlace(), myIntroduceFieldPanel.getFieldVisibility(), (PsiLocalVariable) getLocalVariable(), forcedType, myIntroduceFieldPanel.isDeleteVariable(), getParentClass(), false, false);
    new WriteCommandAction(myProject, getCommandName(), getCommandName()) {

        @Override
        protected void run(@NotNull Result result) throws Throwable {
            if (getLocalVariable() != null) {
                final LocalToFieldHandler.IntroduceFieldRunnable fieldRunnable = new LocalToFieldHandler.IntroduceFieldRunnable(false, (PsiLocalVariable) getLocalVariable(), getParentClass(), settings, myStatic, myOccurrences);
                fieldRunnable.run();
            } else {
                final BaseExpressionToFieldHandler.ConvertToFieldRunnable convertToFieldRunnable = new BaseExpressionToFieldHandler.ConvertToFieldRunnable(myExpr, settings, settings.getForcedType(), myOccurrences, myOccurrenceManager, getAnchorElementIfAll(), getAnchorElement(), myEditor, getParentClass());
                convertToFieldRunnable.run();
            }
        }
    }.execute();
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) Result(com.intellij.openapi.application.Result) JavaRefactoringSettings(com.intellij.refactoring.JavaRefactoringSettings)

Example 39 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project intellij-community by JetBrains.

the class FindUsagesTest method testNonCodeClassUsages.

public void testNonCodeClassUsages() throws Exception {
    final TempDirTestFixture tdf = IdeaTestFixtureFactory.getFixtureFactory().createTempDirTestFixture();
    tdf.setUp();
    try {
        new WriteCommandAction(getProject()) {

            @Override
            protected void run(@NotNull Result result) throws Throwable {
                final ModifiableModuleModel moduleModel = ModuleManager.getInstance(getProject()).getModifiableModel();
                moduleModel.newModule("independent/independent.iml", StdModuleTypes.JAVA.getId());
                moduleModel.commit();
                tdf.createFile("plugin.xml", "<document>\n" + "  <action class=\"com.Foo\" />\n" + "  <action class=\"com.Foo.Bar\" />\n" + "  <action class=\"com.Foo$Bar\" />\n" + "</document>");
                PsiTestUtil.addContentRoot(ModuleManager.getInstance(getProject()).findModuleByName("independent"), tdf.getFile(""));
            }
        }.execute();
        GlobalSearchScope scope = GlobalSearchScope.allScope(getProject());
        PsiClass foo = myJavaFacade.findClass("com.Foo", scope);
        PsiClass bar = myJavaFacade.findClass("com.Foo.Bar", scope);
        final int[] count = { 0 };
        Processor<UsageInfo> processor = usageInfo -> {
            int navigationOffset = usageInfo.getNavigationOffset();
            assertTrue(navigationOffset > 0);
            String textAfter = usageInfo.getFile().getText().substring(navigationOffset);
            assertTrue(textAfter, textAfter.startsWith("Foo") || textAfter.startsWith("Bar") || textAfter.startsWith("com.Foo.Bar"));
            count[0]++;
            return true;
        };
        JavaFindUsagesHandler handler = new JavaFindUsagesHandler(bar, JavaFindUsagesHandlerFactory.getInstance(getProject()));
        count[0] = 0;
        handler.processUsagesInText(foo, processor, scope);
        assertEquals(3, count[0]);
        count[0] = 0;
        handler.processUsagesInText(bar, processor, scope);
        assertEquals(2, count[0]);
    } finally {
        tdf.tearDown();
    }
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) TempDirTestFixture(com.intellij.testFramework.fixtures.TempDirTestFixture) ModuleManager(com.intellij.openapi.module.ModuleManager) JavaFindUsagesHandlerFactory(com.intellij.find.findUsages.JavaFindUsagesHandlerFactory) UsageInfo(com.intellij.usageView.UsageInfo) IntArrayList(com.intellij.util.containers.IntArrayList) ArrayList(java.util.ArrayList) MethodReferencesSearch(com.intellij.psi.search.searches.MethodReferencesSearch) WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) IdeaTestUtil(com.intellij.testFramework.IdeaTestUtil) PsiTestCase(com.intellij.testFramework.PsiTestCase) ReferencesSearch(com.intellij.psi.search.searches.ReferencesSearch) StdModuleTypes(com.intellij.openapi.module.StdModuleTypes) StdFileTypes(com.intellij.openapi.fileTypes.StdFileTypes) PsiTestUtil(com.intellij.testFramework.PsiTestUtil) JavaTestUtil(com.intellij.JavaTestUtil) OverridingMethodsSearch(com.intellij.psi.search.searches.OverridingMethodsSearch) Collection(java.util.Collection) TextRange(com.intellij.openapi.util.TextRange) ModifiableModuleModel(com.intellij.openapi.module.ModifiableModuleModel) JavaFindUsagesHandler(com.intellij.find.findUsages.JavaFindUsagesHandler) List(java.util.List) Result(com.intellij.openapi.application.Result) Processor(com.intellij.util.Processor) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) IdeaTestFixtureFactory(com.intellij.testFramework.fixtures.IdeaTestFixtureFactory) Collections(java.util.Collections) TempDirTestFixture(com.intellij.testFramework.fixtures.TempDirTestFixture) JavaFindUsagesHandler(com.intellij.find.findUsages.JavaFindUsagesHandler) Result(com.intellij.openapi.application.Result) ModifiableModuleModel(com.intellij.openapi.module.ModifiableModuleModel) UsageInfo(com.intellij.usageView.UsageInfo)

Example 40 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project intellij-community by JetBrains.

the class CreateParameterFromUsageFix method invokeImpl.

@Override
protected void invokeImpl(PsiClass targetClass) {
    TransactionGuard.getInstance().submitTransactionLater(targetClass.getProject(), () -> {
        if (!myReferenceExpression.isValid())
            return;
        if (CreateFromUsageUtils.isValidReference(myReferenceExpression, false))
            return;
        final Project project = myReferenceExpression.getProject();
        PsiType[] expectedTypes = CreateFromUsageUtils.guessType(myReferenceExpression, false);
        PsiType type = expectedTypes[0];
        final String varName = myReferenceExpression.getReferenceName();
        PsiMethod method = PsiTreeUtil.getParentOfType(myReferenceExpression, PsiMethod.class);
        LOG.assertTrue(method != null);
        method = IntroduceParameterHandler.chooseEnclosingMethod(method);
        if (method == null)
            return;
        method = SuperMethodWarningUtil.checkSuperMethod(method, RefactoringBundle.message("to.refactor"));
        if (method == null)
            return;
        final List<ParameterInfoImpl> parameterInfos = new ArrayList<>(Arrays.asList(ParameterInfoImpl.fromMethod(method)));
        ParameterInfoImpl parameterInfo = new ParameterInfoImpl(-1, varName, type, varName, false);
        if (!method.isVarArgs()) {
            parameterInfos.add(parameterInfo);
        } else {
            parameterInfos.add(parameterInfos.size() - 1, parameterInfo);
        }
        if (ApplicationManager.getApplication().isUnitTestMode()) {
            ParameterInfoImpl[] array = parameterInfos.toArray(new ParameterInfoImpl[parameterInfos.size()]);
            String modifier = PsiUtil.getAccessModifier(PsiUtil.getAccessLevel(method.getModifierList()));
            ChangeSignatureProcessor processor = new ChangeSignatureProcessor(project, method, false, modifier, method.getName(), method.getReturnType(), array);
            processor.run();
        } else {
            try {
                JavaChangeSignatureDialog dialog = JavaChangeSignatureDialog.createAndPreselectNew(project, method, parameterInfos, true, myReferenceExpression);
                dialog.setParameterInfos(parameterInfos);
                if (dialog.showAndGet()) {
                    for (ParameterInfoImpl info : parameterInfos) {
                        if (info.getOldIndex() == -1) {
                            final String newParamName = info.getName();
                            if (!Comparing.strEqual(varName, newParamName)) {
                                final PsiExpression newExpr = JavaPsiFacade.getElementFactory(project).createExpressionFromText(newParamName, method);
                                new WriteCommandAction(project) {

                                    @Override
                                    protected void run(@NotNull Result result) throws Throwable {
                                        final PsiReferenceExpression[] refs = CreateFromUsageUtils.collectExpressions(myReferenceExpression, PsiMember.class, PsiFile.class);
                                        for (PsiReferenceExpression ref : refs) {
                                            ref.replace(newExpr.copy());
                                        }
                                    }
                                }.execute();
                            }
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    });
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) ArrayList(java.util.ArrayList) ParameterInfoImpl(com.intellij.refactoring.changeSignature.ParameterInfoImpl) Result(com.intellij.openapi.application.Result) Project(com.intellij.openapi.project.Project) JavaChangeSignatureDialog(com.intellij.refactoring.changeSignature.JavaChangeSignatureDialog) ChangeSignatureProcessor(com.intellij.refactoring.changeSignature.ChangeSignatureProcessor)

Aggregations

WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)176 Result (com.intellij.openapi.application.Result)175 NotNull (org.jetbrains.annotations.NotNull)62 Project (com.intellij.openapi.project.Project)45 VirtualFile (com.intellij.openapi.vfs.VirtualFile)29 XmlFile (com.intellij.psi.xml.XmlFile)28 XmlTag (com.intellij.psi.xml.XmlTag)23 Document (com.intellij.openapi.editor.Document)22 PsiFile (com.intellij.psi.PsiFile)16 Module (com.intellij.openapi.module.Module)14 Nullable (org.jetbrains.annotations.Nullable)12 NlModel (com.android.tools.idea.uibuilder.model.NlModel)11 AttributesTransaction (com.android.tools.idea.uibuilder.model.AttributesTransaction)10 Editor (com.intellij.openapi.editor.Editor)10 TextRange (com.intellij.openapi.util.TextRange)8 XmlAttribute (com.intellij.psi.xml.XmlAttribute)8 File (java.io.File)8 IOException (java.io.IOException)8 ArrayList (java.util.ArrayList)8 GradleBuildModel (com.android.tools.idea.gradle.dsl.model.GradleBuildModel)7