Search in sources :

Example 31 with MessageBusConnection

use of com.intellij.util.messages.MessageBusConnection in project intellij-community by JetBrains.

the class GradleManager method runActivity.

@Override
public void runActivity(@NotNull final Project project) {
    // We want to automatically refresh linked projects on gradle service directory change.
    MessageBusConnection connection = project.getMessageBus().connect(project);
    connection.subscribe(GradleSettings.getInstance(project).getChangesTopic(), new GradleSettingsListenerAdapter() {

        @Override
        public void onServiceDirectoryPathChange(@Nullable String oldPath, @Nullable String newPath) {
            ensureProjectsRefresh();
        }

        @Override
        public void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath, @NotNull String linkedProjectPath) {
            ensureProjectsRefresh();
        }

        @Override
        public void onGradleDistributionTypeChange(DistributionType currentValue, @NotNull String linkedProjectPath) {
            ensureProjectsRefresh();
        }

        private void ensureProjectsRefresh() {
            ExternalSystemUtil.refreshProjects(project, GradleConstants.SYSTEM_ID, true);
        }
    });
    // We used to assume that gradle scripts are always named 'build.gradle' and kept path to that build.gradle file at ide settings.
    // However, it was found out that that is incorrect assumption (IDEA-109064). Now we keep paths to gradle script's directories
    // instead. However, we don't want to force old users to re-import gradle projects because of that. That's why we check gradle
    // config and re-point it from build.gradle to the parent dir if necessary.
    Map<String, String> adjustedPaths = patchLinkedProjects(project);
    if (adjustedPaths == null) {
        return;
    }
    GradleLocalSettings localSettings = GradleLocalSettings.getInstance(project);
    patchRecentTasks(adjustedPaths, localSettings);
    patchAvailableProjects(adjustedPaths, localSettings);
    patchAvailableTasks(adjustedPaths, localSettings);
}
Also used : MessageBusConnection(com.intellij.util.messages.MessageBusConnection) GradleSettingsListenerAdapter(org.jetbrains.plugins.gradle.config.GradleSettingsListenerAdapter)

Example 32 with MessageBusConnection

use of com.intellij.util.messages.MessageBusConnection in project intellij-community by JetBrains.

the class ShowUsagesAction method showElementUsages.

