public void testCreateView() {
    final MWindow window = createWindowWithOneView("Part Name");

    MApplication application = ApplicationFactoryImpl.eINSTANCE.createApplication();
    application.getChildren().add(window);
    application.setContext(appContext);
    appContext.set(MApplication.class.getName(), application);

    wb = new E4Workbench(application, appContext);
    wb.createAndRunUI(window);

    MPartSashContainer container = (MPartSashContainer) window.getChildren().get(0);
    MPartStack stack = (MPartStack) container.getChildren().get(0);
    MPart part = (MPart) stack.getChildren().get(0);

    CTabFolder folder = (CTabFolder) stack.getWidget();
    CTabItem item = folder.getItem(0);
    assertEquals("Part Name", item.getText());

    assertFalse(part.isDirty());

    part.setDirty(true);
    assertEquals("*Part Name", item.getText());

    part.setDirty(false);
    assertEquals("Part Name", item.getText());
  }
 private MWindow getWindow() {
   if (workbenchWindow != null) return workbenchWindow;
   if (application.getSelectedElement() != null) return application.getSelectedElement();
   List<MWindow> windows = application.getChildren();
   if (windows.size() != 0) return windows.get(0);
   return null;
 }
 /** Process defined windows and menu contributions */
 protected void processModelMenus() {
   for (MWindow window : app.getChildren()) {
     redirectHandledMenuItems(window.getMainMenu());
   }
   for (MMenuContribution contribution : app.getMenuContributions()) {
     processMenuContribution(contribution);
   }
 }
