In Runtime preferences, we looked at the infrastructure for defining and storing preferences with different scopes. We also saw that the org.eclipse.core.runtime.preferences extension can be used to define additional scopes for preferences. The platform resources plug-in defines its own preference scope, called "Project," in order to define project-scoped preferences. Project-scoped preferences are stored in a file located inside the project. This makes it easy to store a set of preferences and exchange them with other users using resource-oriented mechanisms such as a version control system.
The definition for new scopes is pretty simple. The plug-in defines the name of the scope, as well as the class that implements it. The resources plug-in defines the project scope as follows:
<extension id="preferences" point="org.eclipse.core.runtime.preferences" name="preferences"> <scope name="project" class="org.eclipse.core.internal.resources.ProjectPreferences"/> </extension>
The specified class must implement the IScope interface, which means it must be capable of creating preference nodes for the scope.
Since the project scope for preferences is not one of the standard runtime scopes, the node representing a project-level preference must be obtained specifically. From the root preference node, you must navigate to the project-scoped preference. This can be achieved using the ProjectScope:
IScopeContext projectScope = new ProjectScope(MyProject);
Once the project scope for a particular is project is found, the preference values can be obtained using the same mechanisms seen earlier. Preferences are named using the string name of the preference. The names are qualified with another string (often a plug-in id) that qualifies the namespace of the preference. The following snippet gets a preference node from the project scope. You'll notice that once the correct scope is obtained, working with the nodes is no different than with nodes from other scopes.
... Preferences projectNode = projectScope.getNode("com.example.myplugin"); if (projectNode != null) { value = projectNode.getBoolean("MyPreference", "true"); //do something with the value. } ...
To save the value to a file in the project, the node is flushed. The resources plug-in handles the logistics for managing the project-level preferences file.
projectNode.flush();