简体   繁体   中英

Eclipse Plugin Development - Detect/Listen File open in editor

I need to detect when a file (of any type) is opened in Eclipse and run some code when that happens.

I've tried with the following code but it seems to be calling the function multiple times:

Display.getDefault().asyncExec(new Runnable() {
    @Override
    public void run() {
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().addPartListener(new IPartListener2() {
            @Override
            public void partOpened(IWorkbenchPartReference partRef) {
                System.out.println("File opened");
            }
            
        });
    }
});

Is there a way to do this in Eclipse RCP?

IPartListener2.partOpened is the correct thing to use. Make sure you only set up the listener once.

partOpened will be called for all parts, so you will need to check for the ones you are interested in.

@Override
public void partOpened(final IWorkbenchPartReference partRef)
{
  // Check for editor reference and get the editor part

  if (partRef instanceof IEditorReference && 
      partRef.getPart(false) instanceof IEditorPart editorPart) {
     // Example getting current IFile being edited:
     IFile file = editorPart.getEditorInput().getAdapter(IFile.class);
  }
}

Note: Example code uses Java 16 type pattern, for older releases it will need revising.

Also note Display.asyncExec is not usually needed to set this up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM