Java Code Examples for com.intellij.util.messages.MessageBusConnection#subscribe()

The following examples show how to use com.intellij.util.messages.MessageBusConnection#subscribe() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EditorUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void runBatchFoldingOperationOutsideOfBulkUpdate(@Nonnull Editor editor, @Nonnull Runnable operation) {
  DocumentEx document = ObjectUtils.tryCast(editor.getDocument(), DocumentEx.class);
  if (document != null && document.isInBulkUpdate()) {
    MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect();
    disposeWithEditor(editor, connection::disconnect);
    connection.subscribe(DocumentBulkUpdateListener.TOPIC, new DocumentBulkUpdateListener.Adapter() {
      @Override
      public void updateFinished(@Nonnull Document doc) {
        if (doc == editor.getDocument()) {
          editor.getFoldingModel().runBatchFoldingOperation(operation);
          connection.disconnect();
        }
      }
    });
  }
  else {
    editor.getFoldingModel().runBatchFoldingOperation(operation);
  }
}
 
Example 2
Source File: TextEditorComponent.java    From consulo with Apache License 2.0 6 votes vote down vote up
public TextEditorComponent(@Nonnull final Project project, @Nonnull final VirtualFile file, @Nonnull final DesktopTextEditorImpl textEditor) {
  super(new BorderLayout(), textEditor);

  myProject = project;
  myFile = file;
  myTextEditor = textEditor;

  myDocument = FileDocumentManager.getInstance().getDocument(myFile);
  LOG.assertTrue(myDocument != null);
  myDocument.addDocumentListener(new MyDocumentListener(), this);

  myEditor = createEditor();
  add(myEditor.getComponent(), BorderLayout.CENTER);
  myModified = isModifiedImpl();
  myValid = isEditorValidImpl();
  LOG.assertTrue(myValid);

  MyVirtualFileListener myVirtualFileListener = new MyVirtualFileListener();
  myFile.getFileSystem().addVirtualFileListener(myVirtualFileListener);
  Disposer.register(this, () -> myFile.getFileSystem().removeVirtualFileListener(myVirtualFileListener));
  MessageBusConnection myConnection = project.getMessageBus().connect(this);
  myConnection.subscribe(FileTypeManager.TOPIC, new MyFileTypeListener());

  myEditorHighlighterUpdater = new EditorHighlighterUpdater(myProject, this, (EditorEx)myEditor, myFile);
}
 
Example 3
Source File: EditorHistoryManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Inject
EditorHistoryManager(@Nonnull Project project) {
  myProject = project;

  MessageBusConnection connection = project.getMessageBus().connect();

  connection.subscribe(UISettingsListener.TOPIC, new UISettingsListener() {
    @Override
    public void uiSettingsChanged(UISettings uiSettings) {
      trimToSize();
    }
  });

  connection.subscribe(FileEditorManagerListener.Before.FILE_EDITOR_MANAGER, new FileEditorManagerListener.Before.Adapter() {
    @Override
    public void beforeFileClosed(@Nonnull FileEditorManager source, @Nonnull VirtualFile file) {
      updateHistoryEntry(file, false);
    }
  });
  connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new MyEditorManagerListener());
}
 
Example 4
Source File: PreviewView.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public PreviewView(@NotNull Project project) {
  this.project = project;
  currentFile = new EventStream<>();
  activeOutlines = new EventStream<>(ImmutableList.of());
  flutterAnalysisServer = FlutterDartAnalysisServer.getInstance(project);

  inspectorGroupManagerService = InspectorGroupManagerService.getInstance(project);

  // Show preview for the file selected when the view is being opened.
  final VirtualFile[] selectedFiles = FileEditorManager.getInstance(project).getSelectedFiles();
  if (selectedFiles.length != 0) {
    setSelectedFile(selectedFiles[0]);
  }

  final FileEditor[] selectedEditors = FileEditorManager.getInstance(project).getSelectedEditors();
  if (selectedEditors.length != 0) {
    setSelectedEditor(selectedEditors[0]);
  }

  // Listen for selecting files.
  final MessageBusConnection bus = project.getMessageBus().connect(project);
  bus.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {
    @Override
    public void selectionChanged(@NotNull FileEditorManagerEvent event) {
      setSelectedFile(event.getNewFile());
      setSelectedEditor(event.getNewEditor());
    }
  });

  widgetEditToolbar = new WidgetEditToolbar(
    FlutterSettings.getInstance().isEnableHotUi(),
    activeOutlines,
    currentFile,
    project,
    flutterAnalysisServer
  );
}
 
