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.