Search in sources :

Example 31 with HashMap

use of com.intellij.util.containers.HashMap in project android by JetBrains.

the class AndroidMavenExecutor method generateResources.

public static Map<CompilerMessageCategory, List<String>> generateResources(final Module module) {
    MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(module.getProject());
    final MavenRunnerParameters parameters = new MavenRunnerParameters(true, projectsManager.findProject(module).getDirectory(), Collections.singletonList("process-resources"), projectsManager.getExplicitProfiles());
    final Map<CompilerMessageCategory, List<String>> result = new HashMap<CompilerMessageCategory, List<String>>();
    result.put(CompilerMessageCategory.ERROR, new ArrayList<String>());
    try {
        JavaParameters javaParams = ApplicationManager.getApplication().runReadAction(new Computable<JavaParameters>() {

            @Nullable
            @Override
            public JavaParameters compute() {
                try {
                    return MavenExternalParameters.createJavaParameters(module.getProject(), parameters);
                } catch (ExecutionException e) {
                    LOG.info(e);
                    result.get(CompilerMessageCategory.ERROR).add(e.getMessage());
                    return null;
                }
            }
        });
        if (javaParams == null) {
            return result;
        }
        GeneralCommandLine commandLine = javaParams.toCommandLine();
        final StringBuildingOutputProcessor processor = new StringBuildingOutputProcessor();
        boolean success = AndroidUtils.executeCommand(commandLine, processor, WaitingStrategies.WaitForever.getInstance()) == ExecutionStatus.SUCCESS;
        String message = processor.getMessage();
        if (!success) {
            LOG.info(message);
            String lcmessage = message.toLowerCase();
            int buildErrorIndex = lcmessage.indexOf(BUILD_ERROR_INDICATOR);
            if (buildErrorIndex >= 0) {
                result.get(CompilerMessageCategory.ERROR).add(message.substring(buildErrorIndex));
            }
        }
    } catch (ExecutionException e) {
        LOG.info(e);
        result.get(CompilerMessageCategory.ERROR).add(e.getMessage());
    }
    return result;
}
Also used : CompilerMessageCategory(com.intellij.openapi.compiler.CompilerMessageCategory) MavenProjectsManager(org.jetbrains.idea.maven.project.MavenProjectsManager) HashMap(com.intellij.util.containers.HashMap) StringBuildingOutputProcessor(org.jetbrains.android.util.StringBuildingOutputProcessor) GeneralCommandLine(com.intellij.execution.configurations.GeneralCommandLine) JavaParameters(com.intellij.execution.configurations.JavaParameters) ArrayList(java.util.ArrayList) List(java.util.List) ExecutionException(com.intellij.execution.ExecutionException) Nullable(org.jetbrains.annotations.Nullable) MavenRunnerParameters(org.jetbrains.idea.maven.execution.MavenRunnerParameters)

Example 32 with HashMap

use of com.intellij.util.containers.HashMap in project android by JetBrains.

the class AndroidFindStyleApplicationsProcessor method isPossibleApplicationOfStyle.

private boolean isPossibleApplicationOfStyle(XmlTag candidate) {
    final DomElement domCandidate = DomManager.getDomManager(myProject).getDomElement(candidate);
    if (!(domCandidate instanceof LayoutViewElement)) {
        return false;
    }
    final LayoutViewElement candidateView = (LayoutViewElement) domCandidate;
    final Map<Pair<String, String>, String> attrsInCandidateMap = new HashMap<Pair<String, String>, String>();
    final List<XmlAttribute> attrsInCandidate = AndroidExtractStyleAction.getExtractableAttributes(candidate);
    if (attrsInCandidate.size() < myAttrMap.size()) {
        return false;
    }
    for (XmlAttribute attribute : attrsInCandidate) {
        final String attrValue = attribute.getValue();
        if (attrValue != null) {
            attrsInCandidateMap.put(Pair.create(attribute.getNamespace(), attribute.getLocalName()), attrValue);
        }
    }
    for (Map.Entry<AndroidAttributeInfo, String> entry : myAttrMap.entrySet()) {
        final String ns = entry.getKey().getNamespace();
        final String name = entry.getKey().getName();
        final String value = entry.getValue();
        final String valueInCandidate = attrsInCandidateMap.get(Pair.create(ns, name));
        if (valueInCandidate == null || !valueInCandidate.equals(value)) {
            return false;
        }
    }
    if (candidateView.getStyle().getStringValue() != null) {
        if (myParentStyleNameAttrValue == null) {
            return false;
        }
        final PsiElement styleNameAttrValueForTag = getStyleNameAttrValueForTag(candidateView);
        if (styleNameAttrValueForTag == null || !myParentStyleNameAttrValue.equals(styleNameAttrValueForTag)) {
            return false;
        }
    } else if (myParentStyleNameAttrValue != null) {
        return false;
    }
    return true;
}
Also used : DomElement(com.intellij.util.xml.DomElement) LayoutViewElement(org.jetbrains.android.dom.layout.LayoutViewElement) XmlAttribute(com.intellij.psi.xml.XmlAttribute) HashMap(com.intellij.util.containers.HashMap) HashMap(com.intellij.util.containers.HashMap) PsiElement(com.intellij.psi.PsiElement) Pair(com.intellij.openapi.util.Pair)

Example 33 with HashMap

use of com.intellij.util.containers.HashMap in project android by JetBrains.

the class AndroidRefactoringUtil method computeAttributeMap.

@Nullable
static Map<AndroidAttributeInfo, String> computeAttributeMap(@NotNull Style style, @NotNull ErrorReporter errorReporter, @NotNull String errorReportTitle) {
    final Map<AndroidAttributeInfo, String> attributeValues = new HashMap<AndroidAttributeInfo, String>();
    for (StyleItem item : style.getItems()) {
        final String attributeName = item.getName().getStringValue();
        String attributeValue = item.getStringValue();
        if (attributeName == null || attributeName.length() <= 0 || attributeValue == null) {
            continue;
        }
        final int idx = attributeName.indexOf(':');
        final String localName = idx >= 0 ? attributeName.substring(idx + 1) : attributeName;
        final String nsPrefix = idx >= 0 ? attributeName.substring(0, idx) : null;
        if (nsPrefix != null) {
            if (!AndroidUtils.SYSTEM_RESOURCE_PACKAGE.equals(nsPrefix)) {
                errorReporter.report(RefactoringBundle.getCannotRefactorMessage("Unknown XML attribute prefix '" + nsPrefix + ":'"), errorReportTitle);
                return null;
            }
        } else {
            errorReporter.report(RefactoringBundle.getCannotRefactorMessage("The style contains attribute without 'android' prefix."), errorReportTitle);
            return null;
        }
        attributeValues.put(new AndroidAttributeInfo(localName, nsPrefix), attributeValue);
    }
    return attributeValues;
}
Also used : StyleItem(org.jetbrains.android.dom.resources.StyleItem) HashMap(com.intellij.util.containers.HashMap) Nullable(org.jetbrains.annotations.Nullable)

Example 34 with HashMap

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

the class PageSizes method init.

private static void init() {
    if (myPageSizes != null) {
        return;
    }
    myPageSizes = new ArrayList();
    myNamesToPageSizes = new HashMap();
    try {
        //noinspection ConstantConditions
        for (Element element : JdomKt.loadElement(PageSizes.class.getResourceAsStream(PAGE_SIZES_RESOURCE)).getChildren(ELEMENT_SIZE)) {
            String name = element.getAttributeValue(ATTRIBUTE_NAME);
            final String widthStr = element.getAttributeValue(ATTRIBUTE_WIDTH);
            final String heightStr = element.getAttributeValue(ATTRIBUTE_HEIGHT);
            String unit = element.getAttributeValue(ATTRIBUTE_UNIT);
            final String unitName = unit.equals(UNIT_MM) ? CodeEditorBundle.message("print.page.size.unit.mm") : CodeEditorBundle.message("print.page.size.unit.in");
            final String dimensions = CodeEditorBundle.message("print.page.width.x.height.unit.template", widthStr, heightStr, unitName);
            double width = parsePageSize(widthStr);
            double height = parsePageSize(heightStr);
            if (unit.equals(UNIT_MM)) {
                width *= MM_TO_INCH;
                height *= MM_TO_INCH;
            }
            addPageSizeIn(name, dimensions, width, height);
        }
    } catch (Exception e) {
        LOG.error(e);
    }
}
Also used : HashMap(com.intellij.util.containers.HashMap) Element(org.jdom.Element) ArrayList(java.util.ArrayList)

Example 35 with HashMap

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

the class SaveAsTemplateAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent e) {
    DataContext dataContext = e.getDataContext();
    Editor editor = Objects.requireNonNull(CommonDataKeys.EDITOR.getData(dataContext));
    PsiFile file = Objects.requireNonNull(CommonDataKeys.PSI_FILE.getData(dataContext));
    final Project project = file.getProject();
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    final TextRange selection = new TextRange(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd());
    PsiElement current = file.findElementAt(selection.getStartOffset());
    int startOffset = selection.getStartOffset();
    while (current instanceof PsiWhiteSpace) {
        current = current.getNextSibling();
        if (current == null)
            break;
        startOffset = current.getTextRange().getStartOffset();
    }
    if (startOffset >= selection.getEndOffset())
        startOffset = selection.getStartOffset();
    final PsiElement[] psiElements = PsiTreeUtil.collectElements(file, new PsiElementFilter() {

        @Override
        public boolean isAccepted(PsiElement element) {
            return selection.contains(element.getTextRange()) && element.getReferences().length > 0;
        }
    });
    final Document document = EditorFactory.getInstance().createDocument(editor.getDocument().getText().substring(startOffset, selection.getEndOffset()));
    final boolean isXml = file.getLanguage().is(StdLanguages.XML);
    final int offsetDelta = startOffset;
    new WriteCommandAction.Simple(project, (String) null) {

        @Override
        protected void run() throws Throwable {
            Map<RangeMarker, String> rangeToText = new HashMap<>();
            for (PsiElement element : psiElements) {
                for (PsiReference reference : element.getReferences()) {
                    if (!(reference instanceof PsiQualifiedReference) || ((PsiQualifiedReference) reference).getQualifier() == null) {
                        String canonicalText = reference.getCanonicalText();
                        TextRange referenceRange = reference.getRangeInElement();
                        final TextRange elementTextRange = element.getTextRange();
                        LOG.assertTrue(elementTextRange != null, elementTextRange);
                        final TextRange range = elementTextRange.cutOut(referenceRange).shiftRight(-offsetDelta);
                        final String oldText = document.getText(range);
                        // workaround for Java references: canonicalText contains generics, and we need to cut them off because otherwise
                        // they will be duplicated
                        int pos = canonicalText.indexOf('<');
                        if (pos > 0 && !oldText.contains("<")) {
                            canonicalText = canonicalText.substring(0, pos);
                        }
                        if (isXml) {
                            //strip namespace prefixes
                            pos = canonicalText.lastIndexOf(':');
                            if (pos >= 0 && pos < canonicalText.length() - 1 && !oldText.contains(":")) {
                                canonicalText = canonicalText.substring(pos + 1);
                            }
                        }
                        if (!canonicalText.equals(oldText)) {
                            rangeToText.put(document.createRangeMarker(range), canonicalText);
                        }
                    }
                }
            }
            List<RangeMarker> markers = new ArrayList<>();
            for (RangeMarker m1 : rangeToText.keySet()) {
                boolean nested = false;
                for (RangeMarker m2 : rangeToText.keySet()) {
                    if (m1 != m2 && m2.getStartOffset() <= m1.getStartOffset() && m1.getEndOffset() <= m2.getEndOffset()) {
                        nested = true;
                        break;
                    }
                }
                if (!nested) {
                    markers.add(m1);
                }
            }
            for (RangeMarker marker : markers) {
                final String value = rangeToText.get(marker);
                document.replaceString(marker.getStartOffset(), marker.getEndOffset(), value);
            }
        }
    }.execute();
    final TemplateImpl template = new TemplateImpl(TemplateListPanel.ABBREVIATION, document.getText(), TemplateSettings.USER_GROUP_NAME);
    template.setToReformat(true);
    OffsetKey startKey = OffsetKey.create("pivot");
    OffsetsInFile offsets = new OffsetsInFile(file);
    offsets.getOffsets().addOffset(startKey, startOffset);
    OffsetsInFile copy = TemplateManagerImpl.copyWithDummyIdentifier(offsets, editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd(), CompletionUtil.DUMMY_IDENTIFIER_TRIMMED);
    Set<TemplateContextType> applicable = TemplateManagerImpl.getApplicableContextTypes(copy.getFile(), copy.getOffsets().getOffset(startKey));
    for (TemplateContextType contextType : TemplateManagerImpl.getAllContextTypes()) {
        template.getTemplateContext().setEnabled(contextType, applicable.contains(contextType));
    }
    final LiveTemplatesConfigurable configurable = new LiveTemplatesConfigurable();
    ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> configurable.getTemplateListPanel().addTemplate(template));
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) OffsetsInFile(com.intellij.codeInsight.completion.OffsetsInFile) Document(com.intellij.openapi.editor.Document) DataContext(com.intellij.openapi.actionSystem.DataContext) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) PsiElementFilter(com.intellij.psi.util.PsiElementFilter) Project(com.intellij.openapi.project.Project) OffsetKey(com.intellij.codeInsight.completion.OffsetKey) Editor(com.intellij.openapi.editor.Editor) HashMap(com.intellij.util.containers.HashMap) TemplateContextType(com.intellij.codeInsight.template.TemplateContextType)

Aggregations

HashMap (com.intellij.util.containers.HashMap)118 NotNull (org.jetbrains.annotations.NotNull)23 VirtualFile (com.intellij.openapi.vfs.VirtualFile)22 File (java.io.File)22 Nullable (org.jetbrains.annotations.Nullable)18 Map (java.util.Map)17 Module (com.intellij.openapi.module.Module)15 Project (com.intellij.openapi.project.Project)15 ArrayList (java.util.ArrayList)14 PsiElement (com.intellij.psi.PsiElement)11 HashSet (com.intellij.util.containers.HashSet)10 List (java.util.List)9 IncorrectOperationException (com.intellij.util.IncorrectOperationException)8 IOException (java.io.IOException)8 Pair (com.intellij.openapi.util.Pair)6 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)6 SearchScope (com.intellij.psi.search.SearchScope)6 Logger (com.intellij.openapi.diagnostic.Logger)5 PsiFile (com.intellij.psi.PsiFile)5 UsageInfo (com.intellij.usageView.UsageInfo)5