Search in sources :

Example 86 with Project

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

the class DefaultGenerateElementProvider method generate.

@SuppressWarnings({ "unchecked" })
@Nullable
public T generate(@Nullable final DomElement parent, final Editor editor) {
    if (parent == null) {
        return null;
    }
    final List<? extends DomCollectionChildDescription> list = parent.getGenericInfo().getCollectionChildrenDescriptions();
    for (DomCollectionChildDescription childDescription : list) {
        if (ReflectionUtil.getRawType(childDescription.getType()).isAssignableFrom(myChildElementClass)) {
            XmlTag parentTag = parent.getXmlTag();
            if (editor != null && parentTag != null) {
                int offset = editor.getCaretModel().getOffset();
                PsiFile file = parentTag.getContainingFile();
                PsiElement psiElement = file.findElementAt(offset);
                if (psiElement instanceof PsiWhiteSpace && PsiTreeUtil.isAncestor(parentTag, psiElement, false)) {
                    Document document = editor.getDocument();
                    XmlTag childTag = parentTag.createChildTag(childDescription.getXmlElementName(), null, null, true);
                    String text = childTag.getText();
                    document.insertString(offset, text);
                    Project project = editor.getProject();
                    assert project != null;
                    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
                    documentManager.commitDocument(document);
                    PsiElement element = file.findElementAt(offset + 1);
                    T domElement = DomUtil.findDomElement(element, myChildElementClass);
                    if (domElement != null)
                        return domElement;
                    document.deleteString(offset, offset + text.length());
                    documentManager.commitDocument(document);
                }
            }
            int index = getCollectionIndex(parent, childDescription, editor);
            return index < 0 ? (T) childDescription.addValue(parent, myChildElementClass) : (T) childDescription.addValue(parent, myChildElementClass, index);
        }
    }
    return null;
}
Also used : Project(com.intellij.openapi.project.Project) DomCollectionChildDescription(com.intellij.util.xml.reflect.DomCollectionChildDescription) PsiFile(com.intellij.psi.PsiFile) Document(com.intellij.openapi.editor.Document) PsiElement(com.intellij.psi.PsiElement) XmlTag(com.intellij.psi.xml.XmlTag) PsiWhiteSpace(com.intellij.psi.PsiWhiteSpace) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) Nullable(org.jetbrains.annotations.Nullable)

Example 87 with Project

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

the class EditorTextFieldControl method updateComponent.

@Override
protected void updateComponent() {
    final DomElement domElement = getDomElement();
    if (domElement == null || !domElement.isValid())
        return;
    final EditorTextField textField = getEditorTextField(getComponent());
    final Project project = getProject();
    ApplicationManager.getApplication().invokeLater(() -> {
        if (!project.isOpen())
            return;
        if (!getDomWrapper().isValid())
            return;
        final DomElement domElement1 = getDomElement();
        if (domElement1 == null || !domElement1.isValid())
            return;
        final DomElementAnnotationsManager manager = DomElementAnnotationsManager.getInstance(project);
        final DomElementsProblemsHolder holder = manager.getCachedProblemHolder(domElement1);
        final List<DomElementProblemDescriptor> errorProblems = holder.getProblems(domElement1);
        final List<DomElementProblemDescriptor> warningProblems = new ArrayList<>(holder.getProblems(domElement1, true, HighlightSeverity.WARNING));
        warningProblems.removeAll(errorProblems);
        Color background = getDefaultBackground();
        if (errorProblems.size() > 0 && textField.getText().trim().length() == 0) {
            background = getErrorBackground();
        } else if (warningProblems.size() > 0) {
            background = getWarningBackground();
        }
        final Editor editor = textField.getEditor();
        if (editor != null) {
            final MarkupModel markupModel = editor.getMarkupModel();
            markupModel.removeAllHighlighters();
            if (!errorProblems.isEmpty() && editor.getDocument().getLineCount() > 0) {
                final TextAttributes attributes = SimpleTextAttributes.ERROR_ATTRIBUTES.toTextAttributes();
                attributes.setEffectType(EffectType.WAVE_UNDERSCORE);
                attributes.setEffectColor(attributes.getForegroundColor());
                markupModel.addLineHighlighter(0, 0, attributes);
                editor.getContentComponent().setToolTipText(errorProblems.get(0).getDescriptionTemplate());
            }
        }
        textField.setBackground(background);
    });
}
Also used : Project(com.intellij.openapi.project.Project) DomElementsProblemsHolder(com.intellij.util.xml.highlighting.DomElementsProblemsHolder) DomElement(com.intellij.util.xml.DomElement) EditorTextField(com.intellij.ui.EditorTextField) DomElementProblemDescriptor(com.intellij.util.xml.highlighting.DomElementProblemDescriptor) ArrayList(java.util.ArrayList) SimpleTextAttributes(com.intellij.ui.SimpleTextAttributes) TextAttributes(com.intellij.openapi.editor.markup.TextAttributes) Editor(com.intellij.openapi.editor.Editor) MarkupModel(com.intellij.openapi.editor.markup.MarkupModel) DomElementAnnotationsManager(com.intellij.util.xml.highlighting.DomElementAnnotationsManager)

Example 88 with Project

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

the class ExternalDocumentValidator method runJaxpValidation.

private void runJaxpValidation(final XmlElement element, Validator.ValidationHost host) {
    final PsiFile file = element.getContainingFile();
    if (myFile == file && file != null && myModificationStamp == file.getModificationStamp() && !ValidateXmlActionHandler.isValidationDependentFilesOutOfDate((XmlFile) file) && // we have validated before
    SoftReference.dereference(myInfos) != null) {
        addAllInfos(host, myInfos.get());
        return;
    }
    if (myHandler == null)
        myHandler = new ValidateXmlActionHandler(false);
    final Project project = element.getProject();
    final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
    if (document == null)
        return;
    final List<ValidationInfo> results = new LinkedList<>();
    myHost = new Validator.ValidationHost() {

        @Override
        public void addMessage(PsiElement context, String message, int type) {
            addMessage(context, message, type == ERROR ? ErrorType.ERROR : type == WARNING ? ErrorType.WARNING : ErrorType.INFO);
        }

        @Override
        public void addMessage(final PsiElement context, final String message, @NotNull final ErrorType type) {
            final ValidationInfo o = new ValidationInfo(context, message, type);
            results.add(o);
        }
    };
    myHandler.setErrorReporter(new ErrorReporter(myHandler) {

        @Override
        public boolean isStopOnUndeclaredResource() {
            return true;
        }

        @Override
        public void processError(final SAXParseException e, final ValidateXmlActionHandler.ProblemType warning) {
            try {
                ApplicationManager.getApplication().runReadAction(() -> {
                    if (e.getPublicId() != null) {
                        return;
                    }
                    final VirtualFile errorFile = myHandler.getProblemFile(e);
                    if (!Comparing.equal(errorFile, file.getVirtualFile()) && errorFile != null) {
                        // error in attached schema
                        return;
                    }
                    if (document.getLineCount() < e.getLineNumber() || e.getLineNumber() <= 0) {
                        return;
                    }
                    Validator.ValidationHost.ErrorType problemType = getProblemType(warning);
                    int offset = Math.max(0, document.getLineStartOffset(e.getLineNumber() - 1) + e.getColumnNumber() - 2);
                    if (offset >= document.getTextLength())
                        return;
                    PsiElement currentElement = PsiDocumentManager.getInstance(project).getPsiFile(document).findElementAt(offset);
                    PsiElement originalElement = currentElement;
                    final String elementText = currentElement.getText();
                    if (elementText.equals("</")) {
                        currentElement = currentElement.getNextSibling();
                    } else if (elementText.equals(">") || elementText.equals("=")) {
                        currentElement = currentElement.getPrevSibling();
                    }
                    // Cannot find the declaration of element
                    String localizedMessage = e.getLocalizedMessage();
                    // Ideally would be to switch one messageIds
                    int endIndex = localizedMessage.indexOf(':');
                    if (endIndex < localizedMessage.length() - 1 && localizedMessage.charAt(endIndex + 1) == '/') {
                        // ignore : in http://
                        endIndex = -1;
                    }
                    String messageId = endIndex != -1 ? localizedMessage.substring(0, endIndex) : "";
                    localizedMessage = localizedMessage.substring(endIndex + 1).trim();
                    if (localizedMessage.startsWith(CANNOT_FIND_DECLARATION_ERROR_PREFIX) || localizedMessage.startsWith(ELEMENT_ERROR_PREFIX) || localizedMessage.startsWith(ROOT_ELEMENT_ERROR_PREFIX) || localizedMessage.startsWith(CONTENT_OF_ELEMENT_TYPE_ERROR_PREFIX)) {
                        addProblemToTagName(currentElement, originalElement, localizedMessage, warning);
                    //return;
                    } else if (localizedMessage.startsWith(VALUE_ERROR_PREFIX)) {
                        addProblemToTagName(currentElement, originalElement, localizedMessage, warning);
                    } else {
                        if (messageId.startsWith(ATTRIBUTE_MESSAGE_PREFIX)) {
                            @NonNls String prefix = "of attribute ";
                            final int i = localizedMessage.indexOf(prefix);
                            if (i != -1) {
                                int messagePrefixLength = prefix.length() + i;
                                final int nextQuoteIndex = localizedMessage.indexOf(localizedMessage.charAt(messagePrefixLength), messagePrefixLength + 1);
                                String attrName = nextQuoteIndex == -1 ? null : localizedMessage.substring(messagePrefixLength + 1, nextQuoteIndex);
                                XmlTag parent = PsiTreeUtil.getParentOfType(originalElement, XmlTag.class);
                                currentElement = parent.getAttribute(attrName, null);
                                if (currentElement != null) {
                                    currentElement = ((XmlAttribute) currentElement).getValueElement();
                                }
                            }
                            if (currentElement != null) {
                                assertValidElement(currentElement, originalElement, localizedMessage);
                                myHost.addMessage(currentElement, localizedMessage, problemType);
                            } else {
                                addProblemToTagName(originalElement, originalElement, localizedMessage, warning);
                            }
                        } else if (localizedMessage.startsWith(ATTRIBUTE_ERROR_PREFIX)) {
                            final int messagePrefixLength = ATTRIBUTE_ERROR_PREFIX.length();
                            if (localizedMessage.charAt(messagePrefixLength) == '"' || localizedMessage.charAt(messagePrefixLength) == '\'') {
                                // extract the attribute name from message and get it from tag!
                                final int nextQuoteIndex = localizedMessage.indexOf(localizedMessage.charAt(messagePrefixLength), messagePrefixLength + 1);
                                String attrName = nextQuoteIndex == -1 ? null : localizedMessage.substring(messagePrefixLength + 1, nextQuoteIndex);
                                XmlTag parent = PsiTreeUtil.getParentOfType(originalElement, XmlTag.class);
                                currentElement = parent.getAttribute(attrName, null);
                                if (currentElement != null) {
                                    currentElement = SourceTreeToPsiMap.treeElementToPsi(XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild(SourceTreeToPsiMap.psiElementToTree(currentElement)));
                                }
                            } else {
                                currentElement = PsiTreeUtil.getParentOfType(currentElement, XmlTag.class, false);
                            }
                            if (currentElement != null) {
                                assertValidElement(currentElement, originalElement, localizedMessage);
                                myHost.addMessage(currentElement, localizedMessage, problemType);
                            } else {
                                addProblemToTagName(originalElement, originalElement, localizedMessage, warning);
                            }
                        } else if (localizedMessage.startsWith(STRING_ERROR_PREFIX)) {
                            if (currentElement != null) {
                                myHost.addMessage(currentElement, localizedMessage, Validator.ValidationHost.ErrorType.WARNING);
                            }
                        } else {
                            currentElement = getNodeForMessage(currentElement != null ? currentElement : originalElement);
                            assertValidElement(currentElement, originalElement, localizedMessage);
                            if (currentElement != null) {
                                myHost.addMessage(currentElement, localizedMessage, problemType);
                            }
                        }
                    }
                });
            } catch (Exception ex) {
                if (ex instanceof ProcessCanceledException)
                    throw (ProcessCanceledException) ex;
                if (ex instanceof XmlResourceResolver.IgnoredResourceException)
                    throw (XmlResourceResolver.IgnoredResourceException) ex;
                LOG.error(ex);
            }
        }
    });
    myHandler.doValidate((XmlFile) element.getContainingFile());
    myFile = file;
    myModificationStamp = myFile.getModificationStamp();
    myInfos = new WeakReference<>(results);
    addAllInfos(host, results);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Document(com.intellij.openapi.editor.Document) XmlResourceResolver(com.intellij.xml.util.XmlResourceResolver) ErrorReporter(com.intellij.xml.actions.validate.ErrorReporter) SAXParseException(org.xml.sax.SAXParseException) PsiFile(com.intellij.psi.PsiFile) ValidateXmlActionHandler(com.intellij.xml.actions.validate.ValidateXmlActionHandler) PsiElement(com.intellij.psi.PsiElement) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) NonNls(org.jetbrains.annotations.NonNls) LinkedList(java.util.LinkedList) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) SAXParseException(org.xml.sax.SAXParseException) Project(com.intellij.openapi.project.Project) Validator(com.intellij.codeInsight.daemon.Validator)

Example 89 with Project

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

the class XmlTagImpl method externalResourceModificationTracker.

private ModificationTracker externalResourceModificationTracker() {
    Project project = getProject();
    ExternalResourceManagerEx manager = ExternalResourceManagerEx.getInstanceEx();
    return () -> manager.getModificationCount(project);
}
Also used : Project(com.intellij.openapi.project.Project) ExternalResourceManagerEx(com.intellij.javaee.ExternalResourceManagerEx)

Example 90 with Project

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

the class GroovyCompletionUtil method shortenReference.

//need to shorten references in type argument list
public static void shortenReference(final PsiFile file, final int offset) throws IncorrectOperationException {
    final Project project = file.getProject();
    final PsiDocumentManager manager = PsiDocumentManager.getInstance(project);
    final Document document = manager.getDocument(file);
    assert document != null;
    manager.commitDocument(document);
    final PsiReference ref = file.findReferenceAt(offset);
    if (ref instanceof GrCodeReferenceElement) {
        JavaCodeStyleManager.getInstance(project).shortenClassReferences((GroovyPsiElement) ref);
    }
}
Also used : Project(com.intellij.openapi.project.Project) GrCodeReferenceElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement) Document(com.intellij.openapi.editor.Document)

Aggregations

Project (com.intellij.openapi.project.Project)3623 VirtualFile (com.intellij.openapi.vfs.VirtualFile)874 NotNull (org.jetbrains.annotations.NotNull)580 Nullable (org.jetbrains.annotations.Nullable)478 Module (com.intellij.openapi.module.Module)368 PsiFile (com.intellij.psi.PsiFile)334 Editor (com.intellij.openapi.editor.Editor)301 PsiElement (com.intellij.psi.PsiElement)292 ArrayList (java.util.ArrayList)214 File (java.io.File)212 Document (com.intellij.openapi.editor.Document)180 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)172 List (java.util.List)158 IOException (java.io.IOException)107 TextRange (com.intellij.openapi.util.TextRange)99 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)96 IncorrectOperationException (com.intellij.util.IncorrectOperationException)95 Presentation (com.intellij.openapi.actionSystem.Presentation)94 DataContext (com.intellij.openapi.actionSystem.DataContext)92 PsiDirectory (com.intellij.psi.PsiDirectory)90