Example 5
Source File: SemServiceImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Inject
public SemServiceImpl(Project project, PsiManager psiManager) {
  myProject = project;
  final MessageBusConnection connection = project.getMessageBus().connect();
  connection.subscribe(PsiModificationTracker.TOPIC, new PsiModificationTracker.Listener() {
    @Override
    public void modificationCountChanged() {
      if (!isInsideAtomicChange()) {
        clearCache();
      }
    }
  });

  ((PsiManagerEx)psiManager).registerRunnableToRunOnChange(() -> {
    if (!isInsideAtomicChange()) {
      clearCache();
    }
  });


  LowMemoryWatcher.register(() -> {
    if (myCreatingSem.get() == 0) {
      clearCache();
    }
    //System.out.println("SemService cache flushed");
  }, project);
}
 
Example 6
Source File: RecentProjectsManagerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected RecentProjectsManagerBase(@Nonnull Application application) {
  MessageBusConnection connection = application.getMessageBus().connect();
  connection.subscribe(AppLifecycleListener.TOPIC, new MyAppLifecycleListener());
  if (!application.isHeadlessEnvironment()) {
    connection.subscribe(ProjectManager.TOPIC, new MyProjectListener());
  }
}
 
Example 7
Source File: JSGraphQLLanguageUIProjectService.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
public JSGraphQLLanguageUIProjectService(@NotNull final Project project) {

        myProject = project;

        final MessageBusConnection messageBusConnection = project.getMessageBus().connect(this);

        // tool window
        myToolWindowManager = new JSGraphQLLanguageToolWindowManager(project, GRAPH_QL_TOOL_WINDOW_NAME, GRAPH_QL_TOOL_WINDOW_NAME, JSGraphQLIcons.UI.GraphQLToolwindow);
        Disposer.register(this, this.myToolWindowManager);

        // listen for editor file tab changes to update the list of current errors
        messageBusConnection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, this);

        // add editor headers to already open files since we've only just added the listener for fileOpened()
        final FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
        for (VirtualFile virtualFile : fileEditorManager.getOpenFiles()) {
            UIUtil.invokeLaterIfNeeded(() -> {
                insertEditorHeaderComponentIfApplicable(fileEditorManager, virtualFile);
            });
        }

        // listen for configuration changes
        messageBusConnection.subscribe(JSGraphQLConfigurationListener.TOPIC, this);

        // finally init the tool window tabs
        initToolWindow();

        // and notify to configure the schema
        project.putUserData(GraphQLParserDefinition.JSGRAPHQL_ACTIVATED, true);
        EditorNotifications.getInstance(project).updateAllNotifications();
    }
 
Example 8
Source File: MountainLionNotifications.java    From consulo with Apache License 2.0 5 votes vote down vote up
private MountainLionNotifications() {
  final MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect();
  connection.subscribe(ApplicationActivationListener.TOPIC, new ApplicationActivationListener.Adapter() {
    @Override
    public void applicationActivated(IdeFrame ideFrame) {
      cleanupDeliveredNotifications();
    }
  });
  connection.subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener() {
    @Override
    public void appClosing() {
      cleanupDeliveredNotifications();
    }
  });
}
 
Example 9
Source File: ParametersPanel.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 5 votes vote down vote up
private void initializeUi() {
    graphConsoleView.getGlobalParametersTab().add(globalParamEditor.getComponent(), BorderLayout.CENTER);
    service.registerParametersProvider(this);
    MessageBusConnection mbConnection = messageBus.connect();
    mbConnection.subscribe(QueryParametersRetrievalErrorEvent.QUERY_PARAMETERS_RETRIEVAL_ERROR_EVENT_TOPIC,
            (exception, editor) -> {
                if (editor == null) {
                    return;
                }
                String errorMessage;
                if (exception.getMessage() != null) {
                    errorMessage = String.format("%s: %s", PARAMS_ERROR_COMMON_MSG, exception.getMessage());
                } else {
                    errorMessage = PARAMS_ERROR_COMMON_MSG;
                }
                HintManager.getInstance().showErrorHint(editor, errorMessage);
            });

    mbConnection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {
        // If file opened, fileOpenedSync->selectionChanged->fileOpened are called
        @Override
        public void selectionChanged(@NotNull FileEditorManagerEvent event) {
            releaseFileSpecificEditor(event.getOldFile());
            VirtualFile newFile = event.getNewFile();
            if (newFile != null && FileTypeExtensionUtil.isCypherFileTypeExtension(newFile.getExtension()) &&
                    project.getComponent(DataSourcesComponent.class).getDataSourceContainer().isDataSourceExists(getTabTitle(newFile))) {
                setupFileSpecificEditor(project, newFile);
            }
        }
    });
}
 
Example 10
Source File: DesktopIconDeferrerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Inject
public DesktopIconDeferrerImpl(Application application) {
  final MessageBusConnection connection = application.getMessageBus().connect();
  connection.subscribe(PsiModificationTracker.TOPIC, this::clear);
  connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() {
    @Override
    public void projectClosed(@Nonnull Project project, @Nonnull UIAccess uiAccess) {
      clear();
    }
  });
  LowMemoryWatcher.register(this::clear, this);
}
 
Example 11
Source File: RecentProjectPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
FilePathChecker(Runnable callback, Collection<String> paths) {
  myCallback = callback;
  myPaths = paths;
  MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(this);
  connection.subscribe(ApplicationActivationListener.TOPIC, this);
  connection.subscribe(PowerSaveMode.TOPIC, this);
  onAppStateChanged();
}
 
Example 12
Source File: TodoView.java    From consulo with Apache License 2.0 5 votes vote down vote up
public TodoView(@Nonnull Project project) {
  myProject = project;

  state.all.arePackagesShown = true;
  state.all.isAutoScrollToSource = true;

  state.current.isAutoScrollToSource = true;

  MessageBusConnection connection = project.getMessageBus().connect(this);
  connection.subscribe(TodoConfiguration.PROPERTY_CHANGE, new MyPropertyChangeListener());
  connection.subscribe(FileTypeManager.TOPIC, new MyFileTypeListener());
  connection.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, myVcsListener);
}
 
Example 13
Source File: WidgetPerfTipsPanel.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public WidgetPerfTipsPanel(Disposable parentDisposable, @NotNull FlutterApp app) {
  setLayout(new VerticalLayout(5));

  add(new JSeparator());

  perfManager = FlutterWidgetPerfManager.getInstance(app.getProject());
  perfTips = new JPanel();
  perfTips.setLayout(new VerticalLayout(0));

  linkListener = (source, tip) -> handleTipSelection(tip);
  final Project project = app.getProject();
  final MessageBusConnection bus = project.getMessageBus().connect(project);
  final FileEditorManagerListener listener = new FileEditorManagerListener() {
    @Override
    public void selectionChanged(@NotNull FileEditorManagerEvent event) {
      selectedEditorChanged();
    }
  };
  selectedEditorChanged();
  bus.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, listener);

  // Computing performance tips is somewhat expensive so we don't want to
  // compute them too frequently. Performance tips are only computed when
  // new performance stats are available but performance stats are updated
  // at 60fps so to be conservative we delay computing perf tips.
  final Timer perfTipComputeDelayTimer = new Timer(PERF_TIP_COMPUTE_DELAY, this::onComputePerfTips);
  perfTipComputeDelayTimer.start();
  Disposer.register(parentDisposable, perfTipComputeDelayTimer::stop);
}
 
Example 14
Source File: FileEditorManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected void projectOpened(@Nonnull MessageBusConnection connection) {
  //myFocusWatcher.install(myWindows.getComponent ());
  getMainSplitters().startListeningFocus();

  final FileStatusManager fileStatusManager = FileStatusManager.getInstance(myProject);
  if (fileStatusManager != null) {
    /*
      Updates tabs colors
     */
    final MyFileStatusListener myFileStatusListener = new MyFileStatusListener();
    fileStatusManager.addFileStatusListener(myFileStatusListener, myProject);
  }
  connection.subscribe(FileTypeManager.TOPIC, new MyFileTypeListener());
  connection.subscribe(ProjectTopics.PROJECT_ROOTS, new MyRootsListener());

  /*
    Updates tabs names
   */
  final MyVirtualFileListener myVirtualFileListener = new MyVirtualFileListener();
  VirtualFileManager.getInstance().addVirtualFileListener(myVirtualFileListener, myProject);
  /*
    Extends/cuts number of opened tabs. Also updates location of tabs.
   */
  connection.subscribe(UISettingsListener.TOPIC, new MyUISettingsListener());

  StartupManager.getInstance(myProject).registerPostStartupActivity((DumbAwareRunnable)() -> {
    if (myProject.isDisposed()) return;
    setTabsMode(UISettings.getInstance().getEditorTabPlacement() != UISettings.TABS_NONE);

    ToolWindowManager.getInstance(myProject).invokeLater(() -> {
      if (!myProject.isDisposed()) {
        CommandProcessor.getInstance().executeCommand(myProject, () -> {
          ApplicationManager.getApplication().invokeLater(() -> {
            long currentTime = System.nanoTime();
            Long startTime = myProject.getUserData(ProjectImpl.CREATION_TIME);
            if (startTime != null) {
              LOG.info("Project opening took " + (currentTime - startTime) / 1000000 + " ms");
              PluginManagerCore.dumpPluginClassStatistics(LOG);
            }
          }, myProject.getDisposed());
          // group 1
        }, "", null);
      }
    });
  });
}
 
Example 15
Source File: RemoteRevisionsCache.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Inject
private RemoteRevisionsCache(final Project project) {
  myProject = project;
  myLock = new Object();

  myRemoteRevisionsNumbersCache = new RemoteRevisionsNumbersCache(myProject);
  myRemoteRevisionsStateCache = new RemoteRevisionsStateCache(myProject);

  myChangeDecorator = new RemoteStatusChangeNodeDecorator(this);

  myVcsManager = ProjectLevelVcsManager.getInstance(project);
  MessageBusConnection connection = myProject.getMessageBus().connect();
  connection.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, this);
  connection.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED_IN_PLUGIN, this);
  myKinds = new HashMap<>();

  final VcsConfiguration vcsConfiguration = VcsConfiguration.getInstance(myProject);
  myControlledCycle = new ControlledCycle(project, new Getter<Boolean>() {
    @Override
    public Boolean get() {
      final boolean shouldBeDone = vcsConfiguration.isChangedOnServerEnabled() && myVcsManager.hasActiveVcss();

      if (shouldBeDone) {
        boolean somethingChanged = myRemoteRevisionsNumbersCache.updateStep();
        somethingChanged |= myRemoteRevisionsStateCache.updateStep();
        if (somethingChanged) {
          ApplicationManager.getApplication().runReadAction(new Runnable() {
            @Override
            public void run() {
              if (!myProject.isDisposed()) {
                myProject.getMessageBus().syncPublisher(REMOTE_VERSION_CHANGED).run();
              }
            }
          });
        }
      }
      return shouldBeDone;
    }
  }, "Finishing \"changed on server\" update", DEFAULT_REFRESH_INTERVAL);

  updateRoots();

  if ((! myProject.isDefault()) && vcsConfiguration.isChangedOnServerEnabled()) {
    ((ProjectLevelVcsManagerImpl) myVcsManager).addInitializationRequest(VcsInitObject.REMOTE_REVISIONS_CACHE,
                                                                         new Runnable() {
                                                                           public void run() {
                                                                             // do not start if there're no vcses
                                                                             if (! myVcsManager.hasActiveVcss() || ! vcsConfiguration. isChangedOnServerEnabled()) return;
                                                                             myControlledCycle.startIfNotStarted(-1);
                                                                           }
                                                                         });
  }
}
 
Example 16
Source File: GraphQLSchemaChangeListener.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
public GraphQLSchemaChangeListener(Project project) {
    myProject = project;
    psiManager = PsiManager.getInstance(myProject);
    listener = new PsiTreeChangeAdapter() {

        private void checkForSchemaChange(PsiTreeChangeEvent event) {
            if (myProject.isDisposed()) {
                psiManager.removePsiTreeChangeListener(listener);
                return;
            }
            if (event.getFile() instanceof GraphQLFile) {
                if (affectsGraphQLSchema(event)) {
                    signalSchemaChanged();
                }
            }
            if (event.getFile() instanceof JSGraphQLEndpointFile) {
                // always consider the schema changed when editing an endpoint file
                signalSchemaChanged();
            }
            if (event.getParent() instanceof PsiLanguageInjectionHost) {
                GraphQLInjectionSearchHelper graphQLInjectionSearchHelper = ServiceManager.getService(GraphQLInjectionSearchHelper.class);
                if (graphQLInjectionSearchHelper != null && graphQLInjectionSearchHelper.isJSGraphQLLanguageInjectionTarget(event.getParent())) {
                    // change in injection target
                    signalSchemaChanged();
                }
            }
            if (event.getFile() instanceof JsonFile) {
                boolean introspectionJsonUpdated = false;
                if (event.getFile().getUserData(GraphQLSchemaKeys.GRAPHQL_INTROSPECTION_JSON_TO_SDL) != null) {
                    introspectionJsonUpdated = true;
                } else {
                    final VirtualFile virtualFile = event.getFile().getVirtualFile();
                    if (virtualFile != null && Boolean.TRUE.equals(virtualFile.getUserData(GraphQLSchemaKeys.IS_GRAPHQL_INTROSPECTION_JSON))) {
                        introspectionJsonUpdated = true;
                    }
                }
                if(introspectionJsonUpdated) {
                    signalSchemaChanged();
                }
            }
        }

        @Override
        public void propertyChanged(@NotNull PsiTreeChangeEvent event) {
            checkForSchemaChange(event);
        }

        @Override
        public void childAdded(@NotNull PsiTreeChangeEvent event) {
            checkForSchemaChange(event);
        }

        @Override
        public void childRemoved(@NotNull PsiTreeChangeEvent event) {
            checkForSchemaChange(event);
        }

        @Override
        public void childMoved(@NotNull PsiTreeChangeEvent event) {
            checkForSchemaChange(event);
        }

        @Override
        public void childReplaced(@NotNull PsiTreeChangeEvent event) {
            checkForSchemaChange(event);
        }

        @Override
        public void childrenChanged(@NotNull PsiTreeChangeEvent event) {
            if (event instanceof PsiTreeChangeEventImpl) {
                if (!((PsiTreeChangeEventImpl) event).isGenericChange()) {
                    // ignore the generic event which fires for all other cases above
                    // if it's not the generic case, children have been replaced, e.g. using the commenter
                    checkForSchemaChange(event);
                }
            }
        }
    };
    psiManager.addPsiTreeChangeListener(listener);

    // also consider the schema changed when the underlying schema configuration files change
    final MessageBusConnection connection = myProject.getMessageBus().connect();
    connection.subscribe(GraphQLConfigManager.TOPIC, this::signalSchemaChanged);
}
 
Example 17
Source File: ViewportAdjustmentExecutor.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
void registerListeners(@NotNull MessageBusConnection messageBusConnection) {
  messageBusConnection.subscribe(
      fileEditorManagerListener.FILE_EDITOR_MANAGER, fileEditorManagerListener);
}
 
Example 18
Source File: DotNetLibraryAnalyzerComponent.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
/**
 * Map of
 * <p/>
 * key - File
 * <p/>
 * value -
 * key - typeName
 * value
 * - p1 - libraryName
 * - p2 - namespace
 */
//private final Map<Module, MultiMap<String, NamespaceReference>> myCacheMap = new ConcurrentWeakKeyHashMap<Module, MultiMap<String, NamespaceReference>>();

@Inject
public DotNetLibraryAnalyzerComponent(Project project)
{
	if(!EarlyAccessProgramManager.is(EapDescriptor.class))
	{
		return;
	}

	MessageBusConnection connect = project.getMessageBus().connect();

	connect.subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener()
	{
		@Override
		public void enteredDumbMode()
		{
			Module[] modules = ModuleManager.getInstance(project).getModules();
			for(Module module : modules)
			{
				DotNetSimpleModuleExtension extension = ModuleUtilCore.getExtension(module, DotNetSimpleModuleExtension.class);
				if(extension == null)
				{
					continue;
				}
				runAnalyzerFor(extension);
			}
		}

		@Override
		public void exitDumbMode()
		{

		}
	});

	connect.subscribe(ModuleExtension.CHANGE_TOPIC, new ModuleExtensionChangeListener()
	{
		@Override
		public void beforeExtensionChanged(@Nonnull ModuleExtension<?> moduleExtension, @Nonnull final ModuleExtension<?> moduleExtension2)
		{
			if(moduleExtension2 instanceof DotNetSimpleModuleExtension && moduleExtension2.isEnabled())
			{
				ApplicationManager.getApplication().invokeLater(new Runnable()
				{
					@Override
					public void run()
					{
						runAnalyzerFor((DotNetSimpleModuleExtension) moduleExtension2);
					}
				});
			}
		}
	});

}
 
Example 19
Source File: GradleMonitor.java    From spring-javaformat with Apache License 2.0 4 votes vote down vote up
public GradleMonitor(Project project, Trigger trigger) {
	super(project, trigger);
	MessageBusConnection messageBus = project.getMessageBus().connect();
	messageBus.subscribe(ProjectDataImportListener.TOPIC, (path) -> check());
}
 
Example 20
Source File: PreexistingSelectionDispatcher.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
void registerListeners(@NotNull MessageBusConnection messageBusConnection) {
  messageBusConnection.subscribe(
      fileEditorManagerListener.FILE_EDITOR_MANAGER, fileEditorManagerListener);
}