Search in sources :

Example 66 with HashMap

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

the class RunConfigurable method initTree.

private void initTree() {
    myTree.setRootVisible(false);
    myTree.setShowsRootHandles(true);
    UIUtil.setLineStyleAngled(myTree);
    TreeUtil.installActions(myTree);
    new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() {

        @Override
        public String convert(TreePath o) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) o.getLastPathComponent();
            final Object userObject = node.getUserObject();
            if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
                return ((RunnerAndConfigurationSettingsImpl) userObject).getName();
            } else if (userObject instanceof SingleConfigurationConfigurable) {
                return ((SingleConfigurationConfigurable) userObject).getNameText();
            } else {
                if (userObject instanceof ConfigurationType) {
                    return ((ConfigurationType) userObject).getDisplayName();
                } else if (userObject instanceof String) {
                    return (String) userObject;
                }
            }
            return o.toString();
        }
    });
    myTree.setCellRenderer(new ColoredTreeCellRenderer() {

        @Override
        public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            if (value instanceof DefaultMutableTreeNode) {
                final DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                final DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
                final Object userObject = node.getUserObject();
                Boolean shared = null;
                final String name = RunConfigurable.getName(userObject);
                if (userObject instanceof ConfigurationType) {
                    final ConfigurationType configurationType = (ConfigurationType) userObject;
                    append(name, parent.isRoot() ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES);
                    setIcon(configurationType.getIcon());
                } else if (userObject == DEFAULTS) {
                    append(name, SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
                    setIcon(AllIcons.General.Settings);
                } else if (userObject instanceof String) {
                    //Folders
                    append(name, SimpleTextAttributes.REGULAR_ATTRIBUTES);
                    setIcon(AllIcons.Nodes.Folder);
                } else if (userObject instanceof ConfigurationFactory) {
                    append(name);
                    setIcon(((ConfigurationFactory) userObject).getIcon());
                } else {
                    final RunManagerImpl runManager = getRunManager();
                    RunnerAndConfigurationSettings configuration = null;
                    if (userObject instanceof SingleConfigurationConfigurable) {
                        final SingleConfigurationConfigurable<?> settings = (SingleConfigurationConfigurable) userObject;
                        RunnerAndConfigurationSettings configurationSettings;
                        configurationSettings = settings.getSettings();
                        configuration = configurationSettings;
                        shared = settings.isStoreProjectConfiguration();
                        setIcon(ProgramRunnerUtil.getConfigurationIcon(configurationSettings, !settings.isValid()));
                    } else if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
                        RunnerAndConfigurationSettings settings = (RunnerAndConfigurationSettings) userObject;
                        shared = runManager.isConfigurationShared(settings);
                        setIcon(RunManagerEx.getInstanceEx(myProject).getConfigurationIcon(settings));
                        configuration = settings;
                    }
                    if (configuration != null) {
                        append(name, configuration.isTemporary() ? SimpleTextAttributes.GRAY_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES);
                    }
                }
                if (shared != null) {
                    Icon icon = getIcon();
                    LayeredIcon layeredIcon = new LayeredIcon(icon, shared ? SHARED_ICON : NON_SHARED_ICON);
                    setIcon(layeredIcon);
                    setIconTextGap(0);
                } else {
                    setIconTextGap(2);
                }
            }
        }
    });
    final RunManagerEx manager = getRunManager();
    final ConfigurationType[] factories = manager.getConfigurationFactories();
    for (ConfigurationType type : factories) {
        final List<RunnerAndConfigurationSettings> configurations = manager.getConfigurationSettingsList(type);
        if (!configurations.isEmpty()) {
            final DefaultMutableTreeNode typeNode = new DefaultMutableTreeNode(type);
            myRoot.add(typeNode);
            Map<String, DefaultMutableTreeNode> folderMapping = new HashMap<>();
            int folderCounter = 0;
            for (RunnerAndConfigurationSettings configuration : configurations) {
                String folder = configuration.getFolderName();
                if (folder != null) {
                    DefaultMutableTreeNode node = folderMapping.get(folder);
                    if (node == null) {
                        node = new DefaultMutableTreeNode(folder);
                        typeNode.insert(node, folderCounter);
                        folderCounter++;
                        folderMapping.put(folder, node);
                    }
                    node.add(new DefaultMutableTreeNode(configuration));
                } else {
                    typeNode.add(new DefaultMutableTreeNode(configuration));
                }
            }
        }
    }
    // add defaults
    final DefaultMutableTreeNode defaults = new DefaultMutableTreeNode(DEFAULTS);
    final ConfigurationType[] configurationTypes = RunManagerImpl.getInstanceImpl(myProject).getConfigurationFactories();
    for (final ConfigurationType type : configurationTypes) {
        if (!(type instanceof UnknownConfigurationType)) {
            ConfigurationFactory[] configurationFactories = type.getConfigurationFactories();
            DefaultMutableTreeNode typeNode = new DefaultMutableTreeNode(type);
            defaults.add(typeNode);
            if (configurationFactories.length != 1) {
                for (ConfigurationFactory factory : configurationFactories) {
                    typeNode.add(new DefaultMutableTreeNode(factory));
                }
            }
        }
    }
    if (defaults.getChildCount() > 0)
        myRoot.add(defaults);
    myTree.addTreeSelectionListener(new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent e) {
            final TreePath selectionPath = myTree.getSelectionPath();
            if (selectionPath != null) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
                final Object userObject = getSafeUserObject(node);
                if (userObject instanceof SingleConfigurationConfigurable) {
                    updateRightPanel((SingleConfigurationConfigurable<RunConfiguration>) userObject);
                } else if (userObject instanceof String) {
                    showFolderField(getSelectedConfigurationType(), node, (String) userObject);
                } else {
                    if (userObject instanceof ConfigurationType || userObject == DEFAULTS) {
                        final DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
                        if (parent.isRoot()) {
                            drawPressAddButtonMessage(userObject == DEFAULTS ? null : (ConfigurationType) userObject);
                        } else {
                            final ConfigurationType type = (ConfigurationType) userObject;
                            ConfigurationFactory[] factories = type.getConfigurationFactories();
                            if (factories.length == 1) {
                                final ConfigurationFactory factory = factories[0];
                                showTemplateConfigurable(factory);
                            } else {
                                drawPressAddButtonMessage((ConfigurationType) userObject);
                            }
                        }
                    } else if (userObject instanceof ConfigurationFactory) {
                        showTemplateConfigurable((ConfigurationFactory) userObject);
                    }
                }
            }
            updateDialog();
        }
    });
    myTree.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            clickDefaultButton();
        }
    }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED);
    sortTopLevelBranches();
    ((DefaultTreeModel) myTree.getModel()).reload();
}
Also used : HashMap(com.intellij.util.containers.HashMap) ActionEvent(java.awt.event.ActionEvent) ActionListener(java.awt.event.ActionListener)

