Search in sources :

Example 81 with IncorrectOperationException

use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.

the class PackageChooserDialog method createNewPackage.

private void createNewPackage() {
    final PsiPackage selectedPackage = getTreeSelection();
    if (selectedPackage == null)
        return;
    final String newPackageName = Messages.showInputDialog(myProject, IdeBundle.message("prompt.enter.a.new.package.name"), IdeBundle.message("title.new.package"), Messages.getQuestionIcon(), "", new InputValidator() {

        public boolean checkInput(final String inputString) {
            return inputString != null && inputString.length() > 0;
        }

        public boolean canClose(final String inputString) {
            return checkInput(inputString);
        }
    });
    if (newPackageName == null)
        return;
    CommandProcessor.getInstance().executeCommand(myProject, () -> {
        final Runnable action = () -> {
            try {
                String newQualifiedName = selectedPackage.getQualifiedName();
                if (!Comparing.strEqual(newQualifiedName, ""))
                    newQualifiedName += ".";
                newQualifiedName += newPackageName;
                final PsiDirectory dir = PackageUtil.findOrCreateDirectoryForPackage(myProject, newQualifiedName, null, false);
                if (dir == null)
                    return;
                final PsiPackage newPackage = JavaDirectoryService.getInstance().getPackage(dir);
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) myTree.getSelectionPath().getLastPathComponent();
                final DefaultMutableTreeNode newChild = new DefaultMutableTreeNode();
                newChild.setUserObject(newPackage);
                node.add(newChild);
                final DefaultTreeModel model = (DefaultTreeModel) myTree.getModel();
                model.nodeStructureChanged(node);
                final TreePath selectionPath = myTree.getSelectionPath();
                TreePath path;
                if (selectionPath == null) {
                    path = new TreePath(newChild.getPath());
                } else {
                    path = selectionPath.pathByAddingChild(newChild);
                }
                myTree.setSelectionPath(path);
                myTree.scrollPathToVisible(path);
                myTree.expandPath(path);
            } catch (IncorrectOperationException e) {
                Messages.showMessageDialog(getContentPane(), StringUtil.getMessage(e), CommonBundle.getErrorTitle(), Messages.getErrorIcon());
                if (LOG.isDebugEnabled()) {
                    LOG.debug(e);
                }
            }
        };
        ApplicationManager.getApplication().runReadAction(action);
    }, IdeBundle.message("command.create.new.package"), null);
}
Also used : InputValidator(com.intellij.openapi.ui.InputValidator) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) TreePath(javax.swing.tree.TreePath) IncorrectOperationException(com.intellij.util.IncorrectOperationException) DefaultTreeModel(javax.swing.tree.DefaultTreeModel)

Example 82 with IncorrectOperationException

use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.

the class OverrideImplementMethodAction method actionPerformed.

public final void actionPerformed(final AnActionEvent event) {
    final DataContext dataContext = event.getDataContext();
    final MethodHierarchyBrowser methodHierarchyBrowser = (MethodHierarchyBrowser) MethodHierarchyBrowserBase.DATA_KEY.getData(dataContext);
    if (methodHierarchyBrowser == null)
        return;
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null)
        return;
    final String commandName = event.getPresentation().getText();
    ApplicationManager.getApplication().runWriteAction(() -> CommandProcessor.getInstance().executeCommand(project, () -> {
        try {
            final HierarchyNodeDescriptor[] selectedDescriptors = methodHierarchyBrowser.getSelectedDescriptors();
            if (selectedDescriptors.length > 0) {
                final List<VirtualFile> files = new ArrayList<>(selectedDescriptors.length);
                for (HierarchyNodeDescriptor selectedDescriptor : selectedDescriptors) {
                    final PsiFile containingFile = ((MethodHierarchyNodeDescriptor) selectedDescriptor).getPsiClass().getContainingFile();
                    if (containingFile != null) {
                        final VirtualFile vFile = containingFile.getVirtualFile();
                        if (vFile != null) {
                            files.add(vFile);
                        }
                    }
                }
                final ReadonlyStatusHandler.OperationStatus status = ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(VfsUtil.toVirtualFileArray(files));
                if (!status.hasReadonlyFiles()) {
                    for (HierarchyNodeDescriptor selectedDescriptor : selectedDescriptors) {
                        final PsiElement aClass = ((MethodHierarchyNodeDescriptor) selectedDescriptor).getPsiClass();
                        if (aClass instanceof PsiClass) {
                            OverrideImplementUtil.overrideOrImplement((PsiClass) aClass, methodHierarchyBrowser.getBaseMethod());
                        }
                    }
                    ToolWindowManager.getInstance(project).activateEditorComponent();
                } else {
                    ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(project, status.getReadonlyFilesMessage(), commandName));
                }
            }
        } catch (IncorrectOperationException e) {
            LOG.error(e);
        }
    }, commandName, null));
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Project(com.intellij.openapi.project.Project) ArrayList(java.util.ArrayList) List(java.util.List) IncorrectOperationException(com.intellij.util.IncorrectOperationException) HierarchyNodeDescriptor(com.intellij.ide.hierarchy.HierarchyNodeDescriptor)

Example 83 with IncorrectOperationException

use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.

the class IntroduceVariableBase method introduce.

public static PsiVariable introduce(final Project project, final PsiExpression expr, final Editor editor, final PsiElement anchorStatement, final PsiExpression[] occurrences, final IntroduceVariableSettings settings) {
    final PsiElement container = anchorStatement.getParent();
    PsiElement child = anchorStatement;
    final boolean isInsideLoop = RefactoringUtil.isLoopOrIf(container);
    if (!isInsideLoop) {
        child = locateAnchor(child);
        if (isFinalVariableOnLHS(expr)) {
            child = child.getNextSibling();
        }
    }
    final PsiElement anchor = child == null ? anchorStatement : child;
    boolean tempDeleteSelf = false;
    final boolean replaceSelf = settings.isReplaceLValues() || !RefactoringUtil.isAssignmentLHS(expr);
    final PsiElement exprParent = expr.getParent();
    if (!isInsideLoop) {
        if (exprParent instanceof PsiExpressionStatement && anchor.equals(anchorStatement)) {
            PsiElement parent = exprParent.getParent();
            if (parent instanceof PsiCodeBlock || //fabrique
            parent instanceof PsiCodeFragment) {
                tempDeleteSelf = true;
            }
        }
        tempDeleteSelf &= replaceSelf;
    }
    final boolean deleteSelf = tempDeleteSelf;
    final boolean replaceLoop = isInsideLoop ? exprParent instanceof PsiExpressionStatement : container instanceof PsiLambdaExpression && exprParent == container;
    final int col = editor != null ? editor.getCaretModel().getLogicalPosition().column : 0;
    final int line = editor != null ? editor.getCaretModel().getLogicalPosition().line : 0;
    if (deleteSelf) {
        if (editor != null) {
            LogicalPosition pos = new LogicalPosition(line, col);
            editor.getCaretModel().moveToLogicalPosition(pos);
        }
    }
    final PsiCodeBlock newDeclarationScope = PsiTreeUtil.getParentOfType(container, PsiCodeBlock.class, false);
    final FieldConflictsResolver fieldConflictsResolver = new FieldConflictsResolver(settings.getEnteredName(), newDeclarationScope);
    SmartPsiElementPointer<PsiVariable> pointer = ApplicationManager.getApplication().runWriteAction(new Computable<SmartPsiElementPointer<PsiVariable>>() {

        @Override
        public SmartPsiElementPointer<PsiVariable> compute() {
            try {
                PsiStatement statement = null;
                if (!isInsideLoop && deleteSelf) {
                    statement = (PsiStatement) exprParent;
                }
                final PsiExpression expr1 = fieldConflictsResolver.fixInitializer(expr);
                PsiExpression initializer = RefactoringUtil.unparenthesizeExpression(expr1);
                final SmartTypePointer selectedType = SmartTypePointerManager.getInstance(project).createSmartTypePointer(settings.getSelectedType());
                initializer = simplifyVariableInitializer(initializer, selectedType.getType());
                PsiType type = stripNullabilityAnnotationsFromTargetType(selectedType, project);
                PsiDeclarationStatement declaration = JavaPsiFacade.getInstance(project).getElementFactory().createVariableDeclarationStatement(settings.getEnteredName(), type, initializer, container);
                if (!isInsideLoop) {
                    declaration = addDeclaration(declaration, initializer);
                    LOG.assertTrue(expr1.isValid());
                    if (deleteSelf) {
                        final PsiElement lastChild = statement.getLastChild();
                        if (lastChild instanceof PsiComment) {
                            // keep trailing comment
                            declaration.addBefore(lastChild, null);
                        }
                        statement.delete();
                        if (editor != null) {
                            LogicalPosition pos = new LogicalPosition(line, col);
                            editor.getCaretModel().moveToLogicalPosition(pos);
                            editor.getCaretModel().moveToOffset(declaration.getTextRange().getEndOffset());
                            editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
                            editor.getSelectionModel().removeSelection();
                        }
                    }
                }
                PsiExpression ref = JavaPsiFacade.getInstance(project).getElementFactory().createExpressionFromText(settings.getEnteredName(), null);
                if (settings.isReplaceAllOccurrences()) {
                    ArrayList<PsiElement> array = new ArrayList<>();
                    for (PsiExpression occurrence : occurrences) {
                        if (deleteSelf && occurrence.equals(expr))
                            continue;
                        if (occurrence.equals(expr)) {
                            occurrence = expr1;
                        }
                        if (occurrence != null) {
                            occurrence = RefactoringUtil.outermostParenthesizedExpression(occurrence);
                        }
                        if (settings.isReplaceLValues() || !RefactoringUtil.isAssignmentLHS(occurrence)) {
                            array.add(replace(occurrence, ref, project));
                        }
                    }
                    if (!deleteSelf && replaceSelf && expr1 instanceof PsiPolyadicExpression && expr1.isValid() && !expr1.isPhysical()) {
                        array.add(replace(expr1, ref, project));
                    }
                    if (editor != null) {
                        final PsiElement[] replacedOccurences = PsiUtilCore.toPsiElementArray(array);
                        highlightReplacedOccurences(project, editor, replacedOccurences);
                    }
                } else {
                    if (!deleteSelf && replaceSelf) {
                        replace(expr1, ref, project);
                    }
                }
                declaration = (PsiDeclarationStatement) RefactoringUtil.putStatementInLoopBody(declaration, container, anchorStatement, replaceSelf && replaceLoop);
                declaration = (PsiDeclarationStatement) JavaCodeStyleManager.getInstance(project).shortenClassReferences(declaration);
                PsiVariable var = (PsiVariable) declaration.getDeclaredElements()[0];
                PsiUtil.setModifierProperty(var, PsiModifier.FINAL, settings.isDeclareFinal());
                fieldConflictsResolver.fix();
                return SmartPointerManager.getInstance(project).createSmartPsiElementPointer(var);
            } catch (IncorrectOperationException e) {
                LOG.error(e);
            }
            return null;
        }

        private PsiDeclarationStatement addDeclaration(PsiDeclarationStatement declaration, PsiExpression initializer) {
            if (anchor instanceof PsiDeclarationStatement) {
                final PsiElement[] declaredElements = ((PsiDeclarationStatement) anchor).getDeclaredElements();
                if (declaredElements.length > 1) {
                    final int[] usedFirstVar = new int[] { -1 };
                    initializer.accept(new JavaRecursiveElementWalkingVisitor() {

                        @Override
                        public void visitReferenceExpression(PsiReferenceExpression expression) {
                            final int i = ArrayUtilRt.find(declaredElements, expression.resolve());
                            if (i > -1) {
                                usedFirstVar[0] = Math.max(i, usedFirstVar[0]);
                            }
                            super.visitReferenceExpression(expression);
                        }
                    });
                    if (usedFirstVar[0] > -1) {
                        final PsiVariable psiVariable = (PsiVariable) declaredElements[usedFirstVar[0]];
                        psiVariable.normalizeDeclaration();
                        final PsiDeclarationStatement parDeclarationStatement = PsiTreeUtil.getParentOfType(psiVariable, PsiDeclarationStatement.class);
                        return (PsiDeclarationStatement) container.addAfter(declaration, parDeclarationStatement);
                    }
                }
            }
            return (PsiDeclarationStatement) container.addBefore(declaration, anchor);
        }
    });
    return pointer != null ? pointer.getElement() : null;
}
Also used : FieldConflictsResolver(com.intellij.refactoring.util.FieldConflictsResolver) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 84 with IncorrectOperationException