private void showElementUsages(final Editor editor, @NotNull final RelativePoint popupPosition, @NotNull final FindUsagesHandler handler, final int maxUsages, @NotNull final FindUsagesOptions options) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    final UsageViewSettings usageViewSettings = UsageViewSettings.getInstance();
    final UsageViewSettings savedGlobalSettings = new UsageViewSettings();
    savedGlobalSettings.loadState(usageViewSettings);
    usageViewSettings.loadState(myUsageViewSettings);
    final Project project = handler.getProject();
    UsageViewManager manager = UsageViewManager.getInstance(project);
    FindUsagesManager findUsagesManager = ((FindManagerImpl) FindManager.getInstance(project)).getFindUsagesManager();
    final UsageViewPresentation presentation = findUsagesManager.createPresentation(handler, options);
    presentation.setDetachedMode(true);
    UsageViewImpl usageView = (UsageViewImpl) manager.createUsageView(UsageTarget.EMPTY_ARRAY, Usage.EMPTY_ARRAY, presentation, null);
    if (editor != null) {
        PsiReference reference = TargetElementUtil.findReference(editor);
        if (reference != null) {
            UsageInfo2UsageAdapter origin = new UsageInfo2UsageAdapter(new UsageInfo(reference));
            usageView.setOriginUsage(origin);
        }
    }
    Disposer.register(usageView, () -> {
        myUsageViewSettings.loadState(usageViewSettings);
        usageViewSettings.loadState(savedGlobalSettings);
    });
    final MyTable table = new MyTable();
    final AsyncProcessIcon processIcon = new AsyncProcessIcon("xxx");
    addUsageNodes(usageView.getRoot(), usageView, new ArrayList<>());
    final List<Usage> usages = new ArrayList<>();
    final Set<UsageNode> visibleNodes = new LinkedHashSet<>();
    final List<UsageNode> data = collectData(usages, visibleNodes, usageView, presentation);
    final AtomicInteger outOfScopeUsages = new AtomicInteger();
    setTableModel(table, usageView, data, outOfScopeUsages, options.searchScope);
    boolean isPreviewMode = Boolean.TRUE == PreviewManager.SERVICE.preview(handler.getProject(), UsagesPreviewPanelProvider.ID, Pair.create(usageView, table), false);
    Runnable itemChosenCallback = prepareTable(table, editor, popupPosition, handler, maxUsages, options, isPreviewMode);
    @Nullable final JBPopup popup = isPreviewMode ? null : createUsagePopup(usages, visibleNodes, handler, editor, popupPosition, maxUsages, usageView, options, table, itemChosenCallback, presentation, processIcon);
    if (popup != null) {
        Disposer.register(popup, usageView);
        // show popup only if find usages takes more than 300ms, otherwise it would flicker needlessly
        Alarm alarm = new Alarm(usageView);
        alarm.addRequest(() -> showPopupIfNeedTo(popup, popupPosition), 300);
    }
    final PingEDT pingEDT = new PingEDT("Rebuild popup in EDT", o -> popup != null && popup.isDisposed(), 100, () -> {
        if (popup != null && popup.isDisposed())
            return;
        final List<UsageNode> nodes = new ArrayList<>();
        List<Usage> copy;
        synchronized (usages) {
            // open up popup as soon as several usages 've been found
            if (popup != null && !popup.isVisible() && (usages.size() <= 1 || !showPopupIfNeedTo(popup, popupPosition))) {
                return;
            }
            addUsageNodes(usageView.getRoot(), usageView, nodes);
            copy = new ArrayList<>(usages);
        }
        rebuildTable(usageView, copy, nodes, table, popup, presentation, popupPosition, !processIcon.isDisposed(), outOfScopeUsages, options.searchScope);
    });
    final MessageBusConnection messageBusConnection = project.getMessageBus().connect(usageView);
    messageBusConnection.subscribe(UsageFilteringRuleProvider.RULES_CHANGED, pingEDT::ping);
    final UsageTarget[] myUsageTarget = { new PsiElement2UsageTargetAdapter(handler.getPsiElement()) };
    Processor<Usage> collect = usage -> {
        if (!UsageViewManagerImpl.isInScope(usage, options.searchScope)) {
            if (outOfScopeUsages.getAndIncrement() == 0) {
                visibleNodes.add(USAGES_OUTSIDE_SCOPE_NODE);
                usages.add(USAGES_OUTSIDE_SCOPE_SEPARATOR);
            }
            return true;
        }
        synchronized (usages) {
            if (visibleNodes.size() >= maxUsages)
                return false;
            if (UsageViewManager.isSelfUsage(usage, myUsageTarget))
                return true;
            UsageNode node = ReadAction.compute(() -> usageView.doAppendUsage(usage));
            usages.add(usage);
            if (node != null) {
                visibleNodes.add(node);
                boolean continueSearch = true;
                if (visibleNodes.size() == maxUsages) {
                    visibleNodes.add(MORE_USAGES_SEPARATOR_NODE);
                    usages.add(MORE_USAGES_SEPARATOR);
                    continueSearch = false;
                }
                pingEDT.ping();
                return continueSearch;
            }
        }
        return true;
    };
    final ProgressIndicator indicator = FindUsagesManager.startProcessUsages(handler, handler.getPrimaryElements(), handler.getSecondaryElements(), collect, options, () -> ApplicationManager.getApplication().invokeLater(() -> {
        Disposer.dispose(processIcon);
        Container parent = processIcon.getParent();
        if (parent != null) {
            parent.remove(processIcon);
            parent.repaint();
        }
        // repaint title
        pingEDT.ping();
        synchronized (usages) {
            if (visibleNodes.isEmpty()) {
                if (usages.isEmpty()) {
                    String text = UsageViewBundle.message("no.usages.found.in", searchScopePresentableName(options));
                    hint(editor, text, handler, popupPosition, maxUsages, options, false);
                    cancel(popup);
                }
            // else all usages filtered out
            } else if (visibleNodes.size() == 1) {
                if (usages.size() == 1) {
                    //the only usage
                    Usage usage = visibleNodes.iterator().next().getUsage();
                    if (usage == USAGES_OUTSIDE_SCOPE_SEPARATOR) {
                        hint(editor, UsageViewManagerImpl.outOfScopeMessage(outOfScopeUsages.get(), options.searchScope), handler, popupPosition, maxUsages, options, true);
                    } else {
                        String message = UsageViewBundle.message("show.usages.only.usage", searchScopePresentableName(options));
                        navigateAndHint(usage, message, handler, popupPosition, maxUsages, options);
                    }
                    cancel(popup);
                } else {
                    assert usages.size() > 1 : usages;
                    // usage view can filter usages down to one
                    Usage visibleUsage = visibleNodes.iterator().next().getUsage();
                    if (areAllUsagesInOneLine(visibleUsage, usages)) {
                        String hint = UsageViewBundle.message("all.usages.are.in.this.line", usages.size(), searchScopePresentableName(options));
                        navigateAndHint(visibleUsage, hint, handler, popupPosition, maxUsages, options);
                        cancel(popup);
                    }
                }
            } else {
                if (popup != null) {
                    String title = presentation.getTabText();
                    boolean shouldShowMoreSeparator = visibleNodes.contains(MORE_USAGES_SEPARATOR_NODE);
                    String fullTitle = getFullTitle(usages, title, shouldShowMoreSeparator, visibleNodes.size() - (shouldShowMoreSeparator ? 1 : 0), false);
                    ((AbstractPopup) popup).setCaption(fullTitle);
                }
            }
        }
    }, project.getDisposed()));
    if (popup != null) {
        Disposer.register(popup, indicator::cancel);
    }
}
Also used : UIUtil(com.intellij.util.ui.UIUtil) AllIcons(com.intellij.icons.AllIcons) MessageType(com.intellij.openapi.ui.MessageType) VirtualFile(com.intellij.openapi.vfs.VirtualFile) ColumnInfo(com.intellij.util.ui.ColumnInfo) FileEditorLocation(com.intellij.openapi.fileEditor.FileEditorLocation) TableCellRenderer(javax.swing.table.TableCellRenderer) ReadAction(com.intellij.openapi.application.ReadAction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AsyncProcessIcon(com.intellij.util.ui.AsyncProcessIcon) Disposer(com.intellij.openapi.util.Disposer) MouseAdapter(java.awt.event.MouseAdapter) FeatureUsageTracker(com.intellij.featureStatistics.FeatureUsageTracker) TextEditor(com.intellij.openapi.fileEditor.TextEditor) com.intellij.usages.impl(com.intellij.usages.impl) HintUtil(com.intellij.codeInsight.hint.HintUtil) FindManagerImpl(com.intellij.find.impl.FindManagerImpl) PreviewManager(com.intellij.openapi.preview.PreviewManager) PsiReference(com.intellij.psi.PsiReference) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) AbstractPopup(com.intellij.ui.popup.AbstractPopup) KeyEvent(java.awt.event.KeyEvent) FileEditor(com.intellij.openapi.fileEditor.FileEditor) KeymapUtil(com.intellij.openapi.keymap.KeymapUtil) com.intellij.ui(com.intellij.ui) HintUpdateSupply(com.intellij.ui.popup.HintUpdateSupply) FindManager(com.intellij.find.FindManager) Nullable(org.jetbrains.annotations.Nullable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) IdeFocusManager(com.intellij.openapi.wm.IdeFocusManager) Processor(com.intellij.util.Processor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) XmlStringUtil(com.intellij.xml.util.XmlStringUtil) FindSettings(com.intellij.find.FindSettings) NotNull(org.jetbrains.annotations.NotNull) RelativePoint(com.intellij.ui.awt.RelativePoint) java.util(java.util) ArrayUtil(com.intellij.util.ArrayUtil) UsagesPreviewPanelProvider(com.intellij.find.UsagesPreviewPanelProvider) NonNls(org.jetbrains.annotations.NonNls) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) UsageInfo(com.intellij.usageView.UsageInfo) SearchScope(com.intellij.psi.search.SearchScope) KeyAdapter(java.awt.event.KeyAdapter) AtomicReference(java.util.concurrent.atomic.AtomicReference) MessageBusConnection(com.intellij.util.messages.MessageBusConnection) Comparing(com.intellij.openapi.util.Comparing) com.intellij.find.findUsages(com.intellij.find.findUsages) PsiElement(com.intellij.psi.PsiElement) Project(com.intellij.openapi.project.Project) ListTableModel(com.intellij.util.ui.ListTableModel) DataManager(com.intellij.ide.DataManager) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) PlatformIcons(com.intellij.util.PlatformIcons) UsageFilteringRuleProvider(com.intellij.usages.rules.UsageFilteringRuleProvider) StringUtil(com.intellij.openapi.util.text.StringUtil) TableColumn(javax.swing.table.TableColumn) com.intellij.usages(com.intellij.usages) AsyncEditorLoader(com.intellij.openapi.fileEditor.impl.text.AsyncEditorLoader) ModelDiff(com.intellij.ide.util.gotoByName.ModelDiff) Editor(com.intellij.openapi.editor.Editor) PopupUtil(com.intellij.openapi.ui.popup.util.PopupUtil) JBPopup(com.intellij.openapi.ui.popup.JBPopup) UsageViewUtil(com.intellij.usageView.UsageViewUtil) MouseEvent(java.awt.event.MouseEvent) java.awt(java.awt) com.intellij.openapi.actionSystem(com.intellij.openapi.actionSystem) JBTable(com.intellij.ui.table.JBTable) DumbAwareAction(com.intellij.openapi.project.DumbAwareAction) PopupChooserBuilder(com.intellij.openapi.ui.popup.PopupChooserBuilder) JBPopupFactory(com.intellij.openapi.ui.popup.JBPopupFactory) Pair(com.intellij.openapi.util.Pair) TargetElementUtil(com.intellij.codeInsight.TargetElementUtil) UsageViewBundle(com.intellij.usageView.UsageViewBundle) Navigatable(com.intellij.pom.Navigatable) HintManager(com.intellij.codeInsight.hint.HintManager) TransactionGuard(com.intellij.openapi.application.TransactionGuard) Alarm(com.intellij.util.Alarm) javax.swing(javax.swing) MessageBusConnection(com.intellij.util.messages.MessageBusConnection) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) JBPopup(com.intellij.openapi.ui.popup.JBPopup) UsageInfo(com.intellij.usageView.UsageInfo) AbstractPopup(com.intellij.ui.popup.AbstractPopup) AsyncProcessIcon(com.intellij.util.ui.AsyncProcessIcon) PsiReference(com.intellij.psi.PsiReference) FindManagerImpl(com.intellij.find.impl.FindManagerImpl) Project(com.intellij.openapi.project.Project) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Alarm(com.intellij.util.Alarm) Nullable(org.jetbrains.annotations.Nullable)