Example 67 with HashMap

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

the class ExtractSuperClassUtil method createExtendingReference.

public static PsiJavaCodeReferenceElement createExtendingReference(final PsiClass superClass, final PsiClass derivedClass, final MemberInfo[] selectedMembers) throws IncorrectOperationException {
    final PsiManager manager = derivedClass.getManager();
    Set<PsiElement> movedElements = new com.intellij.util.containers.HashSet<>();
    for (final MemberInfo info : selectedMembers) {
        movedElements.add(info.getMember());
    }
    final Condition<PsiTypeParameter> filter = parameter -> findTypeParameterInDerived(derivedClass, parameter.getName()) == parameter;
    final PsiTypeParameterList typeParameterList = RefactoringUtil.createTypeParameterListWithUsedTypeParameters(null, filter, PsiUtilCore.toPsiElementArray(movedElements));
    final PsiTypeParameterList originalTypeParameterList = superClass.getTypeParameterList();
    assert originalTypeParameterList != null;
    final PsiTypeParameterList newList = typeParameterList != null ? (PsiTypeParameterList) originalTypeParameterList.replace(typeParameterList) : originalTypeParameterList;
    final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    Map<PsiTypeParameter, PsiType> substitutionMap = new HashMap<>();
    for (final PsiTypeParameter parameter : newList.getTypeParameters()) {
        final PsiTypeParameter parameterInDerived = findTypeParameterInDerived(derivedClass, parameter.getName());
        if (parameterInDerived != null) {
            substitutionMap.put(parameter, factory.createType(parameterInDerived));
        }
    }
    final PsiClassType type = factory.createType(superClass, factory.createSubstitutor(substitutionMap));
    return factory.createReferenceElementByType(type);
}
Also used : TypeConversionUtil(com.intellij.psi.util.TypeConversionUtil) VirtualFile(com.intellij.openapi.vfs.VirtualFile) HashMap(com.intellij.util.containers.HashMap) DocCommentPolicy(com.intellij.refactoring.util.DocCommentPolicy) NonNls(org.jetbrains.annotations.NonNls) RefactoringEventListener(com.intellij.refactoring.listeners.RefactoringEventListener) HashSet(java.util.HashSet) ModuleUtil(com.intellij.openapi.module.ModuleUtil) DialogWrapper(com.intellij.openapi.ui.DialogWrapper) Map(java.util.Map) Project(com.intellij.openapi.project.Project) PsiUtil(com.intellij.psi.util.PsiUtil) RefactoringEventData(com.intellij.refactoring.listeners.RefactoringEventData) Logger(com.intellij.openapi.diagnostic.Logger) Module(com.intellij.openapi.module.Module) ProjectRootManager(com.intellij.openapi.roots.ProjectRootManager) MultiMap(com.intellij.util.containers.MultiMap) MemberInfo(com.intellij.refactoring.util.classMembers.MemberInfo) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Collection(java.util.Collection) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Set(java.util.Set) PullUpProcessor(com.intellij.refactoring.memberPullUp.PullUpProcessor) Nullable(org.jetbrains.annotations.Nullable) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) MethodSignature(com.intellij.psi.util.MethodSignature) OverrideImplementExploreUtil(com.intellij.codeInsight.generation.OverrideImplementExploreUtil) PsiUtilCore(com.intellij.psi.util.PsiUtilCore) RefactoringUtil(com.intellij.refactoring.util.RefactoringUtil) ConflictsDialog(com.intellij.refactoring.ui.ConflictsDialog) Function(com.intellij.util.Function) com.intellij.psi(com.intellij.psi) Condition(com.intellij.openapi.util.Condition) HashMap(com.intellij.util.containers.HashMap) MemberInfo(com.intellij.refactoring.util.classMembers.MemberInfo) HashSet(java.util.HashSet)

