Search in sources :

Example 56 with IncorrectOperationException

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

the class ImportToggleAliasIntention method doInvoke.

@Override
public void doInvoke(@NotNull final Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    // sanity check: isAvailable must have set it.
    final IntentionState state = IntentionState.fromContext(editor, file);
    //
    // we set in in the source
    final String target_name;
    // we replace it in the source
    final String remove_name;
    PyReferenceExpression reference = sure(state.myImportElement.getImportReferenceExpression());
    // search for references to us with the right name
    try {
        String imported_name = PyPsiUtils.toPath(reference);
        if (state.myAlias != null) {
            // have to remove alias, rename everything to original
            target_name = imported_name;
            remove_name = state.myAlias;
        } else {
            // ask for and add alias
            Application application = ApplicationManager.getApplication();
            if (application != null && !application.isUnitTestMode()) {
                String alias = Messages.showInputDialog(project, PyBundle.message("INTN.alias.for.$0.dialog.title", imported_name), "Add Alias", Messages.getQuestionIcon(), "", new InputValidator() {

                    @Override
                    public boolean checkInput(String inputString) {
                        return PyNames.isIdentifier(inputString);
                    }

                    @Override
                    public boolean canClose(String inputString) {
                        return PyNames.isIdentifier(inputString);
                    }
                });
                if (alias == null) {
                    return;
                }
                target_name = alias;
            } else {
                // test mode
                target_name = "alias";
            }
            remove_name = imported_name;
        }
        final PsiElement referee = reference.getReference().resolve();
        if (referee != null && imported_name != null) {
            final Collection<PsiReference> references = new ArrayList<>();
            final ScopeOwner scope = PsiTreeUtil.getParentOfType(state.myImportElement, ScopeOwner.class);
            PsiTreeUtil.processElements(scope, new PsiElementProcessor() {

                public boolean execute(@NotNull PsiElement element) {
                    getReferences(element);
                    if (element instanceof PyStringLiteralExpression) {
                        final PsiLanguageInjectionHost host = (PsiLanguageInjectionHost) element;
                        final List<Pair<PsiElement, TextRange>> files = InjectedLanguageManager.getInstance(project).getInjectedPsiFiles(host);
                        if (files != null) {
                            for (Pair<PsiElement, TextRange> pair : files) {
                                final PsiElement first = pair.getFirst();
                                if (first instanceof ScopeOwner) {
                                    final ScopeOwner scopeOwner = (ScopeOwner) first;
                                    PsiTreeUtil.processElements(scopeOwner, new PsiElementProcessor() {

                                        public boolean execute(@NotNull PsiElement element) {
                                            getReferences(element);
                                            return true;
                                        }
                                    });
                                }
                            }
                        }
                    }
                    return true;
                }

                private void getReferences(PsiElement element) {
                    if (element instanceof PyReferenceExpression && PsiTreeUtil.getParentOfType(element, PyImportElement.class) == null) {
                        PyReferenceExpression ref = (PyReferenceExpression) element;
                        if (remove_name.equals(PyPsiUtils.toPath(ref))) {
                            // filter out other names that might resolve to our target
                            PsiElement resolved = ref.getReference().resolve();
                            if (resolved == referee)
                                references.add(ref.getReference());
                        }
                    }
                }
            });
            // no references here is OK by us.
            if (showConflicts(project, findDefinitions(target_name, references, Collections.<PsiElement>emptySet()), target_name, null)) {
                // got conflicts
                return;
            }
            // alter the import element
            PyElementGenerator generator = PyElementGenerator.getInstance(project);
            final LanguageLevel languageLevel = LanguageLevel.forElement(state.myImportElement);
            if (state.myAlias != null) {
                // remove alias
                ASTNode node = sure(state.myImportElement.getNode());
                ASTNode parent = sure(node.getTreeParent());
                // this is the reference
                node = sure(node.getFirstChildNode());
                // things past the reference: space, 'as', and alias
                node = sure(node.getTreeNext());
                parent.removeRange(node, null);
            } else {
                // add alias
                ASTNode my_ielt_node = sure(state.myImportElement.getNode());
                PyImportElement fountain = generator.createFromText(languageLevel, PyImportElement.class, "import foo as " + target_name, new int[] { 0, 2 });
                // at import elt
                ASTNode graft_node = sure(fountain.getNode());
                // at ref
                graft_node = sure(graft_node.getFirstChildNode());
                // space
                graft_node = sure(graft_node.getTreeNext());
                my_ielt_node.addChild((ASTNode) graft_node.clone());
                // 'as'
                graft_node = sure(graft_node.getTreeNext());
                my_ielt_node.addChild((ASTNode) graft_node.clone());
                // space
                graft_node = sure(graft_node.getTreeNext());
                my_ielt_node.addChild((ASTNode) graft_node.clone());
                // alias
                graft_node = sure(graft_node.getTreeNext());
                my_ielt_node.addChild((ASTNode) graft_node.clone());
            }
            // alter references
            for (PsiReference ref : references) {
                ASTNode ref_name_node = sure(sure(ref.getElement()).getNode());
                ASTNode parent = sure(ref_name_node.getTreeParent());
                ASTNode new_name_node = generator.createExpressionFromText(languageLevel, target_name).getNode();
                assert new_name_node != null;
                parent.replaceChild(ref_name_node, new_name_node);
            }
        }
    } catch (IncorrectOperationException ignored) {
        PyUtil.showBalloon(project, PyBundle.message("QFIX.action.failed"), MessageType.WARNING);
    }
}
Also used : ArrayList(java.util.ArrayList) PsiReference(com.intellij.psi.PsiReference) TextRange(com.intellij.openapi.util.TextRange) NotNull(org.jetbrains.annotations.NotNull) PsiElementProcessor(com.intellij.psi.search.PsiElementProcessor) ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) InputValidator(com.intellij.openapi.ui.InputValidator) PsiLanguageInjectionHost(com.intellij.psi.PsiLanguageInjectionHost) ASTNode(com.intellij.lang.ASTNode) ArrayList(java.util.ArrayList) List(java.util.List) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Application(com.intellij.openapi.application.Application) PsiElement(com.intellij.psi.PsiElement) Pair(com.intellij.openapi.util.Pair)

Example 57 with IncorrectOperationException

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

the class GrCreateSubclassAction method createSubclassGroovy.

@Nullable
public static PsiClass createSubclassGroovy(final GrTypeDefinition psiClass, final PsiDirectory targetDirectory, final String className) {
    final Project project = psiClass.getProject();
    final Ref<GrTypeDefinition> targetClass = new Ref<>();
    new WriteCommandAction(project, getTitle(psiClass), getTitle(psiClass)) {

        @Override
        protected void run(@NotNull Result result) throws Throwable {
            IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
            final GrTypeParameterList oldTypeParameterList = psiClass.getTypeParameterList();
            try {
                targetClass.set(CreateClassActionBase.createClassByType(targetDirectory, className, PsiManager.getInstance(project), psiClass, GroovyTemplates.GROOVY_CLASS, true));
            } catch (final IncorrectOperationException e) {
                ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(project, CodeInsightBundle.message("intention.error.cannot.create.class.message", className) + "\n" + e.getLocalizedMessage(), CodeInsightBundle.message("intention.error.cannot.create.class.title")));
                return;
            }
            startTemplate(oldTypeParameterList, project, psiClass, targetClass.get(), false);
        }
    }.execute();
    if (targetClass.get() == null)
        return null;
    if (!ApplicationManager.getApplication().isUnitTestMode() && !psiClass.hasTypeParameters()) {
        final Editor editor = CodeInsightUtil.positionCursorAtLBrace(project, targetClass.get().getContainingFile(), targetClass.get());
        if (editor == null)
            return targetClass.get();
        chooseAndImplement(psiClass, project, targetClass.get(), editor);
    }
    return targetClass.get();
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) Project(com.intellij.openapi.project.Project) GrTypeParameterList(org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameterList) Ref(com.intellij.openapi.util.Ref) GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor) Result(com.intellij.openapi.application.Result) Nullable(org.jetbrains.annotations.Nullable)

Example 58 with IncorrectOperationException

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

the class GrIntroduceClosureParameterProcessor method insertDeclaration.

private GrVariableDeclaration insertDeclaration(GrVariable original, GrVariableDeclaration declaration) {
    if (original instanceof GrField) {
        final PsiClass containingClass = ((GrField) original).getContainingClass();
        LOG.assertTrue(containingClass != null);
        return (GrVariableDeclaration) containingClass.addBefore(declaration, original.getParent());
    }
    final GrStatementOwner block;
    if (original instanceof PsiParameter) {
        final PsiElement container = original.getParent().getParent();
        if (container instanceof GrMethod) {
            block = ((GrMethod) container).getBlock();
        } else if (container instanceof GrClosableBlock) {
            block = (GrCodeBlock) container;
        } else if (container instanceof GrForStatement) {
            final GrStatement body = ((GrForStatement) container).getBody();
            if (body instanceof GrBlockStatement) {
                block = ((GrBlockStatement) body).getBlock();
            } else {
                GrBlockStatement blockStatement = myFactory.createBlockStatement();
                LOG.assertTrue(blockStatement != null);
                if (body != null) {
                    blockStatement.getBlock().addStatementBefore((GrStatement) body.copy(), null);
                    blockStatement = (GrBlockStatement) body.replace(blockStatement);
                } else {
                    blockStatement = (GrBlockStatement) container.add(blockStatement);
                }
                block = blockStatement.getBlock();
            }
        } else {
            throw new IncorrectOperationException();
        }
        LOG.assertTrue(block != null);
        return (GrVariableDeclaration) block.addStatementBefore(declaration, null);
    }
    PsiElement parent = original.getParent();
    LOG.assertTrue(parent instanceof GrVariableDeclaration);
    final PsiElement pparent = parent.getParent();
    if (pparent instanceof GrIfStatement) {
        if (((GrIfStatement) pparent).getThenBranch() == parent) {
            block = ((GrIfStatement) pparent).replaceThenBranch(myFactory.createBlockStatement()).getBlock();
        } else {
            block = ((GrIfStatement) pparent).replaceElseBranch(myFactory.createBlockStatement()).getBlock();
        }
        parent = block.addStatementBefore(((GrVariableDeclaration) parent), null);
    } else if (pparent instanceof GrLoopStatement) {
        block = ((GrLoopStatement) pparent).replaceBody(myFactory.createBlockStatement()).getBlock();
        parent = block.addStatementBefore(((GrVariableDeclaration) parent), null);
    } else {
        LOG.assertTrue(pparent instanceof GrStatementOwner);
        block = (GrStatementOwner) pparent;
    }
    return (GrVariableDeclaration) block.addStatementBefore(declaration, (GrStatement) parent);
}
Also used : GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrStatementOwner(org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) IncorrectOperationException(com.intellij.util.IncorrectOperationException) GrCodeBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock)

Example 59 with IncorrectOperationException

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

the class GroovyIntroduceParameterMethodUsagesProcessor method processChangeMethodSignature.

@Override
public boolean processChangeMethodSignature(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) throws IncorrectOperationException {
    if (!(usage.getElement() instanceof GrMethod) || !isGroovyUsage(usage))
        return true;
    GrMethod method = (GrMethod) usage.getElement();
    final FieldConflictsResolver fieldConflictsResolver = new FieldConflictsResolver(data.getParameterName(), method.getBlock());
    final MethodJavaDocHelper javaDocHelper = new MethodJavaDocHelper(method);
    final PsiParameter[] parameters = method.getParameterList().getParameters();
    data.getParametersToRemove().forEachDescending(new TIntProcedure() {

        @Override
        public boolean execute(final int paramNum) {
            try {
                PsiParameter param = parameters[paramNum];
                PsiDocTag tag = javaDocHelper.getTagForParameter(param);
                if (tag != null) {
                    tag.delete();
                }
                param.delete();
            } catch (IncorrectOperationException e) {
                LOG.error(e);
            }
            return true;
        }
    });
    addParameter(method, javaDocHelper, data.getForcedType(), data.getParameterName(), data.isDeclareFinal(), data.getProject());
    fieldConflictsResolver.fix();
    return false;
}
Also used : MethodJavaDocHelper(com.intellij.refactoring.util.javadoc.MethodJavaDocHelper) TIntProcedure(gnu.trove.TIntProcedure) PsiDocTag(com.intellij.psi.javadoc.PsiDocTag) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 60 with IncorrectOperationException

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

the class CustomCreateProperty method generateCreateComponentsMethod.

public static void generateCreateComponentsMethod(final PsiClass aClass) {
    final PsiFile psiFile = aClass.getContainingFile();
    if (psiFile == null)
        return;
    final VirtualFile vFile = psiFile.getVirtualFile();
    if (vFile == null)
        return;
    if (!FileModificationService.getInstance().prepareFileForWrite(psiFile))
        return;
    final Ref<SmartPsiElementPointer> refMethod = new Ref<>();
    CommandProcessor.getInstance().executeCommand(aClass.getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> {
        PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory();
        try {
            PsiMethod method = factory.createMethodFromText("private void " + AsmCodeGenerator.CREATE_COMPONENTS_METHOD_NAME + "() { \n // TODO: place custom component creation code here \n }", aClass);
            final PsiMethod psiMethod = (PsiMethod) aClass.add(method);
            refMethod.set(SmartPointerManager.getInstance(aClass.getProject()).createSmartPsiElementPointer(psiMethod));
            CodeStyleManager.getInstance(aClass.getProject()).reformat(psiMethod);
        } catch (IncorrectOperationException e) {
            LOG.error(e);
        }
    }), null, null);
    if (!refMethod.isNull()) {
        SwingUtilities.invokeLater(() -> {
            final PsiMethod element = (PsiMethod) refMethod.get().getElement();
            if (element != null) {
                final PsiCodeBlock body = element.getBody();
                assert body != null;
                final PsiComment comment = PsiTreeUtil.getChildOfType(body, PsiComment.class);
                if (comment != null) {
                    new OpenFileDescriptor(comment.getProject(), vFile, comment.getTextOffset()).navigate(true);
                }
            }
        });
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Ref(com.intellij.openapi.util.Ref) IncorrectOperationException(com.intellij.util.IncorrectOperationException) OpenFileDescriptor(com.intellij.openapi.fileEditor.OpenFileDescriptor)

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