Modify the e4 model at startup via processors

Eclipse e4 offers two ways to contribute to the application model, via fragments and processors. Fragments describe via static xmi additonal model elements and processors allow to add and modify existing model elements.

I added an example to my Eclipse 4.0 Tutorial how you could use a processor to remove certain model elements (in my case menu entries) and how to add a new one.


package de.vogella.e4.todo.contribute;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.model.application.ui.menu.MDirectMenuItem;
import org.eclipse.e4.ui.model.application.ui.menu.MMenu;
import org.eclipse.e4.ui.model.application.ui.menu.MMenuElement;
import org.eclipse.e4.ui.model.application.ui.menu.MMenuFactory;

public class MenuProcessor {
	// I get this via the parameter of the process definition
	@Inject
	@Named("de.vogella.e4.todo.filemenu")
	private MMenu menu;

	@Execute
	public void execute() {
		// Remove the old exit menu entry 
		if (menu != null && menu.getChildren() != null) {
			List<MMenuElement> list = new ArrayList<MMenuElement>();
			for (MMenuElement element : menu.getChildren()) {
				if (element.getLabel().contains("Exit")) {
					list.add(element);
				}
			}
			menu.getChildren().removeAll(list);
		}

               // Add a new menu entry
		MDirectMenuItem menuItem = MMenuFactory.INSTANCE.createDirectMenuItem();
		menuItem.setLabel("Another Exit");
		menuItem.setContributionURI("platform:/plugin/de.vogella.e4.todo.contribute/de.vogella.e4.todo.contribute.handler.ExitHandlerWithCheck");
		menu.getChildren().add(menuItem);
	}
}

I hope this shows how simple the application model can be modified. For details check out Eclipse 4.0 Tutorial .

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, With more than one million visitors per month his website vogella.com is one of the central sources for Eclipse and Android programming information.
This entry was posted in Eclipse and tagged , , . Bookmark the permalink.