Example 68 with HashMap

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

the class PasteHandler method doPaste.

private static void doPaste(final Editor editor, final Project project, final PsiFile file, final Document document, @NotNull final Transferable content) {
    CopyPasteManager.getInstance().stopKillRings();
    String text = null;
    try {
        text = (String) content.getTransferData(DataFlavor.stringFlavor);
    } catch (Exception e) {
        editor.getComponent().getToolkit().beep();
    }
    if (text == null)
        return;
    final CodeInsightSettings settings = CodeInsightSettings.getInstance();
    final Map<CopyPastePostProcessor, List<? extends TextBlockTransferableData>> extraData = new HashMap<>();
    final Collection<TextBlockTransferableData> allValues = new ArrayList<>();
    for (CopyPastePostProcessor<? extends TextBlockTransferableData> processor : Extensions.getExtensions(CopyPastePostProcessor.EP_NAME)) {
        List<? extends TextBlockTransferableData> data = processor.extractTransferableData(content);
        if (!data.isEmpty()) {
            extraData.put(processor, data);
            allValues.addAll(data);
        }
    }
    text = TextBlockTransferable.convertLineSeparators(editor, text, allValues);
    final CaretModel caretModel = editor.getCaretModel();
    final SelectionModel selectionModel = editor.getSelectionModel();
    final int col = caretModel.getLogicalPosition().column;
    // There is a possible case that we want to perform paste while there is an active selection at the editor and caret is located
    // inside it (e.g. Ctrl+A is pressed while caret is not at the zero column). We want to insert the text at selection start column
    // then, hence, inserted block of text should be indented according to the selection start as well.
    final int blockIndentAnchorColumn;
    final int caretOffset = caretModel.getOffset();
    if (selectionModel.hasSelection() && caretOffset >= selectionModel.getSelectionStart()) {
        blockIndentAnchorColumn = editor.offsetToLogicalPosition(selectionModel.getSelectionStart()).column;
    } else {
        blockIndentAnchorColumn = col;
    }
    // We assume that EditorModificationUtil.insertStringAtCaret() is smart enough to remove currently selected text (if any).
    RawText rawText = RawText.fromTransferable(content);
    String newText = text;
    for (CopyPastePreProcessor preProcessor : Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
        newText = preProcessor.preprocessOnPaste(project, file, editor, newText, rawText);
    }
    int indentOptions = text.equals(newText) ? settings.REFORMAT_ON_PASTE : CodeInsightSettings.REFORMAT_BLOCK;
    text = newText;
    if (LanguageFormatting.INSTANCE.forContext(file) == null && indentOptions != CodeInsightSettings.NO_REFORMAT) {
        indentOptions = CodeInsightSettings.INDENT_BLOCK;
    }
    final String _text = text;
    ApplicationManager.getApplication().runWriteAction(() -> {
        EditorModificationUtil.insertStringAtCaret(editor, _text, false, true);
    });
    int length = text.length();
    int offset = caretModel.getOffset() - length;
    if (offset < 0) {
        length += offset;
        offset = 0;
    }
    final RangeMarker bounds = document.createRangeMarker(offset, offset + length);
    caretModel.moveToOffset(bounds.getEndOffset());
    editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    selectionModel.removeSelection();
    final Ref<Boolean> indented = new Ref<>(Boolean.FALSE);
    for (Map.Entry<CopyPastePostProcessor, List<? extends TextBlockTransferableData>> e : extraData.entrySet()) {
        //noinspection unchecked
        e.getKey().processTransferableData(project, editor, bounds, caretOffset, indented, e.getValue());
    }
    boolean pastedTextContainsWhiteSpacesOnly = CharArrayUtil.shiftForward(document.getCharsSequence(), bounds.getStartOffset(), " \n\t") >= bounds.getEndOffset();
    VirtualFile virtualFile = file.getVirtualFile();
    if (!pastedTextContainsWhiteSpacesOnly && (virtualFile == null || !SingleRootFileViewProvider.isTooLargeForIntelligence(virtualFile))) {
        final int indentOptions1 = indentOptions;
        ApplicationManager.getApplication().runWriteAction(() -> {
            PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
            switch(indentOptions1) {
                case CodeInsightSettings.INDENT_BLOCK:
                    if (!indented.get()) {
                        indentBlock(project, editor, bounds.getStartOffset(), bounds.getEndOffset(), blockIndentAnchorColumn);
                    }
                    break;
                case CodeInsightSettings.INDENT_EACH_LINE:
                    if (!indented.get()) {
                        indentEachLine(project, editor, bounds.getStartOffset(), bounds.getEndOffset());
                    }
                    break;
                case CodeInsightSettings.REFORMAT_BLOCK:
                    // this is needed for example when inserting a comment before method
                    indentEachLine(project, editor, bounds.getStartOffset(), bounds.getEndOffset());
                    reformatBlock(project, editor, bounds.getStartOffset(), bounds.getEndOffset());
                    break;
            }
        });
    }
    if (bounds.isValid()) {
        caretModel.moveToOffset(bounds.getEndOffset());
        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
        selectionModel.removeSelection();
        editor.putUserData(EditorEx.LAST_PASTED_REGION, TextRange.create(bounds));
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) CodeInsightSettings(com.intellij.codeInsight.CodeInsightSettings) HashMap(com.intellij.util.containers.HashMap) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Ref(com.intellij.openapi.util.Ref) HashMap(com.intellij.util.containers.HashMap) Map(java.util.Map)

Example 69 with HashMap

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

the class MoveClassesOrPackagesProcessor method detectPackageLocalsMoved.

private void detectPackageLocalsMoved(final UsageInfo[] usages, final MultiMap<PsiElement, String> conflicts) {
    //    final HashSet reportedPackageLocalUsed = new HashSet();
    final HashSet<PsiClass> movedClasses = new HashSet<>();
    final HashMap<PsiClass, HashSet<PsiElement>> reportedClassToContainers = new HashMap<>();
    final PackageWrapper aPackage = myTargetPackage;
    for (UsageInfo usage : usages) {
        PsiElement element = usage.getElement();
        if (element == null)
            continue;
        if (usage instanceof MoveRenameUsageInfo && !(usage instanceof NonCodeUsageInfo) && ((MoveRenameUsageInfo) usage).getReferencedElement() instanceof PsiClass) {
            PsiClass aClass = (PsiClass) ((MoveRenameUsageInfo) usage).getReferencedElement();
            if (!movedClasses.contains(aClass)) {
                movedClasses.add(aClass);
            }
            if (aClass != null && aClass.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
                if (PsiTreeUtil.getParentOfType(element, PsiImportStatement.class) != null)
                    continue;
                PsiElement container = ConflictsUtil.getContainer(element);
                HashSet<PsiElement> reported = reportedClassToContainers.get(aClass);
                if (reported == null) {
                    reported = new HashSet<>();
                    reportedClassToContainers.put(aClass, reported);
                }
                if (!reported.contains(container)) {
                    reported.add(container);
                    PsiFile containingFile = element.getContainingFile();
                    if (containingFile != null && !isInsideMoved(element)) {
                        PsiDirectory directory = containingFile.getContainingDirectory();
                        if (directory != null) {
                            PsiPackage usagePackage = JavaDirectoryService.getInstance().getPackage(directory);
                            if (aPackage != null && usagePackage != null && !aPackage.equalToPackage(usagePackage)) {
                                final String message = RefactoringBundle.message("a.package.local.class.0.will.no.longer.be.accessible.from.1", CommonRefactoringUtil.htmlEmphasize(aClass.getName()), RefactoringUIUtil.getDescription(container, true));
                                conflicts.putValue(aClass, message);
                            }
                        }
                    }
                }
            }
        }
    }
    final MyClassInstanceReferenceVisitor instanceReferenceVisitor = new MyClassInstanceReferenceVisitor(conflicts);
    for (final PsiClass aClass : movedClasses) {
        String visibility = VisibilityUtil.getVisibilityModifier(aClass.getModifierList());
        if (PsiModifier.PACKAGE_LOCAL.equals(visibility)) {
            findInstancesOfPackageLocal(aClass, usages, instanceReferenceVisitor);
        } else {
            // public classes
            findPublicClassConflicts(aClass, instanceReferenceVisitor);
        }
    }
}
Also used : HashMap(com.intellij.util.containers.HashMap) PackageWrapper(com.intellij.refactoring.PackageWrapper) UsageInfo(com.intellij.usageView.UsageInfo)

Example 70 with HashMap

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

the class DuplicateConflictResolver method resolveConflict.

@Override
public CandidateInfo resolveConflict(@NotNull List<CandidateInfo> conflicts) {
    if (conflicts.size() == 1)
        return conflicts.get(0);
    final Map<Object, CandidateInfo> uniqueItems = new HashMap<>();
    for (CandidateInfo info : conflicts) {
        final PsiElement element = info.getElement();
        Object key;
        if (info instanceof MethodCandidateInfo) {
            key = ((PsiMethod) element).getSignature(((MethodCandidateInfo) info).getSubstitutor(false));
        } else {
            key = PsiUtilCore.getName(element);
        }
        if (!uniqueItems.containsKey(key)) {
            uniqueItems.put(key, info);
        }
    }
    if (uniqueItems.size() == 1)
        return uniqueItems.values().iterator().next();
    return null;
}
Also used : HashMap(com.intellij.util.containers.HashMap) MethodCandidateInfo(com.intellij.psi.infos.MethodCandidateInfo) CandidateInfo(com.intellij.psi.infos.CandidateInfo) MethodCandidateInfo(com.intellij.psi.infos.MethodCandidateInfo) PsiElement(com.intellij.psi.PsiElement)

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