When we use Eclipse, we are used to the notion of editors operating on a workspace file. But workspace and resources are optional for an RCP application. You might have to invoke an editor on a non-file object like a database record or an in-memory object. So one of the frequently asked questions is how to open an editor with a file? This tip explains how to do that.
For this I'll be using a simple sting as the model to be edited and use the default text editor to edit it. You can switch the model or editor with whatever you prefer (say a result of a database query edited in a form based editor).
Editors in Eclipse know nothing about the files/actual objects they edit. They always operate on IEditorInput. There are standard implementations like FileEditorInput (for workspace files), FileStoreEditorInput (for files on disk). In our case we have to create our own implementation. I have extended the IStorageEditorInput to make things easier:
public class StringEditorInput implements IStorageEditorInput {
private final String inputString;
public StringEditorInput(String inputString) {
this.inputString = inputString;
}
public boolean exists() {
return false;
}
public ImageDescriptor getImageDescriptor() {
return null;
}
public IPersistableElement getPersistable() {
return null;
}
public Object getAdapter(Class adapter) {
return null;
}
public String getName() {
return "input name";
}
public String getToolTipText() {
return "tool tip";
}
public IStorage getStorage() throws CoreException {
return new IStorage() {
public InputStream getContents() throws CoreException {
return new StringBufferInputStream(inputString);
}
public IPath getFullPath() {
return null;
}
public String getName() {
return StringEditorInput.this.getName();
}
public boolean isReadOnly() {
return false;
}
public Object getAdapter(Class adapter) {
return null;
}
};
}
}
In a command, I've opened the text editor with this call:
workbenchPage.openEditor(new StringEditorInput("text to be edited"), "org.eclipse.ui.DefaultTextEditor");
The output:
Hope the above picture shows where the various strings I've used in the class goes into. I'm returning null for the getPersistable() method. So you cannot Save the contents of this editor. If you want to do that, you have to return an instance of IPersistableElement. Write back to the database or send a Http Post message - the implementation is left to your application.


0 comments:
Post a Comment