One of the nicest things in my option in Eclipse e4 is that you have access to the model at runtime and can change it. To get access to the model you can use dependency injection to get the related model elements injected into your class or in you can use the EModelService.
The EModelService is pretty useful in my opinion as it allows you to access multiple model elements and you can use different filters, e.g. id, class name or tags. The following example is the implementation of a e4 handler. The first few statements will get get a few model elements and the last one will actually change the width of the first window to demonstrate that you can directly change model elements.
@Execute
public void execute(MApplication application, EModelService service, Display display) {
System.out.println("Got Model Service: " + (service != null));
// Alternatively get the model service from the application
EModelService modelService = (EModelService) application.getContext()
.get(EModelService.class.getName());
// both services are identical
System.out.println("Got Model Service: " + (service != modelService));
// Find objects by ID
List<MPart> findElements = service.findElements(application, "mypart",
MPart.class, null);
System.out.println("Found part(s) : " + findElements.size());
// Find objects by type
List<MPart> parts = service.findElements(application, null,
MPart.class, null);
System.out.println("Found parts(s) : " + parts.size());
// Find objects by tags
List<String> tags = new ArrayList<String>();
tags.add("justatag");
List<MUIElement> elementsWithTags = modelService.findElements(application, null,
null, tags);
System.out.println("Found parts(s) : " + elementsWithTags.size());
// Get the MWindow and change its size
List<MWindow> windows = modelService.findElements(application, null, MWindow.class,
null);
if (windows.size()>=1){
MWindow mWindow = windows.get(0);
System.out.println("Got the window");
for (int i = mWindow.getWidth(); i >= mWindow.getWidth() - 100; i--) {
while (!display.readAndDispatch()){
mWindow.setWidth(i);
wait10();
}
}
}
}
private void wait10(){
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
As usually find more details about Eclipse e4 in my Eclipse e4 tutorial.
It is pretty nice, but by playing a little with generics, casts could be avoided and possible typing errors:
EModelService modelService = (EModelService) application.getContext()
.get(EModelService.class.getName()); —>
EModelService modelService = application.getContext()
.get(EModelService.class);
class MApplication {
getContext(Class class);
}
@David: cool. Thanks for the additions!