Saturday, February 14, 2009

Eclipse : Keeping Preferences and Preferences UI separate

Eclipse Preferences and PreferenceStore does not connect well with each other. When we have a Core plugin which handles the preferences and the initial values, keeping the UI in a separate plugin becomes difficult. The core plugin does not have access to the PreferenceStore since it is a not UI plugin. The UI Plugin with PreferencePage cannot populate using the Preferences from the core plugin.

So how do we couple these together. The UI Plugin can create a PreferenceStore using the bundle id of the Core Plugin.



public class CorePreferencePage extends FieldEditorPreferencePage implements
IWorkbenchPreferencePage {

public CorePreferencePage() {
IPreferenceStore store = new ScopedPreferenceStore(new InstanceScope(),
""com.blog.sample.core"");
setPreferenceStore(store);
}

@Override
protected void createFieldEditors() {
BooleanFieldEditor formatOnSave = new BooleanFieldEditor("ABC", "ABC",
getFieldEditorParent());
addField(formatOnSave);

}

public void init(IWorkbench workbench) {

}

}



Now we can see the preferences of the Core Plugin in the UI Plugin's preference Page. But what if the preferences are not overridden and they are initialized from the Core Plugin using the Preference Initializer.


public class CorePreferenceInitializer extends AbstractPreferenceInitializer {

public CorePreferenceInitializer() {

}

@Override
public void initializeDefaultPreferences() {
Preferences node = new DefaultScope().getNode("com.blog.sample.core");
node.put("ABC", "true");
}
}


and the core plugin declares an extension point to initialize the value when the preference node is accessed. But the initializer will be only invoked only if it is invoked from the bundle which is initialized.








Now the initializer is invoked when it is accessed from the Core Plugin getPreferences. Now the UI Plugin does not know about the default values from the initializer. Whats the workaround?

Add a duplicate extension point on the UI Plugin with the same initializer from the Core Plugin. Now when you open the prefernece page the initializer on the Core Plugin is invoked and the values are set to default.

Have fun !

1 comment:

ranj said...

Hi, I have a problem. I want to listen to this PreferenceStore from another plugin, without depending on the UI plugin. How can I do that??

Thanks

-Ranjani