IntelliJ Platfrom Plugin

IntelliJ Platform Plugin SDK 공식문서 읽기 - Listeners

PI.314 2022. 10. 20. 00:47

Listeners

 

Listeners는 플러그인이 메시지 버스를 통해 전달된 이벤트에 선언적으로 가입할 수 있도록 허용합니다(자세한 내용은 Messaging infrastructure). Listeners 구현은 stateless이어야 하며 lifecycle(예: Disposable)를 구현할 수 없다.

Listeners는 application 과 project-level로 정의할 수 있습니다.

 

사용 가능한 모든 listeners/topics 는 수신기 섹션의 Extension Point and Listener List에 나열됩니다. IntelliJ Platform Explorer를 통해 오픈 소스 IntelliJ Platform 플러그인의 기존 구현 내에서 사용법을 탐색합니다.

 

Defining Application-Level Listeners

To define an application-level listener, add the <applicationListeners> section to your plugin.xml:

<idea-plugin>
  <applicationListeners>
    <listener
        class="myPlugin.MyListenerClass"
        topic="BaseListenerInterface"/>
  </applicationListeners>
</idea-plugin>
topic 속성은 수신할 이벤트 유형에 해당하는 listener interface를 지정합니다. 일반적으로 이 인터페이스는 이벤트 유형에 대한 주제 인스턴스의 유형 매개 변수로 사용되는 인터페이스입니다. 클래스 속성은 listener interface를 구현하고 이벤트를 수신하는 플러그인의 클래스를 지정합니다.
 
예를 들어 모든 가상 파일 시스템 변경 사항에 대한 이벤트를 수신하려면 VirtualFileManager.VFS_CHANGES 토픽에 해당하는 Bulk FileListener 인터페이스를 구현해야 합니다. 코드에서 이 항목을 구독하려면 다음과 같은 스니펫을 사용할 수 있습니다.
messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES,
    new BulkFileListener() {
        @Override
        public void after(@NotNull List<? extends VFileEvent> events) {
          // handle the events
        }
});
선언적 등록을 사용하려면 더 이상 topic instance를 참조할 필요가 없습니다. 대신 listener interface class를 직접 참조하십시오.
<applicationListeners>
  <listener
      class="myPlugin.MyVfsListener"
      topic="com.intellij.openapi.vfs.newvfs.BulkFileListener"/>
</applicationListeners>
그런 다음 listener implementation을 최상위 클래스로 제공합니다.
 
package myPlugin;

public class MyVfsListener implements BulkFileListener {
  @Override
  public void after(@NotNull List<? extends VFileEvent> events) {
    // handle the events
  }
}

Defining Project-Level Listeners

최상위 태그가 <projectListeners>인 것을 제외하고 project level listener는 동일한 방식으로 등록됩니다. 예를 들어 tool window 작업과 같은 project level listener를 사용할 수 있습니다. 
 
<idea-plugin>
  <projectListeners>
    <listener
        class="myPlugin.MyToolWindowListener"
        topic="com.intellij.openapi.wm.ex.ToolWindowManagerListener"/>
  </projectListeners>
</idea-plugin>

The class implementing the listener interface can define a one-argument constructor accepting a Project, and it will receive the instance of the project for which the listener is created:

package myPlugin;

public class MyToolWindowListener implements ToolWindowManagerListener {
  private final Project project;

  public MyToolwindowListener(Project project) {
    this.project = project;
  }

  @Override
  public void stateChanged(@NotNull ToolWindowManager toolWindowManager) {
    // handle the state change
  }
}