Search in sources :

Example 36 with IncorrectOperationException

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

the class ConvertConcatenationToGstringIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
    final PsiFile file = element.getContainingFile();
    final int offset = editor.getCaretModel().getOffset();
    final AccessToken accessToken = ReadAction.start();
    final List<GrExpression> expressions;
    try {
        expressions = collectExpressions(file, offset);
    } finally {
        accessToken.finish();
    }
    final Document document = editor.getDocument();
    if (expressions.size() == 1) {
        invokeImpl(expressions.get(0), document);
    } else if (!expressions.isEmpty()) {
        if (ApplicationManager.getApplication().isUnitTestMode()) {
            invokeImpl(expressions.get(expressions.size() - 1), document);
            return;
        }
        IntroduceTargetChooser.showChooser(editor, expressions, new Pass<GrExpression>() {

            @Override
            public void pass(final GrExpression selectedValue) {
                invokeImpl(selectedValue, document);
            }
        }, grExpression -> grExpression.getText());
    }
}
Also used : TypeConversionUtil(com.intellij.psi.util.TypeConversionUtil) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) WriteAction(com.intellij.openapi.application.WriteAction) GrLiteralImpl(org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl) org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals) Document(com.intellij.openapi.editor.Document) ReadAction(com.intellij.openapi.application.ReadAction) ArrayList(java.util.ArrayList) AccessToken(com.intellij.openapi.application.AccessToken) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) GroovyCommonClassNames(org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames) Intention(org.jetbrains.plugins.groovy.intentions.base.Intention) Project(com.intellij.openapi.project.Project) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) IntroduceTargetChooser(com.intellij.refactoring.IntroduceTargetChooser) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) PsiElementPredicate(org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate) GroovyTokenTypes(org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes) GrMethodCallExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression) GrStringUtil(org.jetbrains.plugins.groovy.lang.psi.util.GrStringUtil) MethodSignatureUtil(com.intellij.psi.util.MethodSignatureUtil) IncorrectOperationException(com.intellij.util.IncorrectOperationException) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) TypesUtil(org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil) Editor(com.intellij.openapi.editor.Editor) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) CommandProcessor(com.intellij.openapi.command.CommandProcessor) Nullable(org.jetbrains.annotations.Nullable) GrBinaryExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrBinaryExpression) List(java.util.List) Pass(com.intellij.openapi.util.Pass) ErrorUtil(org.jetbrains.plugins.groovy.lang.psi.util.ErrorUtil) ApplicationManager(com.intellij.openapi.application.ApplicationManager) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) PsiUtil(org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil) Pass(com.intellij.openapi.util.Pass) AccessToken(com.intellij.openapi.application.AccessToken) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) Document(com.intellij.openapi.editor.Document)

Example 37 with IncorrectOperationException

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

the class ResourceBundleEditor method reinitSettings.

private void reinitSettings(final EditorEx editor) {
    EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
    editor.setColorsScheme(scheme);
    editor.setBorder(BorderFactory.createLineBorder(JBColor.border(), 1));
    EditorSettings settings = editor.getSettings();
    settings.setLineNumbersShown(false);
    settings.setWhitespacesShown(false);
    settings.setLineMarkerAreaShown(false);
    settings.setIndentGuidesShown(false);
    settings.setFoldingOutlineShown(false);
    settings.setAdditionalColumnsCount(0);
    settings.setAdditionalLinesCount(0);
    settings.setRightMarginShown(true);
    settings.setRightMargin(60);
    settings.setVirtualSpace(false);
    editor.setHighlighter(new LexerEditorHighlighter(new PropertiesValueHighlighter(), scheme));
    editor.setVerticalScrollbarVisible(true);
    // disabling default context menu
    editor.setContextMenuGroupId(null);
    editor.addEditorMouseListener(new EditorPopupHandler() {

        @Override
        public void invokePopup(EditorMouseEvent event) {
            if (!event.isConsumed() && event.getArea() == EditorMouseEventArea.EDITING_AREA) {
                DefaultActionGroup group = new DefaultActionGroup();
                group.add(CustomActionsSchema.getInstance().getCorrectedAction(IdeActions.GROUP_CUT_COPY_PASTE));
                group.add(CustomActionsSchema.getInstance().getCorrectedAction(IdeActions.ACTION_EDIT_SOURCE));
                group.addSeparator();
                group.add(new AnAction("Propagate Value Across of Resource Bundle") {

                    @Override
                    public void actionPerformed(AnActionEvent e) {
                        final String valueToPropagate = editor.getDocument().getText();
                        final String currentSelectedProperty = getSelectedPropertyName();
                        if (currentSelectedProperty == null) {
                            return;
                        }
                        ApplicationManager.getApplication().runWriteAction(() -> WriteCommandAction.runWriteCommandAction(myProject, () -> {
                            try {
                                final PropertiesFile[] propertiesFiles = myResourceBundle.getPropertiesFiles().stream().filter(f -> {
                                    final IProperty property = f.findPropertyByKey(currentSelectedProperty);
                                    return property == null || !valueToPropagate.equals(property.getValue());
                                }).toArray(PropertiesFile[]::new);
                                final PsiFile[] filesToPrepare = Arrays.stream(propertiesFiles).map(PropertiesFile::getContainingFile).toArray(PsiFile[]::new);
                                if (FileModificationService.getInstance().preparePsiElementsForWrite(filesToPrepare)) {
                                    for (PropertiesFile file : propertiesFiles) {
                                        myPropertiesInsertDeleteManager.insertOrUpdateTranslation(currentSelectedProperty, valueToPropagate, file);
                                    }
                                    recreateEditorsPanel();
                                }
                            } catch (final IncorrectOperationException e1) {
                                LOG.error(e1);
                            }
                        }));
                    }
                });
                EditorPopupHandler handler = EditorActionUtil.createEditorPopupHandler(group);
                handler.invokePopup(event);
                event.consume();
            }
        }
    });
}
Also used : EditorPopupHandler(com.intellij.util.EditorPopupHandler) LexerEditorHighlighter(com.intellij.openapi.editor.ex.util.LexerEditorHighlighter) EditorMouseEvent(com.intellij.openapi.editor.event.EditorMouseEvent) IProperty(com.intellij.lang.properties.IProperty) EditorColorsScheme(com.intellij.openapi.editor.colors.EditorColorsScheme) XmlPropertiesFile(com.intellij.lang.properties.xml.XmlPropertiesFile) PropertiesFile(com.intellij.lang.properties.psi.PropertiesFile) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 38 with IncorrectOperationException

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

the class CreatePropertyFix method createProperty.

public static void createProperty(@NotNull final Project project, @NotNull final PsiElement psiElement, @NotNull final Collection<PropertiesFile> selectedPropertiesFiles, @NotNull final String key, @NotNull final String value) {
    for (PropertiesFile selectedFile : selectedPropertiesFiles) {
        if (!FileModificationService.getInstance().prepareFileForWrite(selectedFile.getContainingFile()))
            return;
    }
    UndoUtil.markPsiFileForUndo(psiElement.getContainingFile());
    ApplicationManager.getApplication().runWriteAction(() -> CommandProcessor.getInstance().executeCommand(project, () -> {
        try {
            I18nUtil.createProperty(project, selectedPropertiesFiles, key, value);
        } catch (IncorrectOperationException e) {
            LOG.error(e);
        }
    }, CodeInsightBundle.message("quickfix.i18n.command.name"), project));
}
Also used : PropertiesFile(com.intellij.lang.properties.psi.PropertiesFile) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 39 with IncorrectOperationException

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

the class XsltIntroduceVariableAction method extractImpl.

protected boolean extractImpl(XPathExpression expression, Set<XPathExpression> matchingExpressions, List<XmlTag> otherMatches, IntroduceVariableOptions dlg) {
    final XmlAttribute attribute = PsiTreeUtil.getContextOfType(expression, XmlAttribute.class, true);
    assert attribute != null;
    try {
        final String name = dlg.getName();
        final XmlTag insertionPoint = XsltCodeInsightUtil.findVariableInsertionPoint(attribute.getParent(), XsltCodeInsightUtil.getUsageBlock(expression), name, dlg.isReplaceAll() ? otherMatches.toArray(new XmlTag[otherMatches.size()]) : XmlTag.EMPTY);
        final XmlTag parentTag = insertionPoint.getParentTag();
        assert parentTag != null : "Could not locate position to create variable at";
        final XmlTag xmlTag = parentTag.createChildTag("variable", XsltSupport.XSLT_NS, null, false);
        xmlTag.setAttribute("name", name);
        xmlTag.setAttribute("select", expression.getText());
        // TODO: revisit the formatting
        final PsiElement element = parentTag.addBefore(xmlTag, insertionPoint);
        final ASTNode node1 = parentTag.getNode();
        assert node1 != null;
        final ASTNode node2 = element.getNode();
        assert node2 != null;
        CodeStyleManager.getInstance(xmlTag.getManager().getProject()).reformatNewlyAddedElement(node1, node2);
        final XPathVariableReference var = XPathChangeUtil.createVariableReference(expression, name);
        expression.replace(var);
        if (dlg.isReplaceAll()) {
            for (XPathExpression expr : matchingExpressions) {
                expr.replace(XPathChangeUtil.createVariableReference(expr, name));
            }
            return false;
        } else {
            return true;
        }
    } catch (IncorrectOperationException e) {
        Logger.getInstance(getClass().getName()).error(e);
        return false;
    }
}
Also used : XPathExpression(org.intellij.lang.xpath.psi.XPathExpression) XmlAttribute(com.intellij.psi.xml.XmlAttribute) ASTNode(com.intellij.lang.ASTNode) XPathVariableReference(org.intellij.lang.xpath.psi.XPathVariableReference) IncorrectOperationException(com.intellij.util.IncorrectOperationException) PsiElement(com.intellij.psi.PsiElement) XmlTag(com.intellij.psi.xml.XmlTag)

Example 40 with IncorrectOperationException

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

the class VariableInlineHandler method invoke.

public static void invoke(@NotNull final XPathVariable variable, Editor editor) {
    final String type = LanguageFindUsages.INSTANCE.forLanguage(variable.getLanguage()).getType(variable);
    final Project project = variable.getProject();
    final XmlTag tag = ((XsltElement) variable).getTag();
    final String expression = tag.getAttributeValue("select");
    if (expression == null) {
        CommonRefactoringUtil.showErrorHint(project, editor, MessageFormat.format("{0} ''{1}'' has no value.", StringUtil.capitalize(type), variable.getName()), TITLE, null);
        return;
    }
    final Collection<PsiReference> references = ReferencesSearch.search(variable, new LocalSearchScope(tag.getParentTag()), false).findAll();
    if (references.size() == 0) {
        CommonRefactoringUtil.showErrorHint(project, editor, MessageFormat.format("{0} ''{1}'' is never used.", variable.getName()), TITLE, null);
        return;
    }
    boolean hasExternalRefs = false;
    if (XsltSupport.isTopLevelElement(tag)) {
        final Query<PsiReference> query = ReferencesSearch.search(variable, GlobalSearchScope.allScope(project), false);
        hasExternalRefs = !query.forEach(new Processor<PsiReference>() {

            int allRefs = 0;

            public boolean process(PsiReference psiReference) {
                if (++allRefs > references.size()) {
                    return false;
                } else if (!references.contains(psiReference)) {
                    return false;
                }
                return true;
            }
        });
    }
    final HighlightManager highlighter = HighlightManager.getInstance(project);
    final ArrayList<RangeHighlighter> highlighters = new ArrayList<>();
    final PsiReference[] psiReferences = references.toArray(new PsiReference[references.size()]);
    TextRange[] ranges = ContainerUtil.map2Array(psiReferences, TextRange.class, s -> {
        final PsiElement psiElement = s.getElement();
        final XmlAttributeValue context = PsiTreeUtil.getContextOfType(psiElement, XmlAttributeValue.class, true);
        if (psiElement instanceof XPathElement && context != null) {
            return XsltCodeInsightUtil.getRangeInsideHostingFile((XPathElement) psiElement).cutOut(s.getRangeInElement());
        }
        return psiElement.getTextRange().cutOut(s.getRangeInElement());
    });
    final Editor e = editor instanceof EditorWindow ? ((EditorWindow) editor).getDelegate() : editor;
    for (TextRange range : ranges) {
        final TextAttributes textAttributes = EditorColors.SEARCH_RESULT_ATTRIBUTES.getDefaultAttributes();
        final Color color = getScrollmarkColor(textAttributes);
        highlighter.addOccurrenceHighlight(e, range.getStartOffset(), range.getEndOffset(), textAttributes, HighlightManagerImpl.HIDE_BY_ESCAPE, highlighters, color);
    }
    highlighter.addOccurrenceHighlights(e, new PsiElement[] { ((XsltVariable) variable).getNameIdentifier() }, EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES.getDefaultAttributes(), false, highlighters);
    if (!hasExternalRefs) {
        if (!ApplicationManager.getApplication().isUnitTestMode() && Messages.showYesNoDialog(MessageFormat.format("Inline {0} ''{1}''? ({2} occurrence{3})", type, variable.getName(), String.valueOf(references.size()), references.size() > 1 ? "s" : ""), TITLE, Messages.getQuestionIcon()) != Messages.YES) {
            return;
        }
    } else {
        if (!ApplicationManager.getApplication().isUnitTestMode() && Messages.showYesNoDialog(MessageFormat.format("Inline {0} ''{1}''? ({2} local occurrence{3})\n" + "\nWarning: It is being used in external files. Its declaration will not be removed.", type, variable.getName(), String.valueOf(references.size()), references.size() > 1 ? "s" : ""), TITLE, Messages.getWarningIcon()) != Messages.YES) {
            return;
        }
    }
    final boolean hasRefs = hasExternalRefs;
    new WriteCommandAction.Simple(project, "XSLT.Inline", tag.getContainingFile()) {

        @Override
        protected void run() throws Throwable {
            try {
                for (PsiReference psiReference : references) {
                    final PsiElement element = psiReference.getElement();
                    if (element instanceof XPathElement) {
                        final XPathElement newExpr = XPathChangeUtil.createExpression(element, expression);
                        element.replace(newExpr);
                    } else {
                        assert false;
                    }
                }
                if (!hasRefs) {
                    tag.delete();
                }
            } catch (IncorrectOperationException e) {
                Logger.getInstance(VariableInlineHandler.class.getName()).error(e);
            }
        }
    }.execute();
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) XsltElement(org.intellij.lang.xpath.xslt.psi.XsltElement) ArrayList(java.util.ArrayList) RangeHighlighter(com.intellij.openapi.editor.markup.RangeHighlighter) TextAttributes(com.intellij.openapi.editor.markup.TextAttributes) PsiElement(com.intellij.psi.PsiElement) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) HighlightManager(com.intellij.codeInsight.highlighting.HighlightManager) PsiReference(com.intellij.psi.PsiReference) TextRange(com.intellij.openapi.util.TextRange) XmlAttributeValue(com.intellij.psi.xml.XmlAttributeValue) XPathElement(org.intellij.lang.xpath.psi.XPathElement) EditorWindow(com.intellij.injected.editor.EditorWindow) Project(com.intellij.openapi.project.Project) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor) XmlTag(com.intellij.psi.xml.XmlTag)

Aggregations

IncorrectOperationException (com.intellij.util.IncorrectOperationException)494 Project (com.intellij.openapi.project.Project)91 NotNull (org.jetbrains.annotations.NotNull)91 PsiElement (com.intellij.psi.PsiElement)55 Nullable (org.jetbrains.annotations.Nullable)55 TextRange (com.intellij.openapi.util.TextRange)43 VirtualFile (com.intellij.openapi.vfs.VirtualFile)39 Document (com.intellij.openapi.editor.Document)38 PsiFile (com.intellij.psi.PsiFile)38 ASTNode (com.intellij.lang.ASTNode)35 Editor (com.intellij.openapi.editor.Editor)33 ArrayList (java.util.ArrayList)32 NonNls (org.jetbrains.annotations.NonNls)32 UsageInfo (com.intellij.usageView.UsageInfo)31 IOException (java.io.IOException)27 JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)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