use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.

the class IntroduceParameterProcessor method performRefactoring.

protected void performRefactoring(@NotNull UsageInfo[] usages) {
    try {
        PsiElementFactory factory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory();
        PsiType initializerType = getInitializerType(myForcedType, myParameterInitializer, myLocalVariable);
        setForcedType(initializerType);
        // Converting myParameterInitializer
        if (myParameterInitializer == null) {
            LOG.assertTrue(myLocalVariable != null);
            myParameterInitializer = factory.createExpressionFromText(myLocalVariable.getName(), myLocalVariable);
        } else if (myParameterInitializer instanceof PsiArrayInitializerExpression) {
            final PsiExpression newExprArrayInitializer = RefactoringUtil.createNewExpressionFromArrayInitializer((PsiArrayInitializerExpression) myParameterInitializer, initializerType);
            myParameterInitializer = (PsiExpression) myParameterInitializer.replace(newExprArrayInitializer);
        }
        myInitializerWrapper = new JavaExpressionWrapper(myParameterInitializer);
        // Changing external occurrences (the tricky part)
        IntroduceParameterUtil.processUsages(usages, this);
        if (myGenerateDelegate) {
            generateDelegate(myMethodToReplaceIn);
            if (myMethodToReplaceIn != myMethodToSearchFor) {
                final PsiMethod method = generateDelegate(myMethodToSearchFor);
                if (method.getContainingClass().isInterface()) {
                    final PsiCodeBlock block = method.getBody();
                    if (block != null) {
                        block.delete();
                    }
                }
            }
        }
        // Changing signature of initial method
        // (signature of myMethodToReplaceIn will be either changed now or have already been changed)
        LOG.assertTrue(initializerType.isValid());
        final FieldConflictsResolver fieldConflictsResolver = new FieldConflictsResolver(myParameterName, myMethodToReplaceIn.getBody());
        IntroduceParameterUtil.changeMethodSignatureAndResolveFieldConflicts(new UsageInfo(myMethodToReplaceIn), usages, this);
        if (myMethodToSearchFor != myMethodToReplaceIn) {
            IntroduceParameterUtil.changeMethodSignatureAndResolveFieldConflicts(new UsageInfo(myMethodToSearchFor), usages, this);
        } else if (myGenerateDelegate && myMethodToReplaceIn.findSuperMethods().length == 0) {
            final PsiAnnotation annotation = AnnotationUtil.findAnnotation(myMethodToReplaceIn, true, Override.class.getName());
            if (annotation != null) {
                annotation.delete();
            }
        }
        ChangeContextUtil.clearContextInfo(myParameterInitializer);
        // Replacing expression occurrences
        for (UsageInfo usage : usages) {
            if (usage instanceof ChangedMethodCallInfo) {
                PsiElement element = usage.getElement();
                processChangedMethodCall(element);
            } else if (usage instanceof InternalUsageInfo) {
                PsiElement element = usage.getElement();
                if (element instanceof PsiExpression) {
                    element = RefactoringUtil.outermostParenthesizedExpression((PsiExpression) element);
                }
                if (element != null) {
                    if (element.getParent() instanceof PsiExpressionStatement) {
                        element.getParent().delete();
                    } else {
                        PsiExpression newExpr = factory.createExpressionFromText(myParameterName, element);
                        IntroduceVariableBase.replace((PsiExpression) element, newExpr, myProject);
                    }
                }
            }
        }
        if (myLocalVariable != null && myRemoveLocalVariable) {
            myLocalVariable.normalizeDeclaration();
            myLocalVariable.getParent().delete();
        }
        fieldConflictsResolver.fix();
    } catch (IncorrectOperationException ex) {
        LOG.error(ex);
    }
    if (isReplaceDuplicates()) {
        ApplicationManager.getApplication().invokeLater(() -> processMethodsDuplicates(), ModalityState.NON_MODAL, myProject.getDisposed());
    }
}
Also used : IncorrectOperationException(com.intellij.util.IncorrectOperationException) UsageInfo(com.intellij.usageView.UsageInfo) NoConstructorClassUsageInfo(com.intellij.refactoring.util.usageInfo.NoConstructorClassUsageInfo) DefaultConstructorImplicitUsageInfo(com.intellij.refactoring.util.usageInfo.DefaultConstructorImplicitUsageInfo)

Example 85 with IncorrectOperationException

use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.

the class JavaIntroduceParameterMethodUsagesProcessor method removeParametersFromCall.

private static void removeParametersFromCall(@NotNull final PsiExpressionList argList, TIntArrayList parametersToRemove, PsiMethod method) {
    final int parametersCount = method.getParameterList().getParametersCount();
    final PsiExpression[] exprs = argList.getExpressions();
    parametersToRemove.forEachDescending(new TIntProcedure() {

        public boolean execute(int paramNum) {
            try {
                //parameter was introduced before varargs
                if (method.isVarArgs() && paramNum == parametersCount - 1) {
                    for (int i = paramNum + 1; i < exprs.length; i++) {
                        exprs[i].delete();
                    }
                } else if (paramNum < exprs.length) {
                    exprs[paramNum].delete();
                }
            } catch (IncorrectOperationException e) {
                LOG.error(e);
            }
            return true;
        }
    });
}
Also used : TIntProcedure(gnu.trove.TIntProcedure) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Aggregations

IncorrectOperationException (com.intellij.util.IncorrectOperationException)485 Project (com.intellij.openapi.project.Project)91 NotNull (org.jetbrains.annotations.NotNull)91 Nullable (org.jetbrains.annotations.Nullable)54 PsiElement (com.intellij.psi.PsiElement)50 TextRange (com.intellij.openapi.util.TextRange)43 VirtualFile (com.intellij.openapi.vfs.VirtualFile)38 Document (com.intellij.openapi.editor.Document)37 ASTNode (com.intellij.lang.ASTNode)35 PsiFile (com.intellij.psi.PsiFile)35 Editor (com.intellij.openapi.editor.Editor)33 NonNls (org.jetbrains.annotations.NonNls)32 UsageInfo (com.intellij.usageView.UsageInfo)31 ArrayList (java.util.ArrayList)31 JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)24 IOException (java.io.IOException)24 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)21 XmlTag (com.intellij.psi.xml.XmlTag)20 CodeStyleManager (com.intellij.psi.codeStyle.CodeStyleManager)19 Module (com.intellij.openapi.module.Module)18