对于想了解Meteor文档中的messages-count示例如何工作?的读者,本文将是一篇不可错过的文章,我们将详细介绍messageword,并且为您提供关于com.intellij.util.m
对于想了解Meteor文档中的messages-count示例如何工作?的读者,本文将是一篇不可错过的文章,我们将详细介绍message word,并且为您提供关于com.intellij.util.messages.impl.MessageBusImpl的实例源码、com.intellij.util.messages.MessageBusConnection的实例源码、com.intellij.util.messages.MessageBus的实例源码、com.intellij.util.messages.MessageHandler的实例源码的有价值信息。
本文目录一览:- Meteor文档中的messages-count示例如何工作?(message word)
- com.intellij.util.messages.impl.MessageBusImpl的实例源码
- com.intellij.util.messages.MessageBusConnection的实例源码
- com.intellij.util.messages.MessageBus的实例源码
- com.intellij.util.messages.MessageHandler的实例源码
Meteor文档中的messages-count示例如何工作?(message word)
无法完全从文档中理解此示例…我尝试以多种方式运行该示例,以便观察其工作原理,等等。
您如何订阅?我们可以包括完成这项工作所需的客户端代码吗?
是否有一个名为的收藏messages-count
?是Room
消息集合吗?我们可以在示例中包含集合定义吗?
任何提示都很棒!
注意 :这是最初发布此问题(2012年5月)时显示的代码。现在更简单了。
// server: publish the current size of a collectionMeteor.publish("messages-count", function (roomId) { var self = this; var uuid = Meteor.uuid(); var count = 0; handle = Room.find({room_id: roomId}).observe({ added: function (doc, idx) { count++; self.set("messages-count", uuid, "count", count); self.flush(); }, removed: function (doc, idx) { count--; self.set("messages-count", uuid, "count", count); self.flush(); } // don''t care about moved or changed }); // remove data and turn off observe when client unsubs self.onStop(function () { handle.stop(); self.unset("messages-count", uuid, "count"); self.flush(); });});
答案1
小编典典感谢您提示我写一个更清晰的解释。这是带有我的评论的完整示例。我已经清理了一些错误和不一致之处。下一个文档版本将使用此功能。
Meteor.publish
非常灵活。它不仅限于将现有的MongoDB集合发布到客户端:我们可以发布任何我们想要的东西。具体来说,Meteor.publish
定义客户可以订阅的一
组文档
。每个文档都属于某个集合名称(一个字符串),具有一个唯一的_id
字段,然后具有一组JSON属性。当集合中的文档发生更改时,服务器会将更改向下发送给每个订阅的客户端,以使客户端保持最新状态。
我们将在此处定义一个名为的文档集,该文档集"counts-by-room"
包含一个名为的集合中的单个文档"counts"
。该文档将具有两个字段:一个roomId
具有房间ID的字段,以及count
:该房间中消息的总数。没有名为的实际MongoDB集合counts
。这只是Meteor服务器将向下发送给客户_端的_ 集合的名称,并存储在名为的 客户端 集合中counts
。
为此,我们的publish函数采用一个roomId
来自客户端的参数,并观察对该房间中所有Messages(在其他位置定义)的查询。我们可以在observeChanges
这里使用更高效的观察查询形式,因为我们不需要完整的文档,而只是知道添加或删除了一个新文档。每当添加新消息并添加roomId
我们感兴趣的消息时,我们的回调都会增加内部计数,然后将具有更新后总数的新文档发布到客户端。当删除一条消息时,它将减少计数并向客户端发送更新。
首次调用时observeChanges
,added
对于每个已存在的消息,将立即运行一些回调。然后,无论何时添加或删除邮件,将来的更改都会触发。
我们的发布功能还注册了一个onStop
处理程序,以在客户端退订(手动或断开连接)时进行清理。该处理程序从客户端删除属性,并取消运行observeChanges
。
每次新客户端订阅时"counts-by-room"
,都会运行publish函数,因此每个客户端都将observeChanges
代表其运行。
// server: publish the current size of a collectionMeteor.publish("counts-by-room", function (roomId) { var self = this; var count = 0; var initializing = true; var handle = Messages.find({room_id: roomId}).observeChanges({ added: function (doc, idx) { count++; if (!initializing) self.changed("counts", roomId, {count: count}); // "counts" is the published collection name }, removed: function (doc, idx) { count--; self.changed("counts", roomId, {count: count}); // same published collection, "counts" } // don''t care about moved or changed }); initializing = false; // publish the initial count. `observeChanges` guaranteed not to return // until the initial set of `added` callbacks have run, so the `count` // variable is up to date. self.added("counts", roomId, {count: count}); // and signal that the initial document set is now available on the client self.ready(); // turn off observe when client unsubscribes self.onStop(function () { handle.stop(); });});
现在,在客户端上,我们可以将其视为典型的Meteor订阅。首先,我们需要一个Mongo.Collection
可以保存我们计算的计数文档的文件。由于服务器正在发布到名为的集合中"counts"
,我们将其"counts"
作为参数传递给Mongo.Collection
构造函数。
// client: declare collection to hold count objectCounts = new Mongo.Collection("counts");
然后我们可以订阅。(实际上,您可以在声明集合之前进行订阅:Meteor会将传入的更新排队,直到有放置它们的位置为止。) 订阅 的名称为"counts-by-room"
,它带有一个参数:当前房间的ID。我将其包装在内部,Deps.autorun
以便进行Session.get(''roomId'')
更改时,客户端将自动取消订阅旧房间的计数,然后重新订阅新房间的计数。
// client: autosubscribe to the count for the current roomTracker.autorun(function () { Meteor.subscribe("counts-by-room", Session.get("roomId"));});
最后,我们已经获得了文档,Counts
并且可以像客户端上的任何其他Mongo集合一样使用它。每当服务器发送新计数时,任何引用此数据的模板都将自动重绘。
// client: use the new collectionconsole.log("Current room has " + Counts.findOne().count + " messages.");
com.intellij.util.messages.impl.MessageBusImpl的实例源码
public void testPostingperformanceWithLowListenerDensityInHierarchy() { //simulating million fileWithNodocumentChanged events on refresh in a thousand-module project MessageBusImpl childBus = new MessageBusImpl(this,myBus); childBus.connect().subscribe(TOPIC1,new T1Listener() { @Override public void t11() { } @Override public void t12() { } }); for (int i = 0; i < 1000; i++) { new MessageBusImpl(this,childBus); } PlatformTestUtil.assertTiming("Too long",3000,new Runnable() { @Override public void run() { T1Listener publisher = myBus.syncpublisher(TOPIC1); for (int i = 0; i < 1000000; i++) { publisher.t11(); } } }); }
public CoreProjectEnvironment(disposable parentdisposable,CoreApplicationEnvironment applicationEnvironment) { myParentdisposable = parentdisposable; myEnvironment = applicationEnvironment; myProject = new MockProject(myEnvironment.getApplication().getpicocontainer(),myParentdisposable); preregisterServices(); myFileIndexFacade = createFileIndexFacade(); myMessageBus = new MessageBusImpl("CoreProjectEnvironment",null); PsiModificationTrackerImpl modificationTracker = new PsiModificationTrackerImpl(myProject); myProject.registerService(PsiModificationTracker.class,modificationTracker); myProject.registerService(FileIndexFacade.class,myFileIndexFacade); myProject.registerService(ResolveCache.class,new ResolveCache(myMessageBus)); registerProjectExtensionPoint(PsiTreeChangePreprocessor.EP_NAME,PsiTreeChangePreprocessor.class); myPsiManager = new PsiManagerImpl(myProject,null,myFileIndexFacade,myMessageBus,modificationTracker); ((FileManagerImpl) myPsiManager.getFileManager()).markInitialized(); registerProjectComponent(PsiManager.class,myPsiManager); myProject.registerService(ResolveScopeManager.class,createResolveScopeManager(myPsiManager)); myProject.registerService(PsiFileFactory.class,new PsiFileFactoryImpl(myPsiManager)); myProject.registerService(CachedValuesManager.class,new CachedValuesManagerImpl(myProject,new PsiCachedValuesFactory(myPsiManager))); myProject.registerService(PsiDirectoryFactory.class,new PsiDirectoryFactoryImpl(myPsiManager)); myProject.registerService(ProjectScopeBuilder.class,createProjectScopeBuilder()); myProject.registerService(DumbService.class,new MockDumbService(myProject)); }
public CoreProjectEnvironment(disposable parentdisposable,myParentdisposable); preregisterServices(); myFileIndexFacade = createFileIndexFacade(); myMessageBus = (MessageBusImpl)myProject.getMessageBus(); PsiModificationTrackerImpl modificationTracker = new PsiModificationTrackerImpl(myProject); myProject.registerService(PsiModificationTracker.class,modificationTracker); ((FileManagerImpl)myPsiManager.getFileManager()).markInitialized(); registerProjectComponent(PsiManager.class,myPsiManager); registerProjectComponent(PsiDocumentManager.class,new CorePsiDocumentManager(myProject,myPsiManager,new MockDocumentCommitProcessor())); myProject.registerService(ResolveScopeManager.class,new PsiCachedValuesFactory(myPsiManager))); myProject.registerService(ProjectScopeBuilder.class,new MockDumbService(myProject)); }
@NotNull @Override public MessageBus getMessageBus() { return new MessageBusImpl.RootBus(""); }
@NotNull @Override public MessageBus newMessageBus(@NotNull Object owner) { return new MessageBusImpl.RootBus(owner); }
@NotNull @Override public MessageBus newMessageBus(@NotNull Object owner,@Nullable MessageBus parentBus) { return parentBus == null ? newMessageBus(owner) : new MessageBusImpl(owner,parentBus); }
public static MessageBus newMessageBus(@NotNull Object owner) { return new MessageBusImpl(owner,null); }
public static MessageBus newMessageBus(@NotNull Object owner,MessageBus parentBus) { return new MessageBusImpl(owner,parentBus); }
public CoreApplicationEnvironment(disposable parentdisposable) { myParentdisposable = parentdisposable; Extensions.cleanRootArea(myParentdisposable); myFileTypeRegistry = new CoreFileTypeRegistry(); myEncodingRegistry = new CoreEncodingRegistry(); myApplication = createApplication(myParentdisposable); ApplicationManager.setApplication(myApplication,new StaticGetter<FileTypeRegistry>(myFileTypeRegistry),new StaticGetter<EncodingRegistry>(myEncodingRegistry),myParentdisposable); myLocalFileSystem = createLocalFileSystem(); myJarFileSystem = createJarFileSystem(); Extensions.registerareaClass(ExtensionAreas.IDEA_PROJECT,null); final Mutablepicocontainer appContainer = myApplication.getpicocontainer(); registerComponentInstance(appContainer,FileDocumentManager.class,new MockFileDocumentManagerImpl(new Function<CharSequence,Document>() { @Override public Document fun(CharSequence charSequence) { return new DocumentImpl(charSequence); } },null)); VirtualFileSystem[] fs = {myLocalFileSystem,myJarFileSystem}; VirtualFileManagerImpl virtualFileManager = new VirtualFileManagerImpl(fs,new MessageBusImpl(myApplication,null)); registerComponentInstance(appContainer,VirtualFileManager.class,virtualFileManager); registerapplicationservice(VirtualFilePointerManager.class,createVirtualFilePointerManager()); myApplication.registerService(DefaultASTFactory.class,new CoreASTFactory()); myApplication.registerService(PsiBuilderFactory.class,new PsiBuilderFactoryImpl()); myApplication.registerService(ReferenceProvidersRegistry.class,new MockReferenceProvidersRegistry()); myApplication.registerService(StubTreeLoader.class,new CoreStubTreeLoader()); myApplication.registerService(PsiReferenceService.class,new PsiReferenceServiceImpl()); myApplication.registerService(MetaDataRegistrar.class,new MetaRegistry()); registerapplicationExtensionPoint(ContentBasedFileSubstitutor.EP_NAME,ContentBasedFileSubstitutor.class); registerExtensionPoint(Extensions.getRootArea(),BinaryFileStubBuilders.EP_NAME,FileTypeExtensionPoint.class); registerExtensionPoint(Extensions.getRootArea(),FileContextProvider.EP_NAME,FileContextProvider.class); registerapplicationExtensionPoint(MetaDataContributor.EP_NAME,MetaDataContributor.class); ProgressIndicatorProvider.ourInstance = createProgressIndicatorProvider(); myApplication.registerService(JobLauncher.class,createJobLauncher()); }
public static MessageBus newMessageBus(@Nonnull Object owner) { return new MessageBusImpl.RootBus(owner); }
public static MessageBus newMessageBus(@Nonnull Object owner,parentBus); }
com.intellij.util.messages.MessageBusConnection的实例源码
private void connectToMessageBus(Project project) { logger.info("Connecting to message bus."); MessageBusConnection bus = project.getMessageBus().connect(); bus.setDefaultHandler( (method,objects) -> { logger.info("Method call observed in message bus."); for (Object object : objects) { if (method.toString().toLowerCase().contains("contentselected")) { if (object.toString().toLowerCase().contains("debug")) { new ButtonInputListener().receiveDebugRunAction(); } else if (object.toString().contains("DefaultRunExecutor")) { new ButtonInputListener().receiveRunAction(); } } } }); logger.info("Subscribing to runcontentManager topic."); bus.subscribe(runcontentManager.TOPIC); }
public ExternalAnnotationsManagerImpl(@NotNull final Project project,final PsiManager psiManager) { super(psiManager); myBus = project.getMessageBus(); final MessageBusConnection connection = myBus.connect(project); connection.subscribe(ProjectTopics.PROJECT_ROOTS,new ModuleRootAdapter() { @Override public void rootsChanged(ModuleRootEvent event) { dropCache(); } }); final MyVirtualFileListener fileListener = new MyVirtualFileListener(); VirtualFileManager.getInstance().addVirtualFileListener(fileListener); disposer.register(myPsiManager.getProject(),new disposable() { @Override public void dispose() { VirtualFileManager.getInstance().removeVirtualFileListener(fileListener); } }); }
public void install() { final MessageBusConnection connection = myProject.getMessageBus().connect(myProject); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER,new FileEditorManagerAdapter() { @Override public void selectionChanged(@NotNull FileEditorManagerEvent event) { final FileEditor editor = event.getNewEditor(); if (editor != null && myComponent.isShowing() && isAutoScrollEnabled()) { myAlarm.cancelAllRequests(); myAlarm.addRequest(new Runnable() { @Override public void run() { selectElementFromEditor(editor); } },getAlarmDelay(),getModalityState()); } } }); }
@Override public void projectOpened() { final ModuleRootListener rootListener = new ModuleRootAdapter() { public void rootsChanged(ModuleRootEvent event) { if (!myProject.isdisposed()) { checkToolWindowStatuses(myProject); } } }; StartupManager.getInstance(myProject).runWhenProjectIsInitialized(new Runnable() { public void run() { if (!myProject.isdisposed()) { checkToolWindowStatuses(myProject); final MessageBusConnection connection = myProject.getMessageBus().connect(myProject); connection.subscribe(ProjectTopics.PROJECT_ROOTS,rootListener); } } }); }
public EditorNotificationsImpl(Project project) { super(project); myUpdateMerger = new MergingUpdateQueue("EditorNotifications update merger",100,true,null,project); MessageBusConnection connection = project.getMessageBus().connect(project); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER,new FileEditorManagerAdapter() { @Override public void fileOpened(@NotNull FileEditorManager source,@NotNull VirtualFile file) { updateNotifications(file); } }); connection.subscribe(DumbService.DUMB_MODE,new DumbService.DumbModeListener() { @Override public void enteredDumbMode() { updateallNotifications(); } @Override public void exitDumbMode() { updateallNotifications(); } }); }
private LibNotifyWrapper() { myLibNotify = (LibNotify)Native.loadLibrary("libnotify.so.4",LibNotify.class); String appName = ApplicationNamesInfo.getInstance().getProductName(); if (myLibNotify.notify_init(appName) == 0) { throw new IllegalStateException("notify_init Failed"); } String icon = AppUIUtil.findIcon(PathManager.getBinPath()); myIcon = icon != null ? icon : "dialog-information"; MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(); connection.subscribe(AppLifecycleListener.TOPIC,new AppLifecycleListener.Adapter() { @Override public void appClosing() { synchronized (myLock) { mydisposed = true; myLibNotify.notify_uninit(); } } }); }
public void scheduleInitialVfsRefresh() { UIUtil.invokelaterIfNeeded(new Runnable() { @Override public void run() { if (myProject.isdisposed()) return; markContentRootsForRefresh(); Application app = ApplicationManager.getApplication(); if (!app.isHeadlessEnvironment()) { final long sessionId = VirtualFileManager.getInstance().asyncRefresh(null); final MessageBusConnection connection = app.getMessageBus().connect(); connection.subscribe(ProjectLifecycleListener.TOPIC,new ProjectLifecycleListener.Adapter() { @Override public void afterProjectClosed(@NotNull Project project) { RefreshQueue.getInstance().cancelSession(sessionId); connection.disconnect(); } }); } else { VirtualFileManager.getInstance().syncRefresh(); } } }); }
@Override public void projectOpened() { MessageBusConnection connection = myProject.getMessageBus().connect(myProject); connection.subscribe(ProjectTopics.PROJECT_ROOTS,new ModuleRootAdapter() { @Override public void rootsChanged(ModuleRootEvent event) { ApplicationManager.getApplication().invokelater(new Runnable() { @Override public void run() { if (myProject.isdisposed()) return; VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty(); } },ModalityState.NON_MODAL); } }); final WolfTheProblemSolver.ProblemListener myProblemListener = new MyProblemListener(); WolfTheProblemSolver.getInstance(myProject).addProblemListener(myProblemListener,myProject); }
static void unsubscribeFrom(NavBarPanel panel) { final NavBarListener listener = (NavBarListener)panel.getClientProperty(LISTENER); panel.putClientProperty(LISTENER,null); if (listener != null) { final Project project = panel.getProject(); KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertychangelistener(listener); FileStatusManager.getInstance(project).removeFileStatusListener(listener); PsiManager.getInstance(project).removePsiTreechangelistener(listener); WolfTheProblemSolver.getInstance(project).removeProblemListener(listener); ActionManager.getInstance().removeAnActionListener(listener); final MessageBusConnection connection = (MessageBusConnection)panel.getClientProperty(BUS); panel.putClientProperty(BUS,null); if (connection != null) { connection.disconnect(); } LafManager.getInstance().removeLafManagerListener(listener); } }
@Override public void initFacet() { MessageBusConnection connection = getModule().getMessageBus().connect(this); connection.subscribe(PROJECT_ROOTS,new ModuleRootAdapter() { @Override public void rootsChanged(ModuleRootEvent event) { ApplicationManager.getApplication().invokelater(new Runnable() { @Override public void run() { if (!isdisposed()) { PsiDocumentManager.getInstance(getModule().getProject()).commitAllDocuments(); updateConfiguration(); } } }); } }); updateConfiguration(); }
@Override public void initFacet() { MessageBusConnection connection = getModule().getMessageBus().connect(this); connection.subscribe(ProjectTopics.PROJECT_ROOTS,new ModuleRootAdapter() { @Override public void rootsChanged(ModuleRootEvent event) { ApplicationManager.getApplication().invokelater(new Runnable() { @Override public void run() { if (!isdisposed()) { PsiDocumentManager.getInstance(getModule().getProject()).commitAllDocuments(); updateConfiguration(); } } }); } }); updateConfiguration(); }
/** * There's a bug in the ModuleClassLoader's cache implementation,which results in crashes during preview rendering. The workaround is * to clear the cache on each build. This registers a build complete listener to trigger the cache refresh. */ private void registerSyncListenerIfNecessary() { if (myBuildCompleteListener != null) { return; } myBuildCompleteListener = new GradleBuildListener() { @Override public void buildFinished(@NotNull Project builtProject,@Nullable BuildMode mode) { if (mode == null || builtProject != myProject) { return; } switch (mode) { case CLEAN: case ASSEMBLE: case COMPILE_JAVA: case REBUILD: ModuleClassLoader.clearCache(); clearCache(); case SOURCE_GEN: case ASSEMBLE_TRANSLATE: } } }; MessageBusConnection connection = myProject.getMessageBus().connect(myProject); connection.subscribe(GRADLE_BUILD_TOPIC,myBuildCompleteListener); }
/** * Registers an callback that gets notified when the IDE is closing. */ private static void registerappClosing() { Application app = ApplicationManager.getApplication(); MessageBusConnection connection = app.getMessageBus().connect(app); connection.subscribe(AppLifecycleListener.TOPIC,new AppLifecycleListener.Adapter() { @Override public void appClosing() { try { stopAllGradleDaemons(false); } catch (IOException e) { LOG.info("Failed to stop Gradle daemons",e); } } }); }
public AndroidProjectTreeBuilder(@NotNull Project project,@NotNull JTree tree,@NotNull DefaultTreeModel treeModel,@Nullable Comparator<NodeDescriptor> comparator,@NotNull ProjectAbstractTreeStructureBase treeStructure) { super(project,tree,treeModel,comparator,treeStructure); MessageBusConnection connection = project.getMessageBus().connect(project); connection.subscribe(VirtualFileManager.VFS_CHANGES,new BulkFileListener.Adapter() { @Override public void after(@NotNull List<? extends VFileEvent> events) { for (VFileEvent e : events) { if (e instanceof VFileDeleteEvent) { removeMapping(e.getFile()); } } } }); }
public IdeaDecompiler() { Application app = ApplicationManager.getApplication(); myLegalNoticeAccepted = app.isUnitTestMode() || PropertiesComponent.getInstance().isValueSet(LEgal_NOTICE_KEY); if (!myLegalNoticeAccepted) { MessageBusConnection connection = app.getMessageBus().connect(app); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER,new FileEditorManagerAdapter() { @Override public void fileOpened(@NotNull FileEditorManager source,@NotNull VirtualFile file) { if (file.getFileType() == StdFileTypes.CLASS) { FileEditor editor = source.getSelectedEditor(file); if (editor instanceof TextEditor) { CharSequence text = ((TextEditor)editor).getEditor().getDocument().getImmutableCharSequence(); if (StringUtil.startsWith(text,BANNER)) { showLegalNotice(source.getProject(),file); } } } } }); } }
protected GradletoolWindowPanel(@NotNull Project project,@NotNull String place) { super(true); myProject = project; myPlace = place; setContent(myContent); MessageBusConnection connection = project.getMessageBus().connect(project); connection.subscribe(GradleSettingsListener.TOPIC,new GradleSettingsListenerAdapter() { // Todo den implement // @Override public void onLinkedProjectConfigChange(@Nullable String oldpath,@Nullable String newPath) { // if (StringUtil.isEmpty(newPath)) { // myLayout.show(myContent,NON_LINKED_CARD_NAME); // return; // } // if (StringUtil.isEmpty(oldpath) && !StringUtil.isEmpty(newPath)) { // myLayout.show(myContent,CONTENT_CARD_NAME); // } // } }); }
public void makeDumbAware(final Project project) { Accesstoken accesstoken = ReadAction.start(); try { MessageBusConnection connection = project.getMessageBus().connect(this); connection.subscribe(DumbService.DUMB_MODE,new DumbService.DumbModeListener() { @Override public void enteredDumbMode() { suspend(); } @Override public void exitDumbMode() { resume(); } }); if (DumbService.getInstance(project).isDumb()) { suspend(); } } finally { accesstoken.finish(); } }
protected boolean getWithActive(SvnAuthenticationManager active) throws SVNException { MessageBusConnection connection = null; try { final Project project = myVcs.getProject(); connection = project.getMessageBus().connect(project); connection.subscribe(SvnAuthenticationManager.AUTHENTICATION_PROVIDER_LISTENER,new MyAuthenticationProviderListener()); makeAuthCall(active); } finally { if (connection != null) { connection.disconnect(); } } return afterauthCall(); }
private void upgradeIfNeeded(final MessageBus bus) { final MessageBusConnection connection = bus.connect(); connection.subscribe(changelistManagerImpl.LISTS_LOADED,new LocalchangelistsLoadedListener() { @Override public void processLoadedLists(final List<Localchangelist> lists) { if (lists.isEmpty()) return; try { changelistManager.getInstance(myProject).setReadOnly(SvnChangeProvider.ourDefaultListName,true); if (!myConfiguration.changelistsSynchronized()) { processchangelists(lists); } } catch (ProcessCanceledException e) { // } finally { myConfiguration.upgrade(); } connection.disconnect(); } }); }
public void installListeners() { LOG.info("installListeners " + project.getName()); // Listen for .stg file saves VirtualFileManager.getInstance().addVirtualFileListener(myVirtualFileListener); // Listen for editor window changes MessageBusConnection msgBus = project.getMessageBus().connect(project); msgBus.subscribe( FileEditorManagerListener.FILE_EDITOR_MANAGER,myFileEditorManagerListener ); // Listen for editor creation and release so that we can install // keyboard listeners that notify us when to reanalyze the file. // listener should be removed by Intellij when project is disposed // per doc. EditorFactory factory = EditorFactory.getInstance(); factory.addEditorFactoryListener(new MyEditorFactoryListener(),project); }
private void doViewSwitch(@NotNull ExternalSystemTaskId id,@NotNull String projectPath) { Project ideProject = id.findProject(); if (ideProject == null) { return; } // disable zooming on subsequent project resolves/refreshes,// i.e. a project that already has existing modules,because it may zoom at a module // that is going to be replaced by the current resolve. if (ModuleManager.getInstance(ideProject).getModules().length > 0) { return; } MessageBusConnection messageBusConnection = ideProject.getMessageBus().connect(); messageBusConnection.subscribe( ProjectTopics.PROJECT_ROOTS,new ModuleRootListener() { @Override public void rootsChanged(ModuleRootEvent event) { // Initiate view switch only when project modules have been created. new ViewSwitchProcessor(ideProject,projectPath).asyncViewSwitch(); } } ); }
@Override public void projectOpened() { super.projectOpened(); if (myProject.isDefault() || !PantsUtil.isPantsProject(myProject)) { return; } final MessageBusConnection connection = myProject.getMessageBus().connect(this); connection.subscribe( ProjectTopics.PROJECT_ROOTS,new ModuleRootListener() { @Override public void rootsChanged(ModuleRootEvent event) { myProjectRoots = null; } } ); }
public ExternalAnnotationsManagerImpl(@NotNull final Project project,new disposable() { @Override public void dispose() { VirtualFileManager.getInstance().removeVirtualFileListener(fileListener); } }); }
public void install() { final MessageBusConnection connection = myProject.getMessageBus().connect(myProject); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER,getModalityState()); } } }); }
@Override public void projectOpened() { MessageBusConnection connection = myProject.getMessageBus().connect(myProject); connection.subscribe(ProjectTopics.PROJECT_ROOTS,new ModuleRootAdapter() { @Override public void rootsChanged(ModuleRootEvent event) { ApplicationManager.getApplication().invokelater(new Runnable() { @Override public void run() { if (myProject.isdisposed() || !DirectoryIndex.getInstance(myProject).isInitialized()) return; VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty(); } },myProject); }
TodoView(Project project,ProjectLevelVcsManager manager){ myProject=project; myVCSManager = manager; myCurrentPanelSettings=new TodoPanelSettings(); myAllPanelSettings=new TodoPanelSettings(); mychangelistTodosPanelSettings = new TodoPanelSettings(); myPanels = new ArrayList<TodoPanel>(); myNotAddedContent = new ArrayList<Content>(); myVCSManager.addVcslistener(myVcslistener); final MyPropertychangelistener myPropertychangelistener = new MyPropertychangelistener(); TodoConfiguration.getInstance().addPropertychangelistener(myPropertychangelistener,this); MessageBusConnection connection = myProject.getMessageBus().connect(this); connection.subscribe(FileTypeManager.TOPIC,new MyFileTypeListener()); }
static void unsubscribeFrom(NavBarPanel panel) { final NavBarListener listener = (NavBarListener)panel.getClientProperty(LISTENER); panel.putClientProperty(LISTENER,null); if (connection != null) { connection.disconnect(); } } }
@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) { 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); }
protected GradletoolWindowPanel(@NotNull Project project,CONTENT_CARD_NAME); // } // } }); }
public void makeDumbAware(final Project project) { Accesstoken accesstoken = ReadAction.start(); try { MessageBusConnection connection = project.getMessageBus().connect(this); connection.subscribe(DumbService.DUMB_MODE,new DumbService.DumbModeListener() { public void enteredDumbMode() { suspend(); } public void exitDumbMode() { resume(); } }); if (DumbService.getInstance(project).isDumb()) { suspend(); } } finally { accesstoken.finish(); } }
public void install() { final MessageBusConnection connection = myProject.getMessageBus().connect(myProject); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER,new FileEditorManagerAdapter() { @Override public void selectionChanged(@Nonnull FileEditorManagerEvent event) { final FileEditor editor = event.getNewEditor(); if (editor != null && myComponent.isShowing() && isAutoScrollEnabled()) { myAlarm.cancelAllRequests(); myAlarm.addRequest(new Runnable() { @Override public void run() { selectElementFromEditor(editor); } },getModalityState()); } } }); }
public void addRequest(@Nonnull final Runnable request,final int delay,boolean runWithActiveFrameOnly) { if (runWithActiveFrameOnly && !ApplicationManager.getApplication().isActive()) { final MessageBus bus = ApplicationManager.getApplication().getMessageBus(); final MessageBusConnection connection = bus.connect(this); connection.subscribe(ApplicationActivationListener.TOPIC,new ApplicationActivationListener() { @Override public void applicationActivated(IdeFrame ideFrame) { connection.disconnect(); addRequest(request,delay); } }); } else { addRequest(request,delay); } }
public VcslogContentProvider(@Nonnull Project project,@Nonnull VcsProjectLog projectLog) { myProject = project; myProjectLog = projectLog; MessageBusConnection connection = project.getMessageBus().connect(project); connection.subscribe(VcsProjectLog.VCS_PROJECT_LOG_CHANGED,new VcsProjectLog.ProjectLogListener() { @Override public void logCreated() { addLogUi(); } @Override public void logdisposed() { myContainer.removeAll(); closeLogTabs(); } }); if (myProjectLog.getLogManager() != null) { addLogUi(); } }
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()); }
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); 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); } }
public EditorFactoryImpl(EditorActionManager editorActionManager) { Application application = ApplicationManager.getApplication(); MessageBus bus = application.getMessageBus(); MessageBusConnection connect = bus.connect(); connect.subscribe(ProjectLifecycleListener.TOPIC,new ProjectLifecycleListener() { @Override public void beforeProjectLoaded(@Nonnull final Project project) { // validate all editors are disposed after fireProjectClosed() was called,because it's the place where editor should be released disposer.register(project,() -> { final Project[] openProjects = ProjectManager.getInstance().getopenProjects(); final boolean isLastProjectClosed = openProjects.length == 0; validateEditorsAreReleased(project,isLastProjectClosed); }); } }); ApplicationManager.getApplication().getMessageBus().connect().subscribe(EditorColorsManager.TOPIC,new EditorColorsListener() { @Override public void globalSchemeChange(EditorColoRSScheme scheme) { refreshAllEditors(); } }); TypedAction typedAction = editorActionManager.getTypedAction(); TypedActionHandler originalHandler = typedAction.getRawHandler(); typedAction.setupRawHandler(new MyTypedHandler(originalHandler)); }
public EditorNotificationsImpl(Project project) { myProject = project; myUpdateMerger = new MergingUpdateQueue("EditorNotifications update merger",new FileEditorManagerAdapter() { @Override public void fileOpened(@Nonnull FileEditorManager source,@Nonnull VirtualFile file) { updateNotifications(file); } }); connection.subscribe(DumbService.DUMB_MODE,new DumbService.DumbModeListener() { @Override public void enteredDumbMode() { updateallNotifications(); } @Override public void exitDumbMode() { updateallNotifications(); } }); }
private LibNotifyWrapper() { myLibNotify = (LibNotify)Native.loadLibrary("libnotify.so.4",LibNotify.class); String appName = ApplicationNamesInfo.getInstance().getProductName(); if (myLibNotify.notify_init(appName) == 0) { throw new IllegalStateException("notify_init Failed"); } String icon = AppUIUtil.findIcon(PathManager.getAppHomeDirectory().getPath()); myIcon = icon != null ? icon : "dialog-information"; MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(); connection.subscribe(AppLifecycleListener.TOPIC,new AppLifecycleListener() { @Override public void appClosing() { synchronized (myLock) { mydisposed = true; myLibNotify.notify_uninit(); } } }); }
public void scheduleInitialVfsRefresh() { GuiUtils.invokelaterIfNeeded(() -> { if (myProject.isdisposed() || myInitialRefreshScheduled) return; myInitialRefreshScheduled = true; ((ProjectRootManagerImpl)ProjectRootManager.getInstance(myProject)).markRootsForRefresh(); Application app = ApplicationManager.getApplication(); if (!app.isCommandLine()) { final long sessionId = VirtualFileManager.getInstance().asyncRefresh(null); final MessageBusConnection connection = app.getMessageBus().connect(); connection.subscribe(ProjectLifecycleListener.TOPIC,new ProjectLifecycleListener() { @Override public void afterProjectClosed(@Nonnull Project project) { if (project != myProject) return; RefreshQueue.getInstance().cancelSession(sessionId); connection.disconnect(); } }); } else { VirtualFileManager.getInstance().syncRefresh(); } },ModalityState.defaultModalityState()); }
@Override public void projectOpened() { MessageBusConnection connection = myProject.getMessageBus().connect(myProject); connection.subscribe(ProjectTopics.PROJECT_ROOTS,myProject); }
com.intellij.util.messages.MessageBus的实例源码
@Override public void createtoolWindowContent(@NotNull Project project,@NotNull ToolWindow toolWindow) { ContentFactory contentFactory = ContentFactory.SERVICE.getInstance(); Set<SelectedExchangeCurrencyPair> selectedExchangeCurrencyPairs = IdeaCurrencyConfig.getInstance().getSelectedExchangeCurrencyPairs(); if (IdeaCurrencyConfig.getInstance().getActive()) { List<TickerDto> data = IdeaCurrencyApp.getInstance().getTickers(selectedExchangeCurrencyPairs); fillData(data); } Content content = contentFactory.createContent(contentPane,"",false); toolWindow.getContentManager().addContent(content); MessageBus messageBus = project.getMessageBus(); messageBusConnection = messageBus.connect(); messageBusConnection.subscribe(ConfigChangeNotifier.CONfig_TOPIC,active -> { if (active) { scheduleNextTask(); } }); }
@Override public void initComponent() { MessageBus bus = ApplicationManager.getApplication().getMessageBus(); connection = bus.connect(); ProjectManager.getInstance().addProjectManagerListener(new ProjectManagerListener() { @Override public void projectOpened(Project project) { Config config = Config.getInstance(project); if(config == null) { return; } if(!config.isConfigFilled()) { Notifications.Bus.notify( new Notification("Settings Error","Gherkin TS Runner","Settings have to be filled.",NotificationType.WARNING) ); return; } connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER,new GherkinFileEditorManagerListener(project)); } }); }
@Override public void actionPerformed(AnActionEvent e) { if (e.getProject() != null) { ScanManager scanManager = ScanManagerFactory.getScanManager(e.getProject()); if (scanManager == null) { // Check if the project is supported Now ScanManagerFactory scanManagerFactory = ServiceManager.getService(e.getProject(),ScanManagerFactory.class); scanManagerFactory.initScanManager(e.getProject()); scanManager = ScanManagerFactory.getScanManager(e.getProject()); if (scanManager == null) { return; } MessageBus messageBus = ApplicationManager.getApplication().getMessageBus(); messageBus.syncpublisher(Events.ON_IDEA_FRAMEWORK_CHANGE).update(); } scanManager.asyncScanAndUpdateResults(false); } }
/** * This function is called after change in the build.gradle file or refresh gradle dependencies call. * @param toImport the project dependencies * @param projectData the project data * @param project the current project * @param modelsProvider contains the project modules */ @Override public void importData(@NotNull Collection<Datanode<LibraryDependencyData>> toImport,@Nullable ProjectData projectData,@NotNull Project project,@NotNull IdeModifiableModelsProvider modelsProvider) { if (projectData == null || !projectData.getowner().equals(GradleConstants.SYstem_ID)) { return; } ScanManager scanManager = ScanManagerFactory.getScanManager(project); if (scanManager == null) { ScanManagerFactory scanManagerFactory = ServiceManager.getService(project,ScanManagerFactory.class); scanManagerFactory.initScanManager(project); scanManager = ScanManagerFactory.getScanManager(project); if (scanManager == null) { return; } MessageBus messageBus = ApplicationManager.getApplication().getMessageBus(); messageBus.syncpublisher(Events.ON_IDEA_FRAMEWORK_CHANGE).update(); } if (GlobalSettings.getInstance().isCredentialsSet()) { scanManager.asyncScanAndUpdateResults(true,toImport); } }
public static void _do(@NotNull final ConfigurationError error,@NotNull final Project project,@NotNull final PairProcessor<ConfigurationErrors,ConfigurationError> fun) { if (!project.isInitialized()) { StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { @Override public void run() { fun.process(project.getMessageBus().syncpublisher(TOPIC),error); } }); return; } final MessageBus bus = project.getMessageBus(); if (EventQueue.isdispatchThread()) fun.process(bus.syncpublisher(TOPIC),error); else { //noinspection SSBasedinspection SwingUtilities.invokelater(new Runnable() { @Override public void run() { fun.process(bus.syncpublisher(TOPIC),error); } }); } }
public static void set(@Nullable final String text,@Nullable final Project project,@Nullable final String requestor) { if (project != null) { if (project.isdisposed()) return; if (!project.isInitialized()) { StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { public void run() { project.getMessageBus().syncpublisher(TOPIC).setInfo(text,requestor); } }); return; } } final MessageBus bus = project == null ? ApplicationManager.getApplication().getMessageBus() : project.getMessageBus(); bus.syncpublisher(TOPIC).setInfo(text,requestor); }
public PsiModificationTrackerImpl(Project project) { final MessageBus bus = project.getMessageBus(); myPublisher = bus.syncpublisher(TOPIC); bus.connect().subscribe(DumbService.DUMB_MODE,new DumbService.DumbModeListener() { private void doIncCounter() { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { incCounter(); } }); } @Override public void enteredDumbMode() { doIncCounter(); } @Override public void exitDumbMode() { doIncCounter(); } }); }
public IncomingChangesViewProvider(final Project project,final MessageBus bus) { myProject = project; myBus = bus; myListConsumer = new Consumer<List<Committedchangelist>>() { @Override public void consume(final List<Committedchangelist> lists) { UIUtil.invokelaterIfNeeded(new Runnable() { @Override public void run() { mybrowser.getEmptyText().setText(VcsBundle.message("incoming.changes.empty.message")); mybrowser.setItems(lists,CommittedChangesbrowserUseCase.INCOMING); } }); } }; }
public OutdatedVersionNotifier(FileEditorManager fileEditorManager,CommittedChangesCache cache,MessageBus messageBus,Project project) { myFileEditorManager = fileEditorManager; myCache = cache; myProject = project; messageBus.connect().subscribe(CommittedChangesCache.COMMITTED_TOPIC,new CommittedChangesAdapter() { public void incomingChangesUpdated(@Nullable final List<Committedchangelist> receivedChanges) { if (myCache.getCachedIncomingChanges() == null) { requestLoadIncomingChanges(); } else { updateallEditorsLater(); } } @Override public void changesCleared() { updateallEditorsLater(); } }); }
public PsiAwareFileEditorManagerImpl(final Project project,final PsiManager psiManager,final WolfTheProblemSolver problemSolver,DockManager dockManager,EditorHistoryManager editorHistoryManager) { super(project,dockManager,editorHistoryManager); myPsiManager = psiManager; myProblemSolver = problemSolver; myPsiTreechangelistener = new MyPsiTreechangelistener(); myProblemListener = new MyProblemListener(); registerExtraEditorDataProvider(new TextEditorPsiDataProvider(),null); // reinit Syntax Highlighter for Groovy. In power save mode keywords are highlighted by GroovySyntaxHighlighter insteadof // GrKeywordAndDeclarationHighlighter. So we need to drop caches for token types attributes in layeredLexerEditorHighlighter messageBus.connect().subscribe(PowerSaveMode.TOPIC,new PowerSaveMode.Listener() { @Override public void powerSaveStateChanged() { for (Editor editor : EditorFactory.getInstance().getAllEditors()) { ((EditorEx)editor).reinitSettings(); } } }); }
protected ScratchFileServiceImpl(MessageBus messageBus) { myIndex = new LightDirectoryIndex<Roottype>(messageBus.connect(),NULL_TYPE) { @Override protected void collectRoots(@NotNull PairConsumer<VirtualFile,Roottype> consumer) { LocalFileSystem fileSystem = LocalFileSystem.getInstance(); for (Roottype r : Roottype.getAllRootIds()) { String root = getRootPath(r); VirtualFile rootFile = fileSystem.findFileByPath(root); if (rootFile != null) { consumer.consume(rootFile,r); } } } }; initFileOpenedListener(messageBus); }
public PyModuleListener(MessageBus messageBus) { messageBus.connect().subscribe(ProjectTopics.MODULES,new ModuleAdapter() { @Override public void beforeModuleRemoved(@NotNull Project project,@NotNull Module module) { final RunManagerEx runManager = RunManagerEx.getInstanceEx(project); final Collection<RunnerAndConfigurationSettings> configurations = new ArrayList<RunnerAndConfigurationSettings>(runManager.getSortedConfigurations()); for (RunnerAndConfigurationSettings configuration : configurations) { if (configuration.getConfiguration() instanceof AbstractPythonrunconfiguration) { final Module configModule = ((AbstractPythonrunconfiguration)configuration.getConfiguration()).getModule(); if (configModule == module) { runManager.removeConfiguration(configuration); } } } } }); }
@Override protected void executeChunked(@NotNull List<List<String>> chunkedCommits) throws HgCommandException,VcsException { if (chunkedCommits.isEmpty()) { executeQNew(ContainerUtil.<String>emptyList()); } else { int size = chunkedCommits.size(); int i = 0; if (!myAmend) { executeQNew(chunkedCommits.get(0)); i = 1; } for (; i < size; i++) { executeQRefresh(chunkedCommits.get(i)); } } myRepository.update(); final MessageBus messageBus = myProject.getMessageBus(); messageBus.syncpublisher(HgVcs.REMOTE_TOPIC).update(myProject,null); }
public void execute() throws HgCommandException,VcsException { if (StringUtil.isEmptyOrSpaces(myMessage)) { throw new HgCommandException(HgVcsMessages.message("hg4idea.commit.error.messageEmpty")); } if (myFiles.isEmpty()) { executeChunked(Collections.<List<String>>emptyList()); } else { List<String> relativePaths = ContainerUtil.map2List(myFiles,new Function<HgFile,String>() { @Override public String fun(HgFile file) { return file.getRelativePath(); } }); List<List<String>> chunkedCommits = VcsFileUtil.chunkRelativePaths(relativePaths); executeChunked(chunkedCommits); } myRepository.update(); final MessageBus messageBus = myProject.getMessageBus(); messageBus.syncpublisher(HgVcs.REMOTE_TOPIC).update(myProject,null); }
private void upgradeIfNeeded(final MessageBus bus) { final MessageBusConnection connection = bus.connect(); connection.subscribe(changelistManagerImpl.LISTS_LOADED,new LocalchangelistsLoadedListener() { @Override public void processLoadedLists(final List<Localchangelist> lists) { if (lists.isEmpty()) return; try { changelistManager.getInstance(myProject).setReadOnly(SvnChangeProvider.ourDefaultListName,true); if (!myConfiguration.changelistsSynchronized()) { processchangelists(lists); } } catch (ProcessCanceledException e) { // } finally { myConfiguration.upgrade(); } connection.disconnect(); } }); }
/** Constructor. */ public IntelliJListener(TrackingEventManager trackingEventManager,Project project) { this.trackingEventManager = trackingEventManager; this.project = project; parent = new disposable() { @Override public void dispose() { // intentionally left empty } }; editorWindowListener = new EditorWindowListener(project.getName()); final MessageBus messageBus = ApplicationManager.getApplication().getMessageBus(); connection = messageBus.connect(); }
@Override public void beforeEach(ExtensionContext context) { IdeaMocksImpl ideaMocks = new IdeaMocksImpl(); Project project = mock(Project.class); MessageBus messageBus = mock(MessageBus.class); when(project.getMessageBus()).thenReturn(messageBus); when(messageBus.syncpublisher(any(Topic.class))).thenAnswer(invocation -> { Topic topic = invocation.getArgument(0); Class<?> listenerClass = topic.getListenerClass(); if (ideaMocks.hasMockListener(listenerClass)) { return ideaMocks.getMockListener(listenerClass); } else { return ideaMocks.mockListener(listenerClass); } }); Store store = context.getStore(NS); store.put(Project.class,project); store.put(MessageBus.class,messageBus); store.put(IdeaMocks.class,ideaMocks); }
public JavaFileManagerImpl(final PsiManagerEx manager,final ProjectRootManager projectRootManager,MessageBus bus,final StartupManager startupManager) { super(manager,projectRootManager,bus); myConnection.subscribe(AppTopics.FILE_DOCUMENT_SYNC,new FileDocumentManagerAdapter() { @Override public void fileWithNodocumentChanged(@NotNull final VirtualFile file) { clearNonRepositoryMaps(); } }); startupManager.registerStartupActivity( new Runnable() { @Override public void run() { initialize(); } } ); }
public static void _do(@NotNull final ConfigurationError error,error); } }); } }
public static void set(@Nullable final String text,requestor); }
public PsiModificationTrackerImpl(Project project) { final MessageBus bus = project.getMessageBus(); myPublisher = bus.syncpublisher(TOPIC); bus.connect().subscribe(DumbService.DUMB_MODE,new DumbService.DumbModeListener() { @Override public void enteredDumbMode() { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { incCounter(); } }); } @Override public void exitDumbMode() { enteredDumbMode(); } }); }
public IncomingChangesViewProvider(final Project project,CommittedChangesbrowserUseCase.INCOMING); } }); } }; }
public OutdatedVersionNotifier(FileEditorManager fileEditorManager,new CommittedChangesAdapter() { public void incomingChangesUpdated(@Nullable final List<Committedchangelist> receivedChanges) { if (myCache.getCachedIncomingChanges() == null) { requestLoadIncomingChanges(); } else { updateallEditorsLater(); } } @Override public void changesCleared() { updateallEditorsLater(); } }); }
public ClasspathStorage(Module module) { myConverter = getProvider(ClasspathStorageUtil.getStorageType(module)).createConverter(module); final MessageBus messageBus = module.getMessageBus(); final VirtualFileTracker virtualFileTracker = (VirtualFileTracker)module.getpicocontainer().getComponentInstanceOfType(VirtualFileTracker.class); if (virtualFileTracker != null && messageBus != null) { final ArrayList<VirtualFile> files = new ArrayList<VirtualFile>(); try { myConverter.getFileSet().listFiles(files); for (VirtualFile file : files) { final Listener listener = messageBus.syncpublisher(STORAGE_TOPIC); virtualFileTracker.addTracker(file.getUrl(),new VirtualFileAdapter() { @Override public void contentsChanged(final VirtualFileEvent event) { listener.storageFileChanged(event,ClasspathStorage.this); } },true,module); } } catch (UnsupportedOperationException e) { //UnsupportedStorageProvider doesn't mean any files } } }
private GitRootScanner(@NotNull Project project) { myRootProblemNotifier = GitRootProblemNotifier.getInstance(project); StartupManager.getInstance(project).runWhenProjectIsInitialized(new DumbAwareRunnable() { @Override public void run() { myProjectIsInitialized = true; scanIfReady(); } }); final MessageBus messageBus = project.getMessageBus(); messageBus.connect().subscribe(ProjectLevelVcsManager.VCS_CONfigURATION_CHANGED,this); messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES,this); messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS,this); myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD,project); }
private void setupEventListeners() { ApplicationManager.getApplication().invokelater(new Runnable(){ public void run() { // save file MessageBus bus = ApplicationManager.getApplication().getMessageBus(); connection = bus.connect(); connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC,new CustomSaveListener()); // edit document EditorFactory.getInstance().getEventMulticaster().addDocumentListener(new CustomDocumentListener()); // mouse press EditorFactory.getInstance().getEventMulticaster().addEditorMouseListener(new CustomEditorMouseListener()); // scroll document EditorFactory.getInstance().getEventMulticaster().addVisibleAreaListener(new CustomVisibleAreaListener()); } }); }
public static void set(@Nullable final String text,requestor); }
public void addRequest(@Nonnull final Runnable request,final int delay,boolean runWithActiveFrameOnly) { if (runWithActiveFrameOnly && !ApplicationManager.getApplication().isActive()) { final MessageBus bus = ApplicationManager.getApplication().getMessageBus(); final MessageBusConnection connection = bus.connect(this); connection.subscribe(ApplicationActivationListener.TOPIC,new ApplicationActivationListener() { @Override public void applicationActivated(IdeFrame ideFrame) { connection.disconnect(); addRequest(request,delay); } }); } else { addRequest(request,delay); } }
public EditorFactoryImpl(EditorActionManager editorActionManager) { Application application = ApplicationManager.getApplication(); MessageBus bus = application.getMessageBus(); MessageBusConnection connect = bus.connect(); connect.subscribe(ProjectLifecycleListener.TOPIC,new ProjectLifecycleListener() { @Override public void beforeProjectLoaded(@Nonnull final Project project) { // validate all editors are disposed after fireProjectClosed() was called,because it's the place where editor should be released disposer.register(project,() -> { final Project[] openProjects = ProjectManager.getInstance().getopenProjects(); final boolean isLastProjectClosed = openProjects.length == 0; validateEditorsAreReleased(project,isLastProjectClosed); }); } }); ApplicationManager.getApplication().getMessageBus().connect().subscribe(EditorColorsManager.TOPIC,new EditorColorsListener() { @Override public void globalSchemeChange(EditorColoRSScheme scheme) { refreshAllEditors(); } }); TypedAction typedAction = editorActionManager.getTypedAction(); TypedActionHandler originalHandler = typedAction.getRawHandler(); typedAction.setupRawHandler(new MyTypedHandler(originalHandler)); }
public void reinitComponents(@Nonnull Set<String> componentNames,@Nonnull Collection<String> notReloadableComponents,@Nonnull Collection<? extends StateStorage> changedStorages) { MessageBus messageBus = getMessageBus(); messageBus.syncpublisher(BatchUpdateListener.TOPIC).onBatchUpdateStarted(); try { for (String componentName : componentNames) { if (!notReloadableComponents.contains(componentName)) { reinitComponent(componentName,changedStorages); } } } finally { messageBus.syncpublisher(BatchUpdateListener.TOPIC).onBatchUpdateFinished(); } }
public PsiManagerImpl(Project project,FileDocumentManager fileDocumentManager,PsiBuilderFactory psiBuilderFactory,FileIndexFacade fileIndex,PsiModificationTracker modificationTracker) { myProject = project; myFileIndex = fileIndex; myMessageBus = messageBus; myModificationTracker = modificationTracker; //We need to initialize PsiBuilderFactory service so it won't initialize under PsiLock from ChameleonTransform @SuppressWarnings({"UnusedDeclaration","UnnecessaryLocalVariable"}) Object used = psiBuilderFactory; myFileManager = new FileManagerImpl(this,fileDocumentManager,fileIndex); myTreeChangePreprocessors.add((PsiTreeChangePreprocessor)modificationTracker); disposer.register(project,() -> myIsdisposed = true); }
public PsiModificationTrackerImpl(Project project) { MessageBus bus = project.getMessageBus(); myPublisher = bus.syncpublisher(TOPIC); bus.connect().subscribe(DumbService.DUMB_MODE,new DumbService.DumbModeListener() { private void doIncCounter() { ApplicationManager.getApplication().runWriteAction(() -> incCounter()); } @Override public void enteredDumbMode() { doIncCounter(); } @Override public void exitDumbMode() { doIncCounter(); } }); }
public IncomingChangesViewProvider(final Project project,CommittedChangesbrowserUseCase.INCOMING); } }); } }; }
public OutdatedVersionNotifier(FileEditorManager fileEditorManager,new CommittedChangesAdapter() { public void incomingChangesUpdated(@Nullable final List<Committedchangelist> receivedChanges) { if (myCache.getCachedIncomingChanges() == null) { requestLoadIncomingChanges(); } else { updateallEditorsLater(); } } @Override public void changesCleared() { updateallEditorsLater(); } }); }
public static void _do(@Nonnull final ConfigurationError error,@Nonnull final Project project,@Nonnull final PairProcessor<ConfigurationErrors,error); } }); } }
public PsiDocumentManagerImpl(@Nonnull final Project project,@Nonnull PsiManager psiManager,@Nonnull EditorFactory editorFactory,@Nonnull MessageBus bus,@NonNls @Nonnull final DocumentCommitProcessor documentCommitThread) { super(project,psiManager,bus,documentCommitThread); myDocumentCommitThread = documentCommitThread; editorFactory.getEventMulticaster().addDocumentListener(this,project); MessageBusConnection connection = bus.connect(); connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC,new FileDocumentManagerAdapter() { @Override public void fileContentLoaded(@Nonnull final VirtualFile virtualFile,@Nonnull Document document) { PsiFile psiFile = ReadAction.compute(() -> myProject.isdisposed() || !virtualFile.isValid() ? null : getCachedPsiFile(virtualFile)); fireDocumentCreated(document,psiFile); } }); connection.subscribe(DocumentbulkupdateListener.TOPIC,new DocumentbulkupdateListener.Adapter() { @Override public void updateFinished(@Nonnull Document doc) { documentCommitThread.commitAsynchronously(project,doc,"Bulk update finished",TransactionGuard.getInstance().getContextTransaction()); } }); disposer.register(project,() -> ((DocumentCommitThread)myDocumentCommitThread).cancelTasksOnProjectdispose(project)); }
public FindManagerImpl(Project project,FindSettings findSettings,UsageViewManager anotherManager,MessageBus bus) { myProject = project; myBus = bus; findSettings.initModelBySetings(myFindInProjectModel); myFindInFileModel.setCaseSensitive(findSettings.isLocalCaseSensitive()); myFindInFileModel.setWholeWordsOnly(findSettings.isLocalWholeWordsOnly()); myFindInFileModel.setRegularExpressions(findSettings.isLocalRegularExpressions()); myFindUsagesManager = new FindUsagesManager(myProject,anotherManager); myFindInProjectModel.setMultipleFiles(true); NotificationsConfigurationImpl.remove("FindInPath"); disposer.register(project,new disposable() { @Override public void dispose() { if (myHelper != null) { disposer.dispose(myHelper); } } }); }
private void triggerConfigChange() { DataContext dataContext = DataManager.getInstance().getDataContextFromFocus().getResult(); Project project = DataKeys.PROJECT.getData(dataContext); if (project != null) { MessageBus messageBus = project.getMessageBus(); messageBus.connect(); ConfigChangeNotifier configChangeNotifier = messageBus.syncpublisher(ConfigChangeNotifier.CONfig_TOPIC); configChangeNotifier.configChanged(activeCheckBox.isSelected()); } }
@Override public void initComponent() { logger.debug("Initializing component"); MessageBus bus = ApplicationManager.getApplication().getMessageBus(); connection = bus.connect(); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER,new TabHighlighterFileEditorListener()); }
private ExternalProjectRefreshCallback getRefreshDependenciesCbk(boolean quickScan,ProgressIndicator indicator) { return new ExternalProjectRefreshCallback() { @Override public void onSuccess(@Nullable Datanode<ProjectData> externalProject) { try { Components components = collectComponentsToScan(externalProject); scanAndCacheArtifacts(components,quickScan,indicator); scanResults = updateResultsTree(scanResults); setUiLicenses(); MessageBus messageBus = project.getMessageBus(); messageBus.syncpublisher(Events.ON_SCAN_COMPONENTS_CHANGE).update(); } catch (Exception e) { Utils.notify(logger,"JFrog Xray scan Failed",e,NotificationType.ERROR); } } @Override public void onFailure(@NotNull String errorMessage,@Nullable String errorDetails) { String details; String title = "JFrog Xray scan Failed"; if (errorDetails != null) { details = errorDetails; title += ": " + errorMessage; } else { details = errorMessage; } Utils.notify(logger,title,details,NotificationType.ERROR); } }; }
com.intellij.util.messages.MessageHandler的实例源码
@Override public void setDefaultHandler(MessageHandler handler) { myDefaultHandler = handler; }
@Override public void setDefaultHandler(MessageHandler handler) { myDefaultHandler = handler; }
@Override public void setDefaultHandler(MessageHandler handler) { myDefaultHandler = handler; }
关于Meteor文档中的messages-count示例如何工作?和message word的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于com.intellij.util.messages.impl.MessageBusImpl的实例源码、com.intellij.util.messages.MessageBusConnection的实例源码、com.intellij.util.messages.MessageBus的实例源码、com.intellij.util.messages.MessageHandler的实例源码等相关内容,可以在本站寻找。
本文标签: