Search in sources :

Example 6 with HashMap

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

the class JavaMarkObjectActionHandler method suggestMarkup.

private static Map<ObjectReference, ValueMarkup> suggestMarkup(ObjectReference objRef) {
    final Map<ObjectReference, ValueMarkup> result = new HashMap<>();
    for (ObjectReference ref : getReferringObjects(objRef)) {
        if (!(ref instanceof ClassObjectReference)) {
            // consider references from statisc fields only
            continue;
        }
        final ReferenceType refType = ((ClassObjectReference) ref).reflectedType();
        if (!refType.isAbstract()) {
            continue;
        }
        for (Field field : refType.visibleFields()) {
            if (!(field.isStatic() && field.isFinal())) {
                continue;
            }
            if (DebuggerUtils.isPrimitiveType(field.typeName())) {
                continue;
            }
            final Value fieldValue = refType.getValue(field);
            if (!(fieldValue instanceof ObjectReference)) {
                continue;
            }
            final ValueMarkup markup = result.get((ObjectReference) fieldValue);
            final String fieldName = field.name();
            final Color autoMarkupColor = getAutoMarkupColor();
            if (markup == null) {
                result.put((ObjectReference) fieldValue, new ValueMarkup(fieldName, autoMarkupColor, createMarkupTooltipText(null, refType, fieldName)));
            } else {
                final String currentText = markup.getText();
                if (!currentText.contains(fieldName)) {
                    final String currentTooltip = markup.getToolTipText();
                    final String tooltip = createMarkupTooltipText(currentTooltip, refType, fieldName);
                    result.put((ObjectReference) fieldValue, new ValueMarkup(currentText + ", " + fieldName, autoMarkupColor, tooltip));
                }
            }
        }
    }
    return result;
}
Also used : HashMap(com.intellij.util.containers.HashMap) ValueMarkup(com.intellij.xdebugger.impl.ui.tree.ValueMarkup)

Example 7 with HashMap

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

the class AndroidLintGlobalInspectionContext method performPreRunActivities.

@Override
public void performPreRunActivities(@NotNull List<Tools> globalTools, @NotNull List<Tools> localTools, @NotNull final GlobalInspectionContext context) {
    final Project project = context.getProject();
    if (!ProjectFacetManager.getInstance(project).hasFacets(AndroidFacet.ID)) {
        return;
    }
    final List<Issue> issues = AndroidLintExternalAnnotator.getIssuesFromInspections(project, null);
    if (issues.size() == 0) {
        return;
    }
    final Map<Issue, Map<File, List<ProblemData>>> problemMap = new HashMap<Issue, Map<File, List<ProblemData>>>();
    final AnalysisScope scope = context.getRefManager().getScope();
    if (scope == null) {
        return;
    }
    final IntellijLintClient client = IntellijLintClient.forBatch(project, problemMap, scope, issues);
    final LintDriver lint = new LintDriver(new IntellijLintIssueRegistry(), client);
    final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    if (indicator != null) {
        ProgressWrapper.unwrap(indicator).setText("Running Android Lint");
    }
    EnumSet<Scope> lintScope;
    //noinspection ConstantConditions
    if (!IntellijLintProject.SUPPORT_CLASS_FILES) {
        lintScope = EnumSet.copyOf(Scope.ALL);
        // Can't run class file based checks
        lintScope.remove(Scope.CLASS_FILE);
        lintScope.remove(Scope.ALL_CLASS_FILES);
        lintScope.remove(Scope.JAVA_LIBRARIES);
    } else {
        lintScope = Scope.ALL;
    }
    List<VirtualFile> files = null;
    final List<Module> modules = Lists.newArrayList();
    int scopeType = scope.getScopeType();
    switch(scopeType) {
        case AnalysisScope.MODULE:
            {
                SearchScope searchScope = scope.toSearchScope();
                if (searchScope instanceof ModuleWithDependenciesScope) {
                    ModuleWithDependenciesScope s = (ModuleWithDependenciesScope) searchScope;
                    if (!s.isSearchInLibraries()) {
                        modules.add(s.getModule());
                    }
                }
                break;
            }
        case AnalysisScope.FILE:
        case AnalysisScope.VIRTUAL_FILES:
        case AnalysisScope.UNCOMMITTED_FILES:
            {
                files = Lists.newArrayList();
                SearchScope searchScope = scope.toSearchScope();
                if (searchScope instanceof LocalSearchScope) {
                    final LocalSearchScope localSearchScope = (LocalSearchScope) searchScope;
                    final PsiElement[] elements = localSearchScope.getScope();
                    final List<VirtualFile> finalFiles = files;
                    ApplicationManager.getApplication().runReadAction(new Runnable() {

                        @Override
                        public void run() {
                            for (PsiElement element : elements) {
                                if (element instanceof PsiFile) {
                                    // should be the case since scope type is FILE
                                    Module module = ModuleUtilCore.findModuleForPsiElement(element);
                                    if (module != null && !modules.contains(module)) {
                                        modules.add(module);
                                    }
                                    VirtualFile virtualFile = ((PsiFile) element).getVirtualFile();
                                    if (virtualFile != null) {
                                        finalFiles.add(virtualFile);
                                    }
                                }
                            }
                        }
                    });
                } else {
                    final List<VirtualFile> finalList = files;
                    scope.accept(new PsiElementVisitor() {

                        @Override
                        public void visitFile(PsiFile file) {
                            VirtualFile virtualFile = file.getVirtualFile();
                            if (virtualFile != null) {
                                finalList.add(virtualFile);
                            }
                        }
                    });
                }
                if (files.isEmpty()) {
                    files = null;
                } else {
                    // Lint will compute it lazily based on actual files in the request
                    lintScope = null;
                }
                break;
            }
        case AnalysisScope.PROJECT:
            {
                modules.addAll(Arrays.asList(ModuleManager.getInstance(project).getModules()));
                break;
            }
        case AnalysisScope.CUSTOM:
        case AnalysisScope.MODULES:
        case AnalysisScope.DIRECTORY:
            {
                // Handled by the getNarrowedComplementaryScope case below
                break;
            }
        case AnalysisScope.INVALID:
            break;
        default:
            Logger.getInstance(this.getClass()).warn("Unexpected inspection scope " + scope + ", " + scopeType);
    }
    if (modules.isEmpty()) {
        for (Module module : ModuleManager.getInstance(project).getModules()) {
            if (scope.containsModule(module)) {
                modules.add(module);
            }
        }
        if (modules.isEmpty() && files != null) {
            for (VirtualFile file : files) {
                Module module = ModuleUtilCore.findModuleForFile(file, project);
                if (module != null && !modules.contains(module)) {
                    modules.add(module);
                }
            }
        }
        if (modules.isEmpty()) {
            AnalysisScope narrowed = scope.getNarrowedComplementaryScope(project);
            for (Module module : ModuleManager.getInstance(project).getModules()) {
                if (narrowed.containsModule(module)) {
                    modules.add(module);
                }
            }
        }
    }
    LintRequest request = new IntellijLintRequest(client, project, files, modules, false);
    request.setScope(lintScope);
    lint.analyze(request);
    myResults = problemMap;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Issue(com.android.tools.klint.detector.api.Issue) HashMap(com.intellij.util.containers.HashMap) PsiElementVisitor(com.intellij.psi.PsiElementVisitor) AnalysisScope(com.intellij.analysis.AnalysisScope) LintRequest(com.android.tools.klint.client.api.LintRequest) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement) LintDriver(com.android.tools.klint.client.api.LintDriver) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) ModuleWithDependenciesScope(com.intellij.openapi.module.impl.scopes.ModuleWithDependenciesScope) Project(com.intellij.openapi.project.Project) ModuleWithDependenciesScope(com.intellij.openapi.module.impl.scopes.ModuleWithDependenciesScope) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) AnalysisScope(com.intellij.analysis.AnalysisScope) Scope(com.android.tools.klint.detector.api.Scope) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) Module(com.intellij.openapi.module.Module) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) HashMap(com.intellij.util.containers.HashMap)

Example 8 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 9 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)

Example 10 with HashMap

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

the class GenericInlineHandler method initializeInliners.

public static Map<Language, InlineHandler.Inliner> initializeInliners(PsiElement element, InlineHandler.Settings settings, Collection<? extends PsiReference> allReferences) {
    final Map<Language, InlineHandler.Inliner> inliners = new HashMap<>();
    for (PsiReference ref : allReferences) {
        if (ref == null) {
            LOG.error("element: " + element.getClass() + ", allReferences contains null!");
            continue;
        }
        PsiElement refElement = ref.getElement();
        LOG.assertTrue(refElement != null, ref.getClass().getName());
        final Language language = refElement.getLanguage();
        if (inliners.containsKey(language))
            continue;
        final List<InlineHandler> handlers = InlineHandlers.getInlineHandlers(language);
        for (InlineHandler handler : handlers) {
            InlineHandler.Inliner inliner = handler.createInliner(element, settings);
            if (inliner != null) {
                inliners.put(language, inliner);
                break;
            }
        }
    }
    return inliners;
}
Also used : Language(com.intellij.lang.Language) HashMap(com.intellij.util.containers.HashMap) PsiReference(com.intellij.psi.PsiReference) PsiElement(com.intellij.psi.PsiElement) InlineHandler(com.intellij.lang.refactoring.InlineHandler)

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