Search in sources :

Example 46 with MultiMap

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

the class PsiSearchHelperImpl method processRequests.

@Override
public boolean processRequests(@NotNull SearchRequestCollector collector, @NotNull Processor<PsiReference> processor) {
    final Map<SearchRequestCollector, Processor<PsiReference>> collectors = ContainerUtil.newHashMap();
    collectors.put(collector, processor);
    ProgressIndicator progress = getOrCreateIndicator();
    appendCollectorsFromQueryRequests(collectors);
    boolean result;
    do {
        MultiMap<Set<IdIndexEntry>, RequestWithProcessor> globals = new MultiMap<>();
        final List<Computable<Boolean>> customs = ContainerUtil.newArrayList();
        final Set<RequestWithProcessor> locals = ContainerUtil.newLinkedHashSet();
        Map<RequestWithProcessor, Processor<PsiElement>> localProcessors = new THashMap<>();
        distributePrimitives(collectors, locals, globals, customs, localProcessors, progress);
        result = processGlobalRequestsOptimized(globals, progress, localProcessors);
        if (result) {
            for (RequestWithProcessor local : locals) {
                result = processSingleRequest(local.request, local.refProcessor);
                if (!result)
                    break;
            }
            if (result) {
                for (Computable<Boolean> custom : customs) {
                    result = custom.compute();
                    if (!result)
                        break;
                }
            }
            if (!result)
                break;
        }
    } while (appendCollectorsFromQueryRequests(collectors));
    return result;
}
Also used : ReadActionProcessor(com.intellij.openapi.application.ReadActionProcessor) Processor(com.intellij.util.Processor) THashSet(gnu.trove.THashSet) MultiMap(com.intellij.util.containers.MultiMap) THashMap(gnu.trove.THashMap) EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 47 with MultiMap

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

the class FrameworkDetectionIndex method getIndexer.

@NotNull
@Override
public DataIndexer<Integer, Void, FileContent> getIndexer() {
    final MultiMap<FileType, Pair<ElementPattern<FileContent>, Integer>> detectors = new MultiMap<>();
    FrameworkDetectorRegistry registry = FrameworkDetectorRegistry.getInstance();
    for (FrameworkDetector detector : FrameworkDetector.EP_NAME.getExtensions()) {
        detectors.putValue(detector.getFileType(), Pair.create(detector.createSuitableFilePattern(), registry.getDetectorId(detector)));
    }
    return new DataIndexer<Integer, Void, FileContent>() {

        @NotNull
        @Override
        public Map<Integer, Void> map(@NotNull FileContent inputData) {
            final FileType fileType = inputData.getFileType();
            if (!detectors.containsKey(fileType)) {
                return Collections.emptyMap();
            }
            Map<Integer, Void> result = null;
            for (Pair<ElementPattern<FileContent>, Integer> pair : detectors.get(fileType)) {
                if (pair.getFirst().accepts(inputData)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(inputData.getFile() + " accepted by detector " + pair.getSecond());
                    }
                    if (result == null) {
                        result = new HashMap<>();
                    }
                    myDispatcher.getMulticaster().fileUpdated(inputData.getFile(), pair.getSecond());
                    result.put(pair.getSecond(), null);
                }
            }
            return result != null ? result : Collections.<Integer, Void>emptyMap();
        }
    };
}
Also used : FrameworkDetector(com.intellij.framework.detection.FrameworkDetector) ElementPattern(com.intellij.patterns.ElementPattern) NotNull(org.jetbrains.annotations.NotNull) MultiMap(com.intellij.util.containers.MultiMap) FileType(com.intellij.openapi.fileTypes.FileType) Pair(com.intellij.openapi.util.Pair) NotNull(org.jetbrains.annotations.NotNull)

Example 48 with MultiMap

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

the class VariableInplaceRenamer method performRefactoringRename.

protected void performRefactoringRename(final String newName, final StartMarkAction markAction) {
    final String refactoringId = getRefactoringId();
    try {
        PsiNamedElement elementToRename = getVariable();
        if (refactoringId != null) {
            final RefactoringEventData beforeData = new RefactoringEventData();
            beforeData.addElement(elementToRename);
            beforeData.addStringProperties(myOldName);
            myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(refactoringId, beforeData);
        }
        if (!isIdentifier(newName, myLanguage)) {
            return;
        }
        if (elementToRename != null) {
            new WriteCommandAction(myProject, getCommandName()) {

                @Override
                protected void run(@NotNull Result result) throws Throwable {
                    renameSynthetic(newName);
                }
            }.execute();
        }
        AutomaticRenamerFactory[] factories = Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME);
        for (AutomaticRenamerFactory renamerFactory : factories) {
            if (elementToRename != null && renamerFactory.isApplicable(elementToRename)) {
                final List<UsageInfo> usages = new ArrayList<>();
                final AutomaticRenamer renamer = renamerFactory.createRenamer(elementToRename, newName, new ArrayList<>());
                if (renamer.hasAnythingToRename()) {
                    if (!ApplicationManager.getApplication().isUnitTestMode()) {
                        final AutomaticRenamingDialog renamingDialog = new AutomaticRenamingDialog(myProject, renamer);
                        if (!renamingDialog.showAndGet()) {
                            continue;
                        }
                    }
                    final Runnable runnable = () -> ApplicationManager.getApplication().runReadAction(() -> renamer.findUsages(usages, false, false));
                    if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(runnable, RefactoringBundle.message("searching.for.variables"), true, myProject)) {
                        return;
                    }
                    if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, PsiUtilCore.toPsiElementArray(renamer.getElements())))
                        return;
                    final Runnable performAutomaticRename = () -> {
                        CommandProcessor.getInstance().markCurrentCommandAsGlobal(myProject);
                        final UsageInfo[] usageInfos = usages.toArray(new UsageInfo[usages.size()]);
                        final MultiMap<PsiElement, UsageInfo> classified = RenameProcessor.classifyUsages(renamer.getElements(), usageInfos);
                        for (final PsiNamedElement element : renamer.getElements()) {
                            final String newElementName = renamer.getNewName(element);
                            if (newElementName != null) {
                                final Collection<UsageInfo> infos = classified.get(element);
                                RenameUtil.doRename(element, newElementName, infos.toArray(new UsageInfo[infos.size()]), myProject, RefactoringElementListener.DEAF);
                            }
                        }
                    };
                    final WriteCommandAction writeCommandAction = new WriteCommandAction(myProject, getCommandName()) {

                        @Override
                        protected void run(@NotNull Result result) throws Throwable {
                            performAutomaticRename.run();
                        }
                    };
                    if (ApplicationManager.getApplication().isUnitTestMode()) {
                        writeCommandAction.execute();
                    } else {
                        ApplicationManager.getApplication().invokeLater(() -> writeCommandAction.execute());
                    }
                }
            }
        }
    } finally {
        if (refactoringId != null) {
            final RefactoringEventData afterData = new RefactoringEventData();
            afterData.addElement(getVariable());
            afterData.addStringProperties(newName);
            myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(refactoringId, afterData);
        }
        try {
            ((EditorImpl) InjectedLanguageUtil.getTopLevelEditor(myEditor)).stopDumbLater();
        } finally {
            FinishMarkAction.finish(myProject, myEditor, markAction);
        }
    }
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) AutomaticRenamer(com.intellij.refactoring.rename.naming.AutomaticRenamer) EditorImpl(com.intellij.openapi.editor.impl.EditorImpl) ArrayList(java.util.ArrayList) NotNull(org.jetbrains.annotations.NotNull) Result(com.intellij.openapi.application.Result) MultiMap(com.intellij.util.containers.MultiMap) AutomaticRenamerFactory(com.intellij.refactoring.rename.naming.AutomaticRenamerFactory) RefactoringEventData(com.intellij.refactoring.listeners.RefactoringEventData) Collection(java.util.Collection) UsageInfo(com.intellij.usageView.UsageInfo)

Example 49 with MultiMap

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

the class ProjectDataManager method importData.