示例#4
0
  public static void createParts(
      MApplication application, EModelService service, EPartService partService) {
    // Sometimes, when switching windows at startup, the active context
    // is null or doesn't have a window, and the part instantiation fails.
    // Ensure that a child context with a window is activated:
    IEclipseContext activeChild = application.getContext().getActiveChild();
    if (activeChild == null || activeChild.get(MTrimmedWindow.class) == null) {
      boolean activated = false;
      if (application.getContext() instanceof EclipseContext) {
        for (IEclipseContext child : ((EclipseContext) application.getContext()).getChildren()) {
          MTrimmedWindow window = child.get(MTrimmedWindow.class);
          if (window != null) {
            child.activate();
            activated = true;
            break;
          }
        }
      }
      if (!activated) {
        logger.error("Could not activate window for part instantiation"); // $NON-NLS-1$
        return;
      }
    }

    List<MPart> ontops = new ArrayList<MPart>();
    for (MPartDescriptor descriptor : application.getDescriptors()) {
      if (!(descriptor.getPersistedState().containsKey(VISIBLE_ID)
          && Boolean.toString(true)
              .equalsIgnoreCase(descriptor.getPersistedState().get(VISIBLE_ID)))) {
        continue;
      }
      List<MPart> existingParts =
          service.findElements(application, descriptor.getElementId(), MPart.class, null);
      if (!existingParts.isEmpty()) {
        // part is already instantiated
        continue;
      }
      MPart part = partService.createPart(descriptor.getElementId());
      if (part == null) {
        continue;
      }
      addPartToAppropriateContainer(part, descriptor, application, service);
      partService.activate(part);
      if (descriptor.getPersistedState().containsKey(ONTOP_ID)
          && Boolean.toString(true)
              .equalsIgnoreCase(descriptor.getPersistedState().get(ONTOP_ID))) {
        ontops.add(part);
      }
    }

    // reactivate ontop parts to ensure they are on-top
    for (MPart ontop : ontops) {
      partService.activate(ontop);
    }
  }
    public void createControl(Composite parent) {
      setTitle("Keybinding");
      setMessage("Insert informations for a keybinding");

      Composite group = new Composite(parent, SWT.NONE);
      group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      group.setLayout(new GridLayout(2, false));

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Sequence");

        keyField = new Text(group, SWT.BORDER);
        keyField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        keyField.addModifyListener(
            new ModifyListener() {

              public void modifyText(ModifyEvent e) {
                bindtableViewer.getControl().setEnabled(isPageComplete());
                setPageComplete(isPageComplete());
              }
            });
      }

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Binding Table");
        l.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));

        bindtableViewer = new TableViewer(group);
        bindtableViewer.setLabelProvider(new ComponentLabelProvider(getEditor(), Messages));
        bindtableViewer.setContentProvider(new ArrayContentProvider());
        bindtableViewer.setInput(application.getBindingTables());
        bindtableViewer.addSelectionChangedListener(
            new ISelectionChangedListener() {

              public void selectionChanged(SelectionChangedEvent event) {
                setPageComplete(isPageComplete());
              }
            });
        bindtableViewer.setSelection(
            new StructuredSelection(application.getBindingTables().get(0)));
        GridData gd = new GridData(GridData.FILL_BOTH);
        gd.heightHint = bindtableViewer.getTable().getItemHeight() * 5;
        bindtableViewer.getControl().setLayoutData(gd);
        bindtableViewer.getControl().setEnabled(false);
      }

      setControl(group);
    }
  @Override
  public MPartDescriptor getPartDescriptor(String id) {
    MApplication application = appContext.get(MApplication.class);

    // If the id contains a ':' use the part before it as the descriptor id
    int colonIndex = id == null ? -1 : id.indexOf(':');
    String descId = colonIndex == -1 ? id : id.substring(0, colonIndex);

    for (MPartDescriptor descriptor : application.getDescriptors()) {
      if (descriptor.getElementId().equals(descId)) {
        return descriptor;
      }
    }
    return null;
  }
        public void selectionChanged(MPart part, Object selection) {
          selection = createCompatibilitySelection(selection);
          context.set(ISources.ACTIVE_CURRENT_SELECTION_NAME, selection);

          IEclipseContext applicationContext = application.getContext();
          if (applicationContext.getActiveChild() == context) {
            application.getContext().set(ISources.ACTIVE_CURRENT_SELECTION_NAME, selection);
          }

          Object client = part.getObject();
          if (client instanceof CompatibilityPart) {
            IWorkbenchPart workbenchPart = ((CompatibilityPart) client).getPart();
            notifyListeners(part.getElementId(), workbenchPart, (ISelection) selection);
          }
        }
  /*
   * Action implementation for the toolbar button
   */
  @SuppressWarnings("restriction")
  void toolbarButtonClicked(NSControl source) {
    try {
      NSWindow window = source.window();
      Field idField = NSWindow.class.getField("id"); // $NON-NLS-1$
      Object idValue = idField.get(window);

      Display display = Display.getCurrent();
      Widget widget =
          (Widget)
              invokeMethod(
                  Display.class, display, "findWidget", new Object[] {idValue}); // $NON-NLS-1$

      if (!(widget instanceof Shell)) {
        return;
      }
      Shell shell = (Shell) widget;
      for (MWindow mwin : app.getChildren()) {
        if (mwin.getWidget() == shell) {
          if (!runCommand(COMMAND_ID_TOGGLE_COOLBAR)) {
            // there may be a menu item to do the toggle...
            runAction(COMMAND_ID_TOGGLE_COOLBAR);
          }
        }
      }
    } catch (Exception e) {
      // theoretically, one of
      // SecurityException,Illegal*Exception,InvocationTargetException,NoSuch*Exception
      // not expected to happen at all.
      log(e);
    }
  }
  private MMenuItem createFeature(Feature f) {
    MHandledMenuItem e = modelService.createModelElement(MHandledMenuItem.class);
    e.setLabel("%editorfeature." + f.name());
    e.setContributorURI("platform:/plugin/at.bestsolution.dart.app");
    e.setType(ItemType.CHECK);
    if (f == Feature.SHOW_LINE_NUMBERS) {
      e.setSelected(true);
    }

    MParameter parameter = modelService.createModelElement(MParameter.class);
    parameter.setName("feature");
    parameter.setValue(f.name());

    e.getParameters().add(parameter);
    application
        .getCommands()
        .stream()
        .filter(
            c -> c.getElementId().equals("at.bestsolution.dart.app.command.toggleeditorfeature"))
        .findFirst()
        .ifPresent(e::setCommand);
    itemMap.put(f, e);

    return e;
  }
 private void defineContexts() {
   Activator.trace(
       Policy.DEBUG_CMDS, "Initialize contexts and parents from model", null); // $NON-NLS-1$
   for (MBindingContext root : application.getRootContext()) {
     defineContexts(null, root);
   }
 }
 protected MCommand findCommand(String commandId) {
   for (MCommand cmd : application.getCommands()) {
     if (commandId.equals(cmd.getElementId())) {
       return cmd;
     }
   }
   return null;
 }
  @Test
  public void testBug310027() {
    MApplication application = ApplicationFactoryImpl.eINSTANCE.createApplication();
    MWindow window = BasicFactoryImpl.eINSTANCE.createWindow();
    MPartSashContainer container = BasicFactoryImpl.eINSTANCE.createPartSashContainer();
    MPartStack partStackA = BasicFactoryImpl.eINSTANCE.createPartStack();
    MPartStack partStackB = BasicFactoryImpl.eINSTANCE.createPartStack();
    MPart partA = BasicFactoryImpl.eINSTANCE.createPart();
    MPart partB = BasicFactoryImpl.eINSTANCE.createPart();

    window.setWidth(600);
    window.setHeight(400);

    partStackA.setContainerData("50");
    partStackB.setContainerData("50");

    application.getChildren().add(window);
    application.setSelectedElement(window);

    window.getChildren().add(container);
    window.setSelectedElement(container);

    container.getChildren().add(partStackA);
    container.getChildren().add(partStackB);
    container.setSelectedElement(partStackA);

    partStackA.getChildren().add(partA);
    partStackA.setSelectedElement(partA);
    partStackA.getChildren().add(partB);
    partStackA.setSelectedElement(partB);

    application.setContext(appContext);
    appContext.set(MApplication.class, application);

    wb = new E4Workbench(application, appContext);
    wb.createAndRunUI(window);

    assertEquals("50", partStackA.getContainerData());
    assertEquals("50", partStackB.getContainerData());

    partStackB.setToBeRendered(false);

    while (Display.getDefault().readAndDispatch()) ;

    assertEquals("50", partStackA.getContainerData());
  }
  /**
   * Updates the selection of the workbench window with that of the active part's.
   *
   * @param activePart the currently active part
   */
  public void updateSelection(IWorkbenchPart activePart) {
    if (activePart != null) {
      ISelectionProvider selectionProvider = activePart.getSite().getSelectionProvider();
      if (selectionProvider != null) {
        ISelection selection = selectionProvider.getSelection();
        context.set(ISources.ACTIVE_CURRENT_SELECTION_NAME, selection);

        IEclipseContext applicationContext = application.getContext();
        if (applicationContext.getActiveChild() == context) {
          application.getContext().set(ISources.ACTIVE_CURRENT_SELECTION_NAME, selection);
        }

        notifyListeners(activePart.getSite().getId(), activePart, selection);
        notifyPostSelectionListeners(activePart.getSite().getId(), activePart, selection);
      }
    }
  }
 protected MCategory findCategory(String id) {
   final List<MCategory> categories = application.getCategories();
   for (MCategory cat : categories) {
     if (id.equals(cat.getElementId())) {
       return cat;
     }
   }
   return null;
 }
 public static MCommand getCommandById(MApplication app, String cmdId) {
   final List<MCommand> cmds = app.getCommands();
   for (MCommand cmd : cmds) {
     if (cmdId.equals(cmd.getElementId())) {
       return cmd;
     }
   }
   return null;
 }
 private void switchPerspective(MPerspective perspective) {
   if (perspective.isToBeRendered() && perspective.getWidget() == null)
     engine.createGui(perspective);
   partService.switchPerspective(perspective);
   this.activePerspective = perspective;
   if (perspective.getElementId() != null) {
     String perspectiveId = perspective.getElementId().trim();
     application.getContext().set("activePerspective", perspectiveId);
   }
 }
 @PostConstruct
 public void init(MApplication application, IEclipseContext context) {
   IEclipseContext appContext = application.getContext();
   appContext.set(Preferences.class, ContextInjectionFactory.make(Preferences.class, appContext));
   appContext.set(
       PreferenceStore.class, ContextInjectionFactory.make(PreferenceStore.class, appContext));
   ContextInjectionFactory.make(Services.class, context);
   ProgressManager progressManager = ContextInjectionFactory.make(ProgressManager.class, context);
   appContext.set(ProgressManager.class, progressManager);
 }
 private void defineContexts(MBindingContext parent, MBindingContext current) {
   if (current.getName() == null || current.getElementId() == null) {
     logger.error("Binding context name or id is null for: " + current); // $NON-NLS-1$
     return;
   }
   Context context = contextManager.getContext(current.getElementId());
   if (!context.isDefined()) {
     String localizedName =
         LocalizationHelper.getLocalized(current.getName(), current, application.getContext());
     String localizedDescriptor =
         LocalizationHelper.getLocalized(
             current.getDescription(), current, application.getContext());
     context.define(
         localizedName, localizedDescriptor, parent == null ? null : parent.getElementId());
   }
   for (MBindingContext child : current.getChildren()) {
     defineContexts(current, child);
   }
 }
示例#19
0
  @PersistState
  public void savePersistState(MApplication application) {

    LOG.debug("persistState:");

    final Map<String, String> persistedState = application.getPersistedState();

    persistedState.put(IPersistenceKey.TERMINAL_SUPPRESS_LINES, "" + showSuppressedLines);
    persistedState.put(IPersistenceKey.TERMINAL_GRBL_STATE, "" + showGrblStateLines);
    persistedState.put(IPersistenceKey.TERMINAL_GRBL_MODES, "" + showGcodeModeLines);
  }
  private void testTrimContainer_Side(
      SideValue applicationState, SideValue userChange, SideValue newApplicationState) {
    MApplication application = createApplication();

    MTrimmedWindow window = createTrimmedWindow(application);

    MTrimBar trimBar = BasicFactoryImpl.eINSTANCE.createTrimBar();
    trimBar.setSide(applicationState);
    window.getTrimBars().add(trimBar);

    saveModel();

    ModelReconciler reconciler = createModelReconciler();
    reconciler.recordChanges(application);

    trimBar.setSide(userChange);

    Object serialize = reconciler.serialize();

    application = createApplication();
    window = (MTrimmedWindow) application.getChildren().get(0);
    trimBar = window.getTrimBars().get(0);

    trimBar.setSide(newApplicationState);

    Collection<ModelDelta> deltas = constructDeltas(application, serialize);

    assertEquals(newApplicationState, trimBar.getSide());

    applyAll(deltas);

    if (userChange == applicationState) {
      // no change from the user, the new state is applied
      assertEquals(newApplicationState, trimBar.getSide());
    } else {
      // user change must override application state
      assertEquals(userChange, trimBar.getSide());
    }
  }
  /**
   * Locate an action (a menu item, actually) with the given id in the current menu bar and run it.
   *
   * @param actionId the action to find
   * @return true if an action was found, false otherwise
   */
  private boolean runAction(String actionId) {
    MWindow window = app.getSelectedElement();
    if (window == null) {
      return false;
    }
    MMenu topMenu = window.getMainMenu();
    MMenuItem item = findAction(actionId, topMenu);
    if (item == null || !item.isEnabled()) {
      return false;
    }
    try {
      // disable the about and prefs items -- they shouldn't be
      // able to be run when another item is being triggered
      final Display display = Display.getDefault();
      MenuItem aboutItem = null;
      boolean aboutEnabled = true;
      MenuItem prefsItem = null;
      boolean prefsEnabled = true;

      Menu appMenuBar = display.getMenuBar();
      if (appMenuBar != null) {
        aboutItem = findMenuItemById(appMenuBar, SWT.ID_ABOUT);
        if (aboutItem != null) {
          aboutEnabled = aboutItem.getEnabled();
          aboutItem.setEnabled(false);
        }
        prefsItem = findMenuItemById(appMenuBar, SWT.ID_PREFERENCES);
        if (prefsItem != null) {
          prefsEnabled = prefsItem.getEnabled();
          prefsItem.setEnabled(false);
        }
      }
      try {
        simulateMenuSelection(item);
      } finally {
        if (prefsItem != null) {
          prefsItem.setEnabled(prefsEnabled);
        }
        if (aboutItem != null) {
          aboutItem.setEnabled(aboutEnabled);
        }
      }
    } catch (Exception e) {
      // theoretically, one of
      // SecurityException,Illegal*Exception,InvocationTargetException,NoSuch*Exception
      // not expected to happen at all.
      log(e);
      // return false?
    }
    return true;
  }
  @SuppressWarnings("restriction")
  @Execute
  public void execute(
      MApplication app, EModelService service, IExtensionRegistry registery, IThemeManager mgr) {

    // sanity check
    if (menu == null) {
      return;
    }

    List<String> tags = app.getTags();
    for (String tag : tags) {
      if (PROCESSOR_ID.equals(tag)) {
        return; // already processed
      }
    }

    tags.add(PROCESSOR_ID);

    IThemeEngine engine = mgr.getEngineForDisplay(Display.getCurrent());

    List<ITheme> themes = engine.getThemes();

    MCommand switchThemeCommand = ThemeHelper.findCommand(app);

    // no themes or command, stop processing
    if (themes.size() <= 0 || switchThemeCommand == null) {
      return;
    }

    themesMenu = service.createModelElement(MMenu.class);
    themesMenu.setLabel("%switchThemeMenu"); // $NON-NLS-1$
    themesMenu.setContributorURI(BUNDLE_ID);

    for (ITheme theme : themes) {
      if (!theme.getId().startsWith("org.eclipse.e4.demo.contacts.")) {
        return;
      }
      MParameter parameter = service.createModelElement(MParameter.class);
      parameter.setName("contacts.commands.switchtheme.themeid"); // $NON-NLS-1$
      parameter.setValue(theme.getId());
      String iconURI = ThemeHelper.getCSSUri(theme.getId(), registery);
      if (iconURI != null) {
        iconURI = iconURI.replace(".css", ".png");
      }
      processTheme(theme.getLabel(), switchThemeCommand, parameter, iconURI, service);
    }
    menu.getChildren().add(themesMenu);
  }
 public static void initializeServices(MApplication appModel) {
   IEclipseContext appContext = appModel.getContext();
   // make sure we only add trackers once
   if (appContext.containsKey(CONTEXT_INITIALIZED)) return;
   appContext.set(CONTEXT_INITIALIZED, "true");
   initializeApplicationServices(appContext);
   List<MWindow> windows = appModel.getChildren();
   for (MWindow childWindow : windows) {
     initializeWindowServices(childWindow);
   }
   ((EObject) appModel)
       .eAdapters()
       .add(
           new AdapterImpl() {
             @Override
             public void notifyChanged(Notification notification) {
               if (notification.getFeatureID(MApplication.class)
                   != UiPackageImpl.ELEMENT_CONTAINER__CHILDREN) return;
               if (notification.getEventType() != Notification.ADD) return;
               MWindow childWindow = (MWindow) notification.getNewValue();
               initializeWindowServices(childWindow);
             }
           });
 }
 @Override
 public void processContents(MElementContainer<MUIElement> container) {
   super.processContents(container);
   IEclipseContext ctx = getContext(container);
   ExpressionContext eContext = new ExpressionContext(ctx);
   ArrayList<MToolBarContribution> toContribute = new ArrayList<MToolBarContribution>();
   MElementContainer<?> toolbarObj = container;
   MToolBar toolbarModel = (MToolBar) toolbarObj;
   ContributionsAnalyzer.gatherToolBarContributions(
       toolbarModel,
       application.getToolBarContributions(),
       toolbarModel.getElementId(),
       toContribute,
       eContext);
   addToolBarContributions(toolbarModel, toContribute, ctx, eContext, pendingCleanup);
 }
 public void stop() {
   // FIXME Without this call the test-suite fails
   cleanUp();
   if (theApp != null) {
     for (MWindow window : theApp.getChildren()) {
       if (window.getWidget() != null) {
         removeGui(window);
       }
     }
   } else if (testShell != null && !testShell.isDisposed()) {
     Object model = testShell.getData(AbstractPartRenderer.OWNING_ME);
     if (model instanceof MUIElement) {
       removeGui((MUIElement) model);
     } else {
       testShell.close();
     }
   }
 }
 /**
  * @param menuModel
  * @param isMenuBar
  * @param isPopup
  */
 public void processContributions(MMenu menuModel, boolean isMenuBar, boolean isPopup) {
   if (menuModel.getElementId() == null) {
     return;
   }
   final ArrayList<MMenuContribution> toContribute = new ArrayList<MMenuContribution>();
   ContributionsAnalyzer.XXXgatherMenuContributions(
       menuModel,
       application.getMenuContributions(),
       menuModel.getElementId(),
       toContribute,
       null,
       isPopup);
   generateContributions(menuModel, toContribute, isMenuBar);
   for (MMenuElement element : menuModel.getChildren()) {
     if (element instanceof MMenu) {
       processContributions((MMenu) element, false, isPopup);
     }
   }
 }
示例#27
0
  private void restorePersistedState(MApplication application, MPart part) {

    final Map<String, String> persistedState = application.getPersistedState();
    showSuppressedLines =
        toolbox.parseBoolean(persistedState.get(IPersistenceKey.TERMINAL_SUPPRESS_LINES));
    showGrblStateLines =
        toolbox.parseBoolean(persistedState.get(IPersistenceKey.TERMINAL_GRBL_STATE));
    showGcodeModeLines =
        toolbox.parseBoolean(persistedState.get(IPersistenceKey.TERMINAL_GRBL_MODES));

    // set the state of the direct menu items according to persisted state
    // find the two direct menu items
    final MToolBar toolbar = part.getToolbar();
    List<MToolBarElement> toolBarChildren = toolbar.getChildren();
    for (MToolBarElement child : toolBarChildren) {
      if (child instanceof MHandledToolItem
          && child
              .getElementId()
              .equals("de.jungierek.grblrunner.handledtoolitem.terminal.togglesuppresslines")) {
        LOG.debug(
            "restorePersistedState: child=" + child.getElementId() + " class=" + child.getClass());
        MMenu menu = ((MHandledToolItem) child).getMenu();
        if (menu != null) {
          List<MMenuElement> items = menu.getChildren();
          for (MMenuElement item : items) {
            LOG.debug(
                "restorePersistedState: item=" + item.getElementId() + "class=" + child.getClass());
            switch (item.getElementId()) {
              case "de.jungierek.grblrunner.directmenuitem.togglesuppresslines.grblstate":
                ((MMenuItem) item).setSelected(showGrblStateLines);
                break;
              case "de.jungierek.grblrunner.directmenuitem.togglesuppresslines.gcodestate":
                ((MMenuItem) item).setSelected(showGcodeModeLines);
                break;
              default:
                break;
            }
          }
        }
      }
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.e4.ui.workbench.renderers.swt.SWTPartRenderer#processContents
   * (org.eclipse.e4.ui.model.application.ui.MElementContainer)
   */
  @Override
  public void processContents(MElementContainer<MUIElement> container) {
    if (container.getChildren().size() == 0) {
      Object obj = container.getWidget();
      if (obj instanceof MenuItem) {
        MenuItem mi = (MenuItem) obj;
        if (mi.getMenu() == null) {
          mi.setMenu(new Menu(mi));
        }
        Menu menu = mi.getMenu();
        MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
        menuItem.setText(MenuManagerRendererFilter.NUL_MENU_ITEM);
        menuItem.setEnabled(false);
      }
    }

    super.processContents(container);

    Object obj = container.getWidget();
    Object menuObj = container;
    if ((obj instanceof Menu)
        && (((Menu) obj).getStyle() & SWT.BAR) != 0
        && (menuObj instanceof MMenu)) {
      MMenu menuModel = (MMenu) menuObj;
      IEclipseContext ctx = getContext(container);
      ExpressionContext eContext = new ExpressionContext(ctx);
      ArrayList<MMenuContribution> toContribute = new ArrayList<MMenuContribution>();
      ContributionsAnalyzer.gatherMenuContributions(
          menuModel,
          application.getMenuContributions(),
          menuModel.getElementId(),
          toContribute,
          eContext,
          false);
      addMenuBarContributions(menuModel, toContribute, ctx, eContext);
    }
  }
  public E4Workbench createE4Workbench(
      IApplicationContext applicationContext, final Display display) {
    args = (String[]) applicationContext.getArguments().get(IApplicationContext.APPLICATION_ARGS);

    IEclipseContext appContext = createDefaultContext();
    appContext.set(Display.class, display);
    appContext.set(Realm.class, DisplayRealm.getRealm(display));
    appContext.set(
        UISynchronize.class,
        new UISynchronize() {

          @Override
          public void syncExec(Runnable runnable) {
            if (display != null && !display.isDisposed()) {
              display.syncExec(runnable);
            }
          }

          @Override
          public void asyncExec(Runnable runnable) {
            if (display != null && !display.isDisposed()) {
              display.asyncExec(runnable);
            }
          }
        });
    appContext.set(IApplicationContext.class, applicationContext);

    // This context will be used by the injector for its
    // extended data suppliers
    ContextInjectionFactory.setDefault(appContext);

    // Get the factory to create DI instances with
    IContributionFactory factory = appContext.get(IContributionFactory.class);

    // Install the life-cycle manager for this session if there's one
    // defined
    Optional<String> lifeCycleURI =
        getArgValue(IWorkbench.LIFE_CYCLE_URI_ARG, applicationContext, false);
    lifeCycleURI.ifPresent(
        lifeCycleURIValue -> {
          lcManager = factory.create(lifeCycleURIValue, appContext);
          if (lcManager != null) {
            // Let the manager manipulate the appContext if desired
            ContextInjectionFactory.invoke(lcManager, PostContextCreate.class, appContext, null);
          }
        });

    Optional<String> forcedPerspectiveId =
        getArgValue(PERSPECTIVE_ARG_NAME, applicationContext, false);
    forcedPerspectiveId.ifPresent(
        forcedPerspectiveIdValue ->
            appContext.set(E4Workbench.FORCED_PERSPECTIVE_ID, forcedPerspectiveIdValue));

    String showLocation = getLocationFromCommandLine();
    if (showLocation != null) {
      appContext.set(E4Workbench.FORCED_SHOW_LOCATION, showLocation);
    }

    // Create the app model and its context
    MApplication appModel = loadApplicationModel(applicationContext, appContext);
    appModel.setContext(appContext);

    boolean isRtl = ((Window.getDefaultOrientation() & SWT.RIGHT_TO_LEFT) != 0);
    appModel.getTransientData().put(E4Workbench.RTL_MODE, isRtl);

    // for compatibility layer: set the application in the OSGi service
    // context (see Workbench#getInstance())
    if (!E4Workbench.getServiceContext().containsKey(MApplication.class)) {
      // first one wins.
      E4Workbench.getServiceContext().set(MApplication.class, appModel);
    }

    // Set the app's context after adding itself
    appContext.set(MApplication.class, appModel);

    // adds basic services to the contexts
    initializeServices(appModel);

    // let the life cycle manager add to the model
    if (lcManager != null) {
      ContextInjectionFactory.invoke(lcManager, ProcessAdditions.class, appContext, null);
      ContextInjectionFactory.invoke(lcManager, ProcessRemovals.class, appContext, null);
    }

    // Create the addons
    IEclipseContext addonStaticContext = EclipseContextFactory.create();
    for (MAddon addon : appModel.getAddons()) {
      addonStaticContext.set(MAddon.class, addon);
      Object obj = factory.create(addon.getContributionURI(), appContext, addonStaticContext);
      addon.setObject(obj);
    }

    // Parse out parameters from both the command line and/or the product
    // definition (if any) and put them in the context
    Optional<String> xmiURI = getArgValue(IWorkbench.XMI_URI_ARG, applicationContext, false);
    xmiURI.ifPresent(
        xmiURIValue -> {
          appContext.set(IWorkbench.XMI_URI_ARG, xmiURIValue);
        });

    setCSSContextVariables(applicationContext, appContext);

    Optional<String> rendererFactoryURI =
        getArgValue(E4Workbench.RENDERER_FACTORY_URI, applicationContext, false);
    rendererFactoryURI.ifPresent(
        rendererFactoryURIValue -> {
          appContext.set(E4Workbench.RENDERER_FACTORY_URI, rendererFactoryURIValue);
        });

    // This is a default arg, if missing we use the default rendering engine
    Optional<String> presentationURI =
        getArgValue(IWorkbench.PRESENTATION_URI_ARG, applicationContext, false);
    appContext.set(
        IWorkbench.PRESENTATION_URI_ARG, presentationURI.orElse(PartRenderingEngine.engineURI));

    // Instantiate the Workbench (which is responsible for
    // 'running' the UI (if any)...
    return workbench = new E4Workbench(appModel, appContext);
  }
  private <T> void findElementsRecursive(
      MApplicationElement searchRoot,
      Class<T> clazz,
      Selector matcher,
      List<T> elements,
      int searchFlags) {
    Assert.isLegal(searchRoot != null);
    if (searchFlags == 0) {
      return;
    }

    // are *we* a match ?
    boolean classMatch = clazz == null ? true : clazz.isInstance(searchRoot);
    if (classMatch && matcher.select(searchRoot)) {
      if (!elements.contains(searchRoot)) {
        @SuppressWarnings("unchecked")
        T element = (T) searchRoot;
        elements.add(element);
      }
    }
    if (searchRoot instanceof MApplication && (searchFlags == ANYWHERE)) {
      MApplication app = (MApplication) searchRoot;

      List<MApplicationElement> children = new ArrayList<>();
      if (clazz != null) {
        if (clazz.equals(MHandler.class)) {
          children.addAll(app.getHandlers());
        } else if (clazz.equals(MCommand.class)) {
          children.addAll(app.getCommands());
        } else if (clazz.equals(MBindingContext.class)) {
          children.addAll(app.getBindingContexts());
        } else if (clazz.equals(MBindingTable.class) || clazz.equals(MKeyBinding.class)) {
          children.addAll(app.getBindingTables());
        }
        // } else { only look for these if specifically asked.
        // children.addAll(app.getHandlers());
        // children.addAll(app.getCommands());
        // children.addAll(app.getBindingContexts());
        // children.addAll(app.getBindingTables());
      }

      for (MApplicationElement child : children) {
        findElementsRecursive(child, clazz, matcher, elements, searchFlags);
      }
    }

    if (searchRoot instanceof MBindingContext && (searchFlags == ANYWHERE)) {
      MBindingContext bindingContext = (MBindingContext) searchRoot;
      for (MBindingContext child : bindingContext.getChildren()) {
        findElementsRecursive(child, clazz, matcher, elements, searchFlags);
      }
    }

    if (searchRoot instanceof MBindingTable) {
      MBindingTable bindingTable = (MBindingTable) searchRoot;
      for (MKeyBinding child : bindingTable.getBindings()) {
        findElementsRecursive(child, clazz, matcher, elements, searchFlags);
      }
    }

    // Check regular containers
    if (searchRoot instanceof MElementContainer<?>) {
      /*
       * Bug 455281: If given a window with a primary perspective stack,
       * and we're not told to look outside of the perspectives (i.e.,
       * searchFlags is missing OUTSIDE_PERSPECTIVE), then just search the
       * primary perspective stack instead. This ignores special areas
       * like the compat layer's stack holding the Help, CheatSheets, and
       * Intro.
       */
      MElementContainer<?> searchContainer = (MElementContainer<?>) searchRoot;
      MPerspectiveStack primaryStack = null;
      if (searchRoot instanceof MWindow
          && (searchFlags & OUTSIDE_PERSPECTIVE) == 0
          && (primaryStack = getPrimaryPerspectiveStack((MWindow) searchRoot)) != null) {
        searchContainer = primaryStack;
      }
      if (searchContainer instanceof MPerspectiveStack) {
        if ((searchFlags & IN_ANY_PERSPECTIVE) != 0) {
          // Search *all* the perspectives
          MElementContainer<? extends MUIElement> container = searchContainer;
          List<? extends MUIElement> children = container.getChildren();
          for (MUIElement child : children) {
            findElementsRecursive(child, clazz, matcher, elements, searchFlags);
          }
        } else if ((searchFlags & IN_ACTIVE_PERSPECTIVE) != 0) {
          // Only search the currently active perspective, if any
          MPerspective active = ((MPerspectiveStack) searchContainer).getSelectedElement();
          if (active != null) {
            findElementsRecursive(active, clazz, matcher, elements, searchFlags);
          }
        } else if ((searchFlags & IN_SHARED_AREA) != 0) {
          // Only recurse through the shared areas
          List<MArea> areas = findElements(searchContainer, null, MArea.class, null);
          for (MArea area : areas) {
            findElementsRecursive(area, clazz, matcher, elements, searchFlags);
          }
        }
      } else {
        @SuppressWarnings("unchecked")
        MElementContainer<MUIElement> container = (MElementContainer<MUIElement>) searchRoot;
        List<MUIElement> children = container.getChildren();
        for (MUIElement child : children) {
          findElementsRecursive(child, clazz, matcher, elements, searchFlags);
        }
      }
    }

    // Search Trim
    if (searchRoot instanceof MTrimmedWindow && (searchFlags & IN_TRIM) != 0) {
      MTrimmedWindow tw = (MTrimmedWindow) searchRoot;
      List<MTrimBar> bars = tw.getTrimBars();
      for (MTrimBar bar : bars) {
        findElementsRecursive(bar, clazz, matcher, elements, searchFlags);
      }
    }

    // Search Detached Windows
    if (searchRoot instanceof MWindow) {
      MWindow window = (MWindow) searchRoot;
      for (MWindow dw : window.getWindows()) {
        findElementsRecursive(dw, clazz, matcher, elements, searchFlags);
      }

      MMenu menu = window.getMainMenu();
      if (menu != null && (searchFlags & IN_MAIN_MENU) != 0) {
        findElementsRecursive(menu, clazz, matcher, elements, searchFlags);
      }
      // Check for Handlers
      if (searchFlags == ANYWHERE && MHandler.class.equals(clazz)) {
        for (MHandler child : window.getHandlers()) {
          findElementsRecursive(child, clazz, matcher, elements, searchFlags);
        }
      }
    }

    if (searchRoot instanceof MPerspective) {
      MPerspective persp = (MPerspective) searchRoot;
      for (MWindow dw : persp.getWindows()) {
        findElementsRecursive(dw, clazz, matcher, elements, searchFlags);
      }
    }
    // Search shared elements
    if (searchRoot instanceof MPlaceholder) {
      MPlaceholder ph = (MPlaceholder) searchRoot;

      // Don't search in shared areas unless the flag is set
      if (ph.getRef() != null
          && (!(ph.getRef() instanceof MArea) || (searchFlags & IN_SHARED_AREA) != 0)) {
        findElementsRecursive(ph.getRef(), clazz, matcher, elements, searchFlags);
      }
    }

    if (searchRoot instanceof MPart && (searchFlags & IN_PART) != 0) {
      MPart part = (MPart) searchRoot;

      for (MMenu menu : part.getMenus()) {
        findElementsRecursive(menu, clazz, matcher, elements, searchFlags);
      }

      MToolBar toolBar = part.getToolbar();
      if (toolBar != null) {
        findElementsRecursive(toolBar, clazz, matcher, elements, searchFlags);
      }
      if (MHandler.class.equals(clazz)) {
        for (MHandler child : part.getHandlers()) {
          findElementsRecursive(child, clazz, matcher, elements, searchFlags);
        }
      }
    }
  }