Example 33 with MessageBusConnection

use of com.intellij.util.messages.MessageBusConnection in project intellij-community by JetBrains.

the class ProjectWideFacetListenersRegistryImpl method onModuleAdded.

private void onModuleAdded(final Module module) {
    final FacetManager facetManager = FacetManager.getInstance(module);
    final Facet[] facets = facetManager.getAllFacets();
    for (Facet facet : facets) {
        onFacetAdded(facet);
    }
    final MessageBusConnection connection = module.getMessageBus().connect();
    myModule2Connection.put(module, connection);
    connection.subscribe(FacetManager.FACETS_TOPIC, myFacetListener);
}
Also used : MessageBusConnection(com.intellij.util.messages.MessageBusConnection)

Example 34 with MessageBusConnection

use of com.intellij.util.messages.MessageBusConnection in project intellij-community by JetBrains.

the class GeneratedSourceFileChangeTrackerImpl method projectOpened.

@Override
public void projectOpened() {
    final Update check = new Update("check for changes in generated files") {

        @Override
        public void run() {
            checkFiles();
        }
    };
    EditorFactory.getInstance().getEventMulticaster().addDocumentListener(new DocumentAdapter() {

        @Override
        public void documentChanged(DocumentEvent e) {
            VirtualFile file = myDocumentManager.getFile(e.getDocument());
            if (file != null) {
                myFilesToCheck.add(file);
                myCheckingQueue.queue(check);
            }
        }
    }, myProject);
    MessageBusConnection connection = myProject.getMessageBus().connect();
    connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerAdapter() {

        @Override
        public void fileContentReloaded(@NotNull VirtualFile file, @NotNull Document document) {
            myFilesToCheck.remove(file);
            if (myEditedGeneratedFiles.remove(file)) {
                myEditorNotifications.updateNotifications(file);
            }
        }
    });
    connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {

        @Override
        public void fileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
            myEditedGeneratedFiles.remove(file);
        }
    });
    connection.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() {

        @Override
        public void rootsChanged(ModuleRootEvent event) {
            myFilesToCheck.addAll(myEditedGeneratedFiles);
            myEditedGeneratedFiles.clear();
            myCheckingQueue.queue(check);
        }
    });
    myCheckingQueue.activate();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) FileEditorManager(com.intellij.openapi.fileEditor.FileEditorManager) MessageBusConnection(com.intellij.util.messages.MessageBusConnection) FileDocumentManagerAdapter(com.intellij.openapi.fileEditor.FileDocumentManagerAdapter) ModuleRootEvent(com.intellij.openapi.roots.ModuleRootEvent) DocumentAdapter(com.intellij.openapi.editor.event.DocumentAdapter) Update(com.intellij.util.ui.update.Update) DocumentEvent(com.intellij.openapi.editor.event.DocumentEvent) Document(com.intellij.openapi.editor.Document) FileEditorManagerListener(com.intellij.openapi.fileEditor.FileEditorManagerListener) ModuleRootListener(com.intellij.openapi.roots.ModuleRootListener)

Example 35 with MessageBusConnection

use of com.intellij.util.messages.MessageBusConnection in project intellij-community by JetBrains.

the class ExternalSystemProjectsWatcher method start.

public synchronized void start() {
    if (ExternalSystemUtil.isNoBackgroundMode()) {
        return;
    }
    myUpdatesQueue.activate();
    final MessageBusConnection myBusConnection = myProject.getMessageBus().connect(myChangedDocumentsQueue);
    myBusConnection.subscribe(VirtualFileManager.VFS_CHANGES, new MyFileChangeListener(this));
    makeUserAware(myChangedDocumentsQueue, myProject);
    myChangedDocumentsQueue.activate();
    DocumentAdapter myDocumentListener = new DocumentAdapter() {

        @Override
        public void documentChanged(DocumentEvent event) {
            Document doc = event.getDocument();
            VirtualFile file = FileDocumentManager.getInstance().getFile(doc);
            if (file == null)
                return;
            String externalProjectPath = getRelatedExternalProjectPath(file);
            if (externalProjectPath == null)
                return;
            synchronized (myChangedDocuments) {
                myChangedDocuments.add(doc);
            }
            myChangedDocumentsQueue.queue(new Update(ExternalSystemProjectsWatcher.this) {

                @Override
                public void run() {
                    final Document[] copy;
                    synchronized (myChangedDocuments) {
                        copy = myChangedDocuments.toArray(new Document[myChangedDocuments.size()]);
                        myChangedDocuments.clear();
                    }
                    ExternalSystemUtil.invokeLater(myProject, () -> new WriteAction() {

                        @Override
                        protected void run(@NotNull Result result) throws Throwable {
                            for (Document each : copy) {
                                PsiDocumentManager.getInstance(myProject).commitDocument(each);
                                ((FileDocumentManagerImpl) FileDocumentManager.getInstance()).saveDocument(each, false);
                            }
                        }
                    }.execute());
                }
            });
        }
    };
    EditorFactory.getInstance().getEventMulticaster().addDocumentListener(myDocumentListener, myBusConnection);
    ServiceManager.getService(ExternalSystemProgressNotificationManager.class).addNotificationListener(this);
    updateWatchedRoots(true);
    Disposer.register(myChangedDocumentsQueue, () -> myFilesPointers.clear());
}
Also used : MessageBusConnection(com.intellij.util.messages.MessageBusConnection) Document(com.intellij.openapi.editor.Document) Update(com.intellij.util.ui.update.Update) ExternalSystemProgressNotificationManager(com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager)

Aggregations

MessageBusConnection (com.intellij.util.messages.MessageBusConnection)81 Project (com.intellij.openapi.project.Project)16 NotNull (org.jetbrains.annotations.NotNull)15 Module (com.intellij.openapi.module.Module)11 ModuleRootEvent (com.intellij.openapi.roots.ModuleRootEvent)10 ModuleListener (com.intellij.openapi.project.ModuleListener)8 ModuleRootListener (com.intellij.openapi.roots.ModuleRootListener)8 VirtualFile (com.intellij.openapi.vfs.VirtualFile)7 Disposable (com.intellij.openapi.Disposable)6 Document (com.intellij.openapi.editor.Document)6 VFileEvent (com.intellij.openapi.vfs.newvfs.events.VFileEvent)5 Update (com.intellij.util.ui.update.Update)5 ApplicationManager (com.intellij.openapi.application.ApplicationManager)4 StringUtil (com.intellij.openapi.util.text.StringUtil)4 ProcessHandler (com.intellij.execution.process.ProcessHandler)3 Application (com.intellij.openapi.application.Application)3 FileDocumentManagerAdapter (com.intellij.openapi.fileEditor.FileDocumentManagerAdapter)3 ModuleRootAdapter (com.intellij.openapi.roots.ModuleRootAdapter)3 VFileCreateEvent (com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent)3 File (java.io.File)3