@SuppressWarnings("unchecked")
public void importData(@NotNull Collection<DataNode<?>> nodes, @NotNull Project project, @NotNull IdeModifiableModelsProvider modelsProvider, boolean synchronous) {
    if (project.isDisposed())
        return;
    MultiMap<Key<?>, DataNode<?>> grouped = ExternalSystemApiUtil.recursiveGroup(nodes);
    for (Key<?> key : myServices.getValue().keySet()) {
        if (!grouped.containsKey(key)) {
            grouped.put(key, Collections.<DataNode<?>>emptyList());
        }
    }
    final Collection<DataNode<?>> projects = grouped.get(ProjectKeys.PROJECT);
    // only one project(can be multi-module project) expected for per single import
    assert projects.size() == 1 || projects.isEmpty();
    final DataNode<ProjectData> projectNode = (DataNode<ProjectData>) ContainerUtil.getFirstItem(projects);
    final ProjectData projectData;
    ProjectSystemId projectSystemId;
    if (projectNode != null) {
        projectData = projectNode.getData();
        projectSystemId = projectNode.getData().getOwner();
        ExternalProjectsDataStorage.getInstance(project).saveInclusionSettings(projectNode);
    } else {
        projectData = null;
        DataNode<ModuleData> aModuleNode = (DataNode<ModuleData>) ContainerUtil.getFirstItem(grouped.get(ProjectKeys.MODULE));
        projectSystemId = aModuleNode != null ? aModuleNode.getData().getOwner() : null;
    }
    if (projectSystemId != null) {
        ExternalSystemUtil.scheduleExternalViewStructureUpdate(project, projectSystemId);
    }
    List<Runnable> onSuccessImportTasks = ContainerUtil.newSmartList();
    try {
        final Set<Map.Entry<Key<?>, Collection<DataNode<?>>>> entries = grouped.entrySet();
        final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
        if (indicator != null) {
            indicator.setIndeterminate(false);
        }
        final int size = entries.size();
        int count = 0;
        List<Runnable> postImportTasks = ContainerUtil.newSmartList();
        for (Map.Entry<Key<?>, Collection<DataNode<?>>> entry : entries) {
            if (indicator != null) {
                String message = ExternalSystemBundle.message("progress.update.text", projectSystemId != null ? projectSystemId.getReadableName() : "", "Refresh " + getReadableText(entry.getKey()));
                indicator.setText(message);
                indicator.setFraction((double) count++ / size);
            }
            doImportData(entry.getKey(), entry.getValue(), projectData, project, modelsProvider, postImportTasks, onSuccessImportTasks);
        }
        for (Runnable postImportTask : postImportTasks) {
            postImportTask.run();
        }
        commit(modelsProvider, project, synchronous, "Imported data");
        if (indicator != null) {
            indicator.setIndeterminate(true);
        }
    } catch (Throwable t) {
        dispose(modelsProvider, project, synchronous);
        ExceptionUtil.rethrowAllAsUnchecked(t);
    }
    for (Runnable onSuccessImportTask : ContainerUtil.reverse(onSuccessImportTasks)) {
        onSuccessImportTask.run();
    }
}
Also used : ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) ModuleData(com.intellij.openapi.externalSystem.model.project.ModuleData) MultiMap(com.intellij.util.containers.MultiMap) ProjectData(com.intellij.openapi.externalSystem.model.project.ProjectData)

Example 50 with MultiMap

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

the class ExternalSystemKeymapExtension method createGroup.

