Time for action – reusing expressions

Although it's possible to copy and paste expressions between places where they are used, it is preferable to re-use an identical expression.

  1. Declare an expression using the expression's extension point, by opening the plugin.xml file of the clock.ui project.
    <extension point="org.eclipse.core.expressions.definitions">
      <definition id="when.hello.is.active">
        <with variable="activeContexts">
          <iterate operator="or">
            <equals value="org.eclipse.jdt.ui.javaEditorScope"/>
          </iterate>
        </with>
      </definition>
    </extension>

    If defined via the extension wizard, it will prompt to add dependency on the org.eclipse.core.expressions bundle. This isn't strictly necessary for this example to work.

  2. To use the definition, the enablement expressions needs to use the reference.
    <extension point="org.eclipse.ui.menus">
      <menuContribution allPopups="false"
       locationURI="menu:help?after=additions">
        <command commandId="com.packtpub.e4.clock.ui.command.hello"
         label="Hello" style="push">
          <visibleWhen>
    	  //The following commented lines of code need to be removed
            /*<with variable="activeContexts">
              <iterate operator="or">
                <equals value="org.eclipse.jdt.ui.javaEditorScope"/>
              </iterate>
            </with>*/
            <reference definitionId="when.hello.is.active"/>
          </visibleWhen>
        </command>
      </menuContribution>
    </extension>
  3. Now that the reference has been defined, it can be used to modify the handler as well, so that the handler and menu become active and visible together. Add the following to the Hello handler in the plugin.xml file:
    <extension point="org.eclipse.ui.handlers">
      <handler class="com.packtpub.e4.clock.ui.handlers.Hello"
       commandId="com.packtpub.e4.clock.ui.command.hello">
        <enabledWhen>
          <reference definitionId="when.hello.is.active"/>
        </enabledWhen>
      </handler>
    </extension>
  4. Run the Eclipse application and exactly the same behavior will occur; but should the enablement change, it can be done in one place.

What just happened?

The org.eclipse.core.expressions extension point defined a virtual condition that could be evaluated when the user's context changes, so both the menu and the handler can be made visible and enabled at the same time. The reference was bound in the enabledWhen condition for the handler, and the visibleWhen condition for the menu.

Since references can be used anywhere, expressions can also be defined in terms of other expressions. As long as the expressions aren't recursive, they can be built up in any manner.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset