Search in sources :

Example 46 with IncorrectOperationException

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

the class PyMoveSymbolDelegate method doMove.

public void doMove(@NotNull Project project, @NotNull List<PyElement> elements) {
    final PsiElement firstElement = elements.get(0);
    final String initialPath = StringUtil.notNullize(PyPsiUtils.getContainingFilePath(firstElement));
    final BaseRefactoringProcessor processor;
    if (isMovableLocalFunctionOrMethod(firstElement)) {
        final PyFunction function = (PyFunction) firstElement;
        final PyMakeFunctionTopLevelDialog dialog = new PyMakeFunctionTopLevelDialog(project, function, initialPath, initialPath);
        if (!dialog.showAndGet()) {
            return;
        }
        if (function.getContainingClass() != null) {
            processor = new PyMakeMethodTopLevelProcessor(function, dialog.getTargetPath());
        } else {
            processor = new PyMakeLocalFunctionTopLevelProcessor(function, dialog.getTargetPath());
        }
        processor.setPreviewUsages(dialog.isPreviewUsages());
    } else {
        final List<PsiNamedElement> initialElements = Lists.newArrayList();
        for (PsiElement element : elements) {
            final PsiNamedElement e = PyMoveModuleMembersHelper.extractNamedElement(element);
            if (e == null) {
                return;
            }
            initialElements.add(e);
        }
        final PyMoveModuleMembersDialog dialog = new PyMoveModuleMembersDialog(project, initialElements, initialPath, initialPath);
        if (!dialog.showAndGet()) {
            return;
        }
        final PsiNamedElement[] selectedElements = ContainerUtil.findAllAsArray(dialog.getSelectedTopLevelSymbols(), PsiNamedElement.class);
        processor = new PyMoveModuleMembersProcessor(selectedElements, dialog.getTargetPath());
        processor.setPreviewUsages(dialog.isPreviewUsages());
    }
    try {
        processor.run();
    } catch (IncorrectOperationException e) {
        if (ApplicationManager.getApplication().isUnitTestMode()) {
            throw e;
        }
        CommonRefactoringUtil.showErrorMessage(RefactoringBundle.message("error.title"), e.getMessage(), null, project);
    }
}
Also used : PyMoveModuleMembersDialog(com.jetbrains.python.refactoring.move.moduleMembers.PyMoveModuleMembersDialog) BaseRefactoringProcessor(com.intellij.refactoring.BaseRefactoringProcessor) PyMoveModuleMembersProcessor(com.jetbrains.python.refactoring.move.moduleMembers.PyMoveModuleMembersProcessor) PyMakeFunctionTopLevelDialog(com.jetbrains.python.refactoring.move.makeFunctionTopLevel.PyMakeFunctionTopLevelDialog) PyMakeLocalFunctionTopLevelProcessor(com.jetbrains.python.refactoring.move.makeFunctionTopLevel.PyMakeLocalFunctionTopLevelProcessor) PyMakeMethodTopLevelProcessor(com.jetbrains.python.refactoring.move.makeFunctionTopLevel.PyMakeMethodTopLevelProcessor) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 47 with IncorrectOperationException

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

the class XmlGtTypedHandler method beforeCharTyped.

@Override
public Result beforeCharTyped(final char c, final Project project, Editor editor, PsiFile editedFile, final FileType fileType) {
    final WebEditorOptions webEditorOptions = WebEditorOptions.getInstance();
    if (c == '>' && webEditorOptions != null && webEditorOptions.isAutomaticallyInsertClosingTag() && fileContainsXmlLanguage(editedFile)) {
        PsiDocumentManager.getInstance(project).commitAllDocuments();
        PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
        FileViewProvider provider = editedFile.getViewProvider();
        int offset = editor.getCaretModel().getOffset();
        PsiElement element, elementAtCaret = null;
        if (offset < editor.getDocument().getTextLength()) {
            elementAtCaret = element = provider.findElementAt(offset, XMLLanguage.class);
            if (element == null && offset > 0) {
                // seems like a template language
                // <xml_code><caret><outer_element>
                elementAtCaret = element = provider.findElementAt(offset - 1, XMLLanguage.class);
            }
            if (!(element instanceof PsiWhiteSpace)) {
                boolean nonAcceptableDelimiter = true;
                if (element instanceof XmlToken) {
                    IElementType tokenType = ((XmlToken) element).getTokenType();
                    if (tokenType == XmlTokenType.XML_START_TAG_START || tokenType == XmlTokenType.XML_END_TAG_START) {
                        if (offset > 0) {
                            PsiElement previousElement = provider.findElementAt(offset - 1, XMLLanguage.class);
                            if (previousElement instanceof XmlToken) {
                                tokenType = ((XmlToken) previousElement).getTokenType();
                                element = previousElement;
                                nonAcceptableDelimiter = false;
                            }
                        }
                    } else if (tokenType == XmlTokenType.XML_NAME || tokenType == XmlTokenType.XML_TAG_NAME) {
                        if (element.getNextSibling() instanceof PsiErrorElement) {
                            nonAcceptableDelimiter = false;
                        }
                    }
                    if (tokenType == XmlTokenType.XML_TAG_END || tokenType == XmlTokenType.XML_EMPTY_ELEMENT_END && element.getTextOffset() == offset - 1) {
                        EditorModificationUtil.moveCaretRelatively(editor, 1);
                        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
                        return Result.STOP;
                    }
                }
                if (nonAcceptableDelimiter)
                    return Result.CONTINUE;
            } else {
                // check if right after empty end
                PsiElement previousElement = provider.findElementAt(offset - 1, XMLLanguage.class);
                if (previousElement instanceof XmlToken) {
                    final IElementType tokenType = ((XmlToken) previousElement).getTokenType();
                    if (tokenType == XmlTokenType.XML_EMPTY_ELEMENT_END) {
                        return Result.STOP;
                    }
                }
            }
            PsiElement parent = element.getParent();
            if (parent instanceof XmlText) {
                final String text = parent.getText();
                // check /
                final int index = offset - parent.getTextOffset() - 1;
                if (index >= 0 && text.charAt(index) == '/') {
                    // already seen /
                    return Result.CONTINUE;
                }
                element = parent.getPrevSibling();
            } else if (parent instanceof XmlTag && !(element.getPrevSibling() instanceof XmlTag) && !(element.getPrevSibling() instanceof OuterLanguageElement)) {
                element = parent;
            } else if (parent instanceof XmlAttributeValue) {
                element = parent;
            }
        } else {
            element = provider.findElementAt(editor.getDocument().getTextLength() - 1, XMLLanguage.class);
            if (element == null)
                return Result.CONTINUE;
            element = element.getParent();
        }
        if (offset > 0 && offset <= editor.getDocument().getTextLength()) {
            if (editor.getDocument().getCharsSequence().charAt(offset - 1) == '/') {
                // Some languages (e.g. GSP) allow character '/' in tag name.
                return Result.CONTINUE;
            }
        }
        if (element instanceof XmlAttributeValue) {
            element = element.getParent().getParent();
        }
        while (element instanceof PsiWhiteSpace || element instanceof OuterLanguageElement) element = element.getPrevSibling();
        if (element instanceof XmlDocument) {
            // hack for closing tags in RHTML
            element = element.getLastChild();
        }
        if (element == null)
            return Result.CONTINUE;
        if (!(element instanceof XmlTag)) {
            if (element instanceof XmlTokenImpl && element.getPrevSibling() != null && element.getPrevSibling().getText().equals("<")) {
                // tag is started and there is another text in the end
                EditorModificationUtil.insertStringAtCaret(editor, "</" + element.getText() + ">", false, 0);
            }
            return Result.CONTINUE;
        }
        XmlTag tag = (XmlTag) element;
        if (XmlUtil.getTokenOfType(tag, XmlTokenType.XML_TAG_END) != null)
            return Result.CONTINUE;
        if (XmlUtil.getTokenOfType(tag, XmlTokenType.XML_EMPTY_ELEMENT_END) != null)
            return Result.CONTINUE;
        final XmlToken startToken = XmlUtil.getTokenOfType(tag, XmlTokenType.XML_START_TAG_START);
        if (startToken == null || !startToken.getText().equals("<"))
            return Result.CONTINUE;
        String name = tag.getName();
        if (elementAtCaret instanceof XmlToken && (((XmlToken) elementAtCaret).getTokenType() == XmlTokenType.XML_NAME || ((XmlToken) elementAtCaret).getTokenType() == XmlTokenType.XML_TAG_NAME)) {
            name = name.substring(0, offset - elementAtCaret.getTextOffset());
        }
        if (tag instanceof HtmlTag && HtmlUtil.isSingleHtmlTag(name))
            return Result.CONTINUE;
        if (name.isEmpty())
            return Result.CONTINUE;
        int tagOffset = tag.getTextRange().getStartOffset();
        final XmlToken nameToken = XmlUtil.getTokenOfType(tag, XmlTokenType.XML_NAME);
        if (nameToken != null && nameToken.getTextRange().getStartOffset() > offset)
            return Result.CONTINUE;
        HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(tagOffset);
        if (BraceMatchingUtil.matchBrace(editor.getDocument().getCharsSequence(), editedFile.getFileType(), iterator, true, true)) {
            PsiElement parent = tag.getParent();
            boolean hasBalance = true;
            loop: while (parent instanceof XmlTag) {
                if (name.equals(((XmlTag) parent).getName())) {
                    hasBalance = false;
                    ASTNode astNode = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(parent.getNode());
                    if (astNode == null) {
                        hasBalance = true;
                        break;
                    }
                    for (PsiElement el = parent.getNextSibling(); el != null; el = el.getNextSibling()) {
                        if (el instanceof PsiErrorElement && el.getText().startsWith("</" + name)) {
                            hasBalance = true;
                            break loop;
                        }
                    }
                }
                parent = parent.getParent();
            }
            if (hasBalance)
                return Result.CONTINUE;
        }
        Collection<TextRange> cdataReformatRanges = null;
        final XmlElementDescriptor descriptor = tag.getDescriptor();
        EditorModificationUtil.insertStringAtCaret(editor, "</" + name + ">", false, 0);
        if (descriptor instanceof XmlElementDescriptorWithCDataContent) {
            final XmlElementDescriptorWithCDataContent cDataContainer = (XmlElementDescriptorWithCDataContent) descriptor;
            cdataReformatRanges = ContainerUtil.newSmartList();
            if (cDataContainer.requiresCdataBracesInContext(tag)) {
                @NonNls final String cDataStart = "><![CDATA[";
                final String inserted = cDataStart + "\n]]>";
                EditorModificationUtil.insertStringAtCaret(editor, inserted, false, cDataStart.length());
                int caretOffset = editor.getCaretModel().getOffset();
                if (caretOffset >= cDataStart.length()) {
                    cdataReformatRanges.add(TextRange.from(caretOffset - cDataStart.length(), inserted.length() + 1));
                }
            }
        }
        if (cdataReformatRanges != null && !cdataReformatRanges.isEmpty()) {
            PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
            try {
                CodeStyleManager.getInstance(project).reformatText(file, cdataReformatRanges);
            } catch (IncorrectOperationException e) {
                LOG.error(e);
            }
        }
        return cdataReformatRanges != null && !cdataReformatRanges.isEmpty() ? Result.STOP : Result.CONTINUE;
    }
    return Result.CONTINUE;
}
Also used : OuterLanguageElement(com.intellij.psi.templateLanguages.OuterLanguageElement) XmlTokenImpl(com.intellij.psi.impl.source.xml.XmlTokenImpl) TemplateLanguageFileViewProvider(com.intellij.psi.templateLanguages.TemplateLanguageFileViewProvider) WebEditorOptions(com.intellij.application.options.editor.WebEditorOptions) ASTNode(com.intellij.lang.ASTNode) XMLLanguage(com.intellij.lang.xml.XMLLanguage) NonNls(org.jetbrains.annotations.NonNls) HtmlTag(com.intellij.psi.html.HtmlTag) TextRange(com.intellij.openapi.util.TextRange) IElementType(com.intellij.psi.tree.IElementType) XmlElementDescriptorWithCDataContent(com.intellij.xml.XmlElementDescriptorWithCDataContent) IncorrectOperationException(com.intellij.util.IncorrectOperationException) XmlElementDescriptor(com.intellij.xml.XmlElementDescriptor) HighlighterIterator(com.intellij.openapi.editor.highlighter.HighlighterIterator)

Example 48 with IncorrectOperationException

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

the class FieldConflictsResolver method fixInitializer.

public GrExpression fixInitializer(GrExpression initializer) {
    if (myField == null)
        return initializer;
    final GrReferenceExpression[] replacedRef = { null };
    initializer.accept(new GroovyRecursiveElementVisitor() {

        @Override
        public void visitReferenceExpression(@NotNull GrReferenceExpression expression) {
            final GrExpression qualifierExpression = expression.getQualifier();
            if (qualifierExpression != null) {
                qualifierExpression.accept(this);
            } else {
                final PsiElement result = expression.resolve();
                if (expression.getManager().areElementsEquivalent(result, myField)) {
                    try {
                        replacedRef[0] = qualifyReference(expression, myField, myQualifyingClass);
                    } catch (IncorrectOperationException e) {
                        LOG.error(e);
                    }
                }
            }
        }
    });
    if (!initializer.isValid())
        return replacedRef[0];
    return initializer;
}
Also used : GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) IncorrectOperationException(com.intellij.util.IncorrectOperationException) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)

Example 49 with IncorrectOperationException

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

the class MorphAction method updateBoundFieldType.

private static void updateBoundFieldType(final GuiEditor editor, final RadComponent oldComponent, final ComponentItem targetItem) {
    PsiField oldBoundField = BindingProperty.findBoundField(editor.getRootContainer(), oldComponent.getBinding());
    if (oldBoundField != null) {
        final PsiElementFactory factory = JavaPsiFacade.getInstance(editor.getProject()).getElementFactory();
        try {
            PsiType componentType = factory.createTypeFromText(targetItem.getClassName().replace('$', '.'), null);
            new ChangeFieldTypeFix(editor, oldBoundField, componentType).run();
        } catch (IncorrectOperationException e) {
            LOG.error(e);
        }
    }
}
Also used : PsiField(com.intellij.psi.PsiField) PsiElementFactory(com.intellij.psi.PsiElementFactory) ChangeFieldTypeFix(com.intellij.uiDesigner.quickFixes.ChangeFieldTypeFix) IncorrectOperationException(com.intellij.util.IncorrectOperationException) PsiType(com.intellij.psi.PsiType)

Example 50 with IncorrectOperationException

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

the class FormClassAnnotator method annotateFormField.

private static void annotateFormField(final PsiField field, final PsiFile boundForm, final AnnotationHolder holder) {
    Annotation boundFieldAnnotation = holder.createInfoAnnotation(field, null);
    boundFieldAnnotation.setGutterIconRenderer(new BoundIconRenderer(field));
    LOG.assertTrue(boundForm instanceof PsiPlainTextFile);
    final PsiType guiComponentType = FormReferenceProvider.getGUIComponentType((PsiPlainTextFile) boundForm, field.getName());
    if (guiComponentType != null) {
        final PsiType fieldType = field.getType();
        if (!fieldType.isAssignableFrom(guiComponentType)) {
            String message = UIDesignerBundle.message("bound.field.type.mismatch", guiComponentType.getCanonicalText(), fieldType.getCanonicalText());
            Annotation annotation = holder.createErrorAnnotation(field.getTypeElement(), message);
            annotation.registerFix(new ChangeFormComponentTypeFix((PsiPlainTextFile) boundForm, field.getName(), field.getType()), null, null);
            annotation.registerFix(new ChangeBoundFieldTypeFix(field, guiComponentType), null, null);
        }
    }
    if (field.hasInitializer()) {
        final String message = UIDesignerBundle.message("field.is.overwritten.by.generated.code", field.getName());
        Annotation annotation = holder.createWarningAnnotation(field.getInitializer(), message);
        annotation.registerFix(new IntentionAction() {

            @Override
            @NotNull
            public String getText() {
                return message;
            }

            @Override
            @NotNull
            public String getFamilyName() {
                return UIBundle.message("remove.field.initializer.quick.fix");
            }

            @Override
            public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
                return field.getInitializer() != null;
            }

            @Override
            public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
                final PsiExpression initializer = field.getInitializer();
                LOG.assertTrue(initializer != null);
                initializer.delete();
            }

            @Override
            public boolean startInWriteAction() {
                return true;
            }
        });
    }
}
Also used : NotNull(org.jetbrains.annotations.NotNull) Annotation(com.intellij.lang.annotation.Annotation) Project(com.intellij.openapi.project.Project) IntentionAction(com.intellij.codeInsight.intention.IntentionAction) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor)

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