public KeymapGroup createGroup(Condition<AnAction> condition, final Project project) {
    KeymapGroup result = KeymapGroupFactory.getInstance().createGroup(ExternalSystemBundle.message("external.system.keymap.group"), ExternalSystemIcons.TaskGroup);
    AnAction[] externalSystemActions = ActionsTreeUtil.getActions("ExternalSystem.Actions");
    for (AnAction action : externalSystemActions) {
        ActionsTreeUtil.addAction(result, action, condition);
    }
    if (project == null)
        return result;
    MultiMap<ProjectSystemId, String> projectToActionsMapping = MultiMap.create();
    for (ExternalSystemManager<?, ?, ?, ?, ?> manager : ExternalSystemApiUtil.getAllManagers()) {
        projectToActionsMapping.putValues(manager.getSystemId(), ContainerUtil.<String>emptyList());
    }
    ActionManager actionManager = ActionManager.getInstance();
    if (actionManager != null) {
        for (String eachId : actionManager.getActionIds(getActionPrefix(project, null))) {
            AnAction eachAction = actionManager.getAction(eachId);
            if (!(eachAction instanceof MyExternalSystemAction))
                continue;
            if (condition != null && !condition.value(actionManager.getActionOrStub(eachId)))
                continue;
            MyExternalSystemAction taskAction = (MyExternalSystemAction) eachAction;
            projectToActionsMapping.putValue(taskAction.getSystemId(), eachId);
        }
    }
    Map<ProjectSystemId, KeymapGroup> keymapGroupMap = ContainerUtil.newHashMap();
    for (ProjectSystemId systemId : projectToActionsMapping.keySet()) {
        if (!keymapGroupMap.containsKey(systemId)) {
            final Icon projectIcon = ExternalSystemUiUtil.getUiAware(systemId).getProjectIcon();
            KeymapGroup group = KeymapGroupFactory.getInstance().createGroup(systemId.getReadableName(), projectIcon);
            keymapGroupMap.put(systemId, group);
        }
    }
    for (Map.Entry<ProjectSystemId, Collection<String>> each : projectToActionsMapping.entrySet()) {
        Collection<String> tasks = each.getValue();
        final ProjectSystemId systemId = each.getKey();
        final KeymapGroup systemGroup = keymapGroupMap.get(systemId);
        if (systemGroup == null)
            continue;
        for (String actionId : tasks) {
            systemGroup.addActionId(actionId);
        }
        if (systemGroup instanceof Group) {
            Icon icon = SystemInfoRt.isMac ? AllIcons.ToolbarDecorator.Mac.Add : AllIcons.ToolbarDecorator.Add;
            ((Group) systemGroup).addHyperlink(new Hyperlink(icon, "Choose a task to assign a shortcut") {

                @Override
                public void onClick(MouseEvent e) {
                    SelectExternalTaskDialog dialog = new SelectExternalTaskDialog(systemId, project);
                    if (dialog.showAndGet() && dialog.getResult() != null) {
                        TaskData taskData = dialog.getResult().second;
                        String ownerModuleName = dialog.getResult().first;
                        ExternalSystemTaskAction externalSystemAction = (ExternalSystemTaskAction) getOrRegisterAction(project, ownerModuleName, taskData);
                        ApplicationManager.getApplication().getMessageBus().syncPublisher(KeymapListener.CHANGE_TOPIC).processCurrentKeymapChanged();
                        Settings allSettings = Settings.KEY.getData(DataManager.getInstance().getDataContext(e.getComponent()));
                        KeymapPanel keymapPanel = allSettings != null ? allSettings.find(KeymapPanel.class) : null;
                        if (keymapPanel != null) {
                            // clear actions filter
                            keymapPanel.showOption("");
                            keymapPanel.selectAction(externalSystemAction.myId);
                        }
                    }
                }
            });
        }
    }
    for (KeymapGroup keymapGroup : keymapGroupMap.values()) {
        if (isGroupFiltered(condition, keymapGroup)) {
            result.addGroup(keymapGroup);
        }
    }
    for (ActionsProvider extension : ActionsProvider.EP_NAME.getExtensions()) {
        KeymapGroup keymapGroup = extension.createGroup(condition, project);
        if (isGroupFiltered(condition, keymapGroup)) {
            result.addGroup(keymapGroup);
        }
    }
    return result;
}
Also used : KeymapGroup(com.intellij.openapi.keymap.KeymapGroup) TaskData(com.intellij.openapi.externalSystem.model.task.TaskData) Settings(com.intellij.openapi.options.ex.Settings) RunnerAndConfigurationSettings(com.intellij.execution.RunnerAndConfigurationSettings) MouseEvent(java.awt.event.MouseEvent) KeymapGroup(com.intellij.openapi.keymap.KeymapGroup) SelectExternalTaskDialog(com.intellij.openapi.externalSystem.service.ui.SelectExternalTaskDialog) Collection(java.util.Collection) ProjectSystemId(com.intellij.openapi.externalSystem.model.ProjectSystemId) Map(java.util.Map) MultiMap(com.intellij.util.containers.MultiMap)

Aggregations

MultiMap (com.intellij.util.containers.MultiMap)138 NotNull (org.jetbrains.annotations.NotNull)37 UsageInfo (com.intellij.usageView.UsageInfo)26 VirtualFile (com.intellij.openapi.vfs.VirtualFile)25 Project (com.intellij.openapi.project.Project)18 PsiElement (com.intellij.psi.PsiElement)18 ConflictsDialog (com.intellij.refactoring.ui.ConflictsDialog)16 Collection (java.util.Collection)16 Nullable (org.jetbrains.annotations.Nullable)15 Map (java.util.Map)14 File (java.io.File)11 HashSet (com.intellij.util.containers.HashSet)10 ContainerUtil (com.intellij.util.containers.ContainerUtil)9 THashSet (gnu.trove.THashSet)9 java.util (java.util)9 Module (com.intellij.openapi.module.Module)8 com.intellij.psi (com.intellij.psi)8 Pair (com.intellij.openapi.util.Pair)7 PsiFile (com.intellij.psi.PsiFile)7 ArrayList (java.util.ArrayList)7