@Override public Object compute(IEclipseContext context, String contextKey) { // look for the top-most MWindow in the context chain: // 1st: go up the tree to find topmost MWindow MWindow window = null; IEclipseContext current = context; do { MContext model = current.get(MContext.class); if (model instanceof MWindow) window = (MWindow) model; current = current.getParent(); } while (current != null); if (window == null) { if (context.get(MApplication.class) != null) { // called from Application scope return ContextInjectionFactory.make(ApplicationPartServiceImpl.class, context); } return IInjector.NOT_A_VALUE; } IEclipseContext windowContext = window.getContext(); PartServiceImpl service = windowContext.getLocal(PartServiceImpl.class); if (service == null) { service = ContextInjectionFactory.make(PartServiceImpl.class, windowContext); windowContext.set(PartServiceImpl.class, service); } return service; }
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); } }
/** * This is a singleton service. One instance is used throughout the running application * * @param appContext The applicationContext to get the eventBroker from * @throws NullPointerException if the given appContext is <code>null</code> */ public ModelServiceImpl(IEclipseContext appContext) { if (appContext == null) { throw new NullPointerException("No application context given!"); // $NON-NLS-1$ } this.appContext = appContext; IEventBroker eventBroker = appContext.get(IEventBroker.class); eventBroker.subscribe(UIEvents.UIElement.TOPIC_WIDGET, hostedElementHandler); mApplicationElementFactory = new GenericMApplicationElementFactoryImpl(appContext.get(IExtensionRegistry.class)); }
@Inject public void injectedMethod( @Named("arg1") String strValue, @Named("arg2") Integer intValue, IEclipseContext context) { string = strValue; integer = intValue; if (context == null) { other = null; return; } IEclipseContext otherContext = (IEclipseContext) context.get("otherContext"); if (otherContext == null) { other = null; } else { other = (String) otherContext.get("arg3"); } }
private void cleanUpContributionCache() { if (!actionContributionCache.isEmpty()) { PluginActionContributionItem[] items = actionContributionCache.toArray( new PluginActionContributionItem[actionContributionCache.size()]); actionContributionCache.clear(); for (int i = 0; i < items.length; i++) { items[i].dispose(); } } if (modelPart == null || menuModel == null) { return; } IEclipseContext modelContext = modelPart.getContext(); if (modelContext != null) { IRendererFactory factory = modelContext.get(IRendererFactory.class); if (factory != null) { AbstractPartRenderer obj = factory.getRenderer(menuModel, null); if (obj instanceof MenuManagerRenderer) { MenuManagerRenderer renderer = (MenuManagerRenderer) obj; renderer.cleanUp(menuModel); } } } }
/* * (non-Javadoc) * * @see * org.eclipse.e4.ui.internal.workbench.swt.AbstractPartRenderer#createWidget * (org.eclipse.e4.ui.model.application.ui.MUIElement, java.lang.Object) */ @Override public Object createWidget(final MUIElement element, Object parent) { if (!(element instanceof MToolBar) || !(parent instanceof Composite)) return null; final MToolBar toolbarModel = (MToolBar) element; ToolBar newTB = createToolbar(toolbarModel, (Composite) parent); bindWidget(element, newTB); processContribution(toolbarModel, toolbarModel.getElementId()); Control renderedCtrl = newTB; MUIElement parentElement = element.getParent(); if (parentElement instanceof MTrimBar) { element.getTags().add("Draggable"); // $NON-NLS-1$ setCSSInfo(element, newTB); boolean vertical = false; MTrimBar bar = (MTrimBar) parentElement; vertical = bar.getSide() == SideValue.LEFT || bar.getSide() == SideValue.RIGHT; IEclipseContext parentContext = getContextForParent(element); CSSRenderingUtils cssUtils = parentContext.get(CSSRenderingUtils.class); if (cssUtils != null) { renderedCtrl = (Composite) cssUtils.frameMeIfPossible(newTB, null, vertical, true); } } return renderedCtrl; }
@Override public void initialize(String nodeID, IEclipseContext context) { alternative = (InputAlternative) context.get(IEditorInputResource.class); if (alternative != null) { alternative.addPropertyChangeListener(projectListener); } }
private void generateGcodeProgram() { LOG.debug("generateGcodeProgram:"); gcodeProgram.clear(); gcodeProgram.appendLine("(Macro for " + getTitle() + ")"); gcodeProgram.appendLine("(generated " + getTimestamp() + ")"); gcodeProgram.appendLine("G21"); gcodeProgram.appendLine("G90"); generateGcodeCore(gcodeProgram); if (gcodeGenerationError) { clear(); } else { gcodeProgram.appendLine( "G0 Z" + String.format( IConstant.FORMAT_COORDINATE, getDoublePreference(IPreferenceKey.Z_CLEARANCE))); gcodeProgram.appendLine("M5"); gcodeProgram.parse(); Text gcodeText = (Text) context.get(IConstant.MACRO_TEXT_ID); if (gcodeText != null) toolbox.gcodeToText(gcodeText, gcodeProgram); } eventBroker.send(IEvent.GCODE_MACRO_GENERATED, null); eventBroker.send(IEvent.REDRAW, null); }
/** * Simplified copy of IDEAplication processing that does not offer to choose a workspace location. */ private boolean checkInstanceLocation( Location instanceLocation, Shell shell, IEclipseContext context) { // Eclipse has been run with -data @none or -data @noDefault options so // we don't need to validate the location if (instanceLocation == null && Boolean.FALSE.equals(context.get(IWorkbench.PERSIST_STATE))) { return true; } if (instanceLocation == null) { MessageDialog.openError( shell, WorkbenchSWTMessages.IDEApplication_workspaceMandatoryTitle, WorkbenchSWTMessages.IDEApplication_workspaceMandatoryMessage); return false; } // -data "/valid/path", workspace already set if (instanceLocation.isSet()) { // make sure the meta data version is compatible (or the user // has // chosen to overwrite it). if (!checkValidWorkspace(shell, instanceLocation.getURL())) { return false; } // at this point its valid, so try to lock it and update the // metadata version information if successful try { if (instanceLocation.lock()) { writeWorkspaceVersion(); return true; } // we failed to create the directory. // Two possibilities: // 1. directory is already in use // 2. directory could not be created File workspaceDirectory = new File(instanceLocation.getURL().getFile()); if (workspaceDirectory.exists()) { MessageDialog.openError( shell, WorkbenchSWTMessages.IDEApplication_workspaceCannotLockTitle, WorkbenchSWTMessages.IDEApplication_workspaceCannotLockMessage); } else { MessageDialog.openError( shell, WorkbenchSWTMessages.IDEApplication_workspaceCannotBeSetTitle, WorkbenchSWTMessages.IDEApplication_workspaceCannotBeSetMessage); } } catch (IOException e) { Logger logger = new WorkbenchLogger(PLUGIN_ID); logger.error(e); MessageDialog.openError(shell, WorkbenchSWTMessages.InternalError, e.getMessage()); } return false; } return false; }
private void fillArgs(Object[] actualArgs, String[] keys, boolean[] active) { for (int i = 0; i < keys.length; i++) { if (keys[i] == null) continue; IEclipseContext targetContext = (active[i]) ? context.getActiveLeaf() : context; if (ECLIPSE_CONTEXT_NAME.equals(keys[i])) actualArgs[i] = targetContext; else if (targetContext.containsKey(keys[i])) actualArgs[i] = targetContext.get(keys[i]); } }
private ImageDescriptor getImageDescriptor(MUILabel element) { IEclipseContext localContext = context; String iconURI = element.getIconURI(); if (iconURI != null && iconURI.length() > 0) { ISWTResourceUtilities resUtils = (ISWTResourceUtilities) localContext.get(IResourceUtilities.class.getName()); return resUtils.imageDescriptorFromURI(URI.createURI(iconURI)); } return null; }
public void testCreateWindow() { final MWindow window = BasicFactoryImpl.eINSTANCE.createWindow(); window.setLabel("MyWindow"); wb = new E4Workbench(window, appContext); Widget topWidget = (Widget) window.getWidget(); assertTrue(topWidget instanceof Shell); assertEquals("MyWindow", ((Shell) topWidget).getText()); assertEquals(topWidget, appContext.get(IServiceConstants.ACTIVE_SHELL)); }
/** * Check if this Handler is enabled on the selection. Only one Teststrucutre is valid as a * selection. * * @param context Eclipse Context to retrive the Viewer * @return true if only one element is selected. */ @CanExecute public boolean canExecute(IEclipseContext context) { TestExplorer explorer = (TestExplorer) context.get(TestEditorConstants.TEST_EXPLORER_VIEW); TestStructure selected = (TestStructure) explorer.getSelection().getFirstElement(); renameHandler = getAbstactRenameTestStructureHandler(context, selected); if (renameHandler != null) { return renameHandler.canExecute(context); } return false; }
private void simulateMenuSelection(MMenuItem item) { // FIXME: pity this code isn't available through the MMenuItem instance // somehow IEclipseContext lclContext = getContext(item); if (item instanceof MDirectMenuItem) { MDirectMenuItem dmi = (MDirectMenuItem) item; if (dmi.getObject() == null) { IContributionFactory cf = (IContributionFactory) lclContext.get(IContributionFactory.class.getName()); dmi.setObject(cf.create(dmi.getContributionURI(), lclContext)); } lclContext.set(MItem.class.getName(), item); ContextInjectionFactory.invoke(dmi.getObject(), Execute.class, lclContext); lclContext.remove(MItem.class.getName()); } else if (item instanceof MHandledMenuItem) { MHandledMenuItem hmi = (MHandledMenuItem) item; EHandlerService service = (EHandlerService) lclContext.get(EHandlerService.class.getName()); ParameterizedCommand cmd = hmi.getWbCommand(); if (cmd == null) { cmd = HandledMenuItemRenderer.generateParameterizedCommand(hmi, lclContext); } lclContext.set(MItem.class.getName(), item); service.executeHandler(cmd); lclContext.remove(MItem.class.getName()); } else { statusReporter .get() .report( new Status( IStatus.WARNING, CocoaUIProcessor.FRAGMENT_ID, "Unhandled menu type: " + item.getClass() + ": " + item), //$NON-NLS-1$ //$NON-NLS-2$ $NON-NLS-2$ StatusReporter.LOG); } }
@Override public boolean update(IEclipseContext eventsContext, int eventType, Object[] extraArguments) { if (eventType == ContextChangeEvent.INITIAL) { // needs to be done inside runnable to establish dependencies for (int i = 0; i < keys.length; i++) { if (keys[i] == null) continue; IEclipseContext targetContext = (active[i]) ? context.getActiveLeaf() : context; if (ECLIPSE_CONTEXT_NAME.equals(keys[i])) { result[i] = targetContext; IEclipseContext parent = targetContext.getParent(); // creates pseudo-link if (parent == null) targetContext.get(ECLIPSE_CONTEXT_NAME); // pseudo-link in case there is no parent } else if (targetContext.containsKey(keys[i])) result[i] = targetContext.get(keys[i]); } return true; } if (eventType == ContextChangeEvent.DISPOSE) { if (eventsContext == context) { ContextObjectSupplier originatingSupplier = eventsContext.getLocal(ContextObjectSupplier.class); requestor.disposed(originatingSupplier); return false; } } else if (eventType == ContextChangeEvent.UNINJECTED) { if (eventsContext == context) { ContextObjectSupplier originatingSupplier = eventsContext.getLocal(ContextObjectSupplier.class); return requestor.uninject(extraArguments[0], originatingSupplier); } } else { if (!requestor.isValid()) return false; // remove this listener requestor.resolveArguments(false); requestor.execute(); } return true; }
@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 static ParameterizedCommand generateParameterizedCommand( final MHandledItem item, final IEclipseContext lclContext) { ECommandService cmdService = (ECommandService) lclContext.get(ECommandService.class.getName()); Map<String, Object> parameters = null; List<MParameter> modelParms = item.getParameters(); if (modelParms != null && !modelParms.isEmpty()) { parameters = new HashMap<String, Object>(); for (MParameter mParm : modelParms) { parameters.put(mParm.getName(), mParm.getValue()); } } ParameterizedCommand cmd = cmdService.createCommand(item.getCommand().getElementId(), parameters); item.setWbCommand(cmd); return cmd; }
@Override protected void createFieldEditors() { // TODO Auto-generated method stub Composite container = (Composite) this.getControl(); addField( new BooleanFieldEditor( BTSCorpusConstants.PREF_LEMMA_NAVIGATOR_SORTBYKEY, "Lemma Navigator sort by sort key", BooleanFieldEditor.DEFAULT, getFieldEditorParent())); context = StaticAccessController.getContext(); configurationController = context.get(PassportConfigurationController.class); Label lblVisibility = new Label(container, SWT.NONE); lblVisibility.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); lblVisibility.setText("Default Visibility"); visibilityCMB_Admin = new Combo(container, SWT.READ_ONLY); visibilityCMB_Admin.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false, 3, 1)); visibility_viewer = new ComboViewer(visibilityCMB_Admin); AdapterFactoryLabelProvider labelProvider_vis = new AdapterFactoryLabelProvider(factory); AdapterFactoryContentProvider contentProvider_vis = new AdapterFactoryContentProvider(factory); visibility_viewer.setContentProvider(contentProvider_vis); visibility_viewer.setLabelProvider(labelProvider_vis); visibility_viewer.setInput( configurationController.getVisibilityConfigItemProcessedClones(null)); Label lblRevisionState = new Label(container, SWT.NONE); lblRevisionState.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); lblRevisionState.setText("Default Review State"); reviewCMB_Admin = new Combo(container, SWT.READ_ONLY); reviewCMB_Admin.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false, 3, 1)); reviewState_viewer = new ComboViewer(reviewCMB_Admin); AdapterFactoryLabelProvider labelProvider_rev = new AdapterFactoryLabelProvider(factory); AdapterFactoryContentProvider contentProvider_rev = new AdapterFactoryContentProvider(factory); reviewState_viewer.setContentProvider(contentProvider_rev); reviewState_viewer.setLabelProvider(labelProvider_rev); reviewState_viewer.setInput( configurationController.getReviewStateConfigItemProcessedClones(null)); init(); container.layout(); }
private IGcodeProgram getSelectedProgram(String text) { LOG.debug("getSelectedProgram: text=" + text); Collection<MPart> parts = partService.getParts(); for (MPart part : parts) { if (isOverlayPart(part)) { if (text.equals(part.getLabel())) { final IEclipseContext context = part.getContext(); if (context != null) return context.get(IGcodeProgram.class); } } } // if part is not instantiated and therefore gcode program is not loaded, then we are here return null; }
private MApplication loadApplicationModel( IApplicationContext appContext, IEclipseContext eclipseContext) { MApplication theApp = null; Location instanceLocation = WorkbenchSWTActivator.getDefault().getInstanceLocation(); URI applicationModelURI = determineApplicationModelURI(appContext); eclipseContext.set(E4Workbench.INITIAL_WORKBENCH_MODEL_URI, applicationModelURI); // Save and restore Boolean saveAndRestore = getArgValue(IWorkbench.PERSIST_STATE, appContext, false) .map(value -> Boolean.parseBoolean(value)) .orElse(Boolean.TRUE); eclipseContext.set(IWorkbench.PERSIST_STATE, saveAndRestore); // when -data @none or -data @noDefault options if (instanceLocation != null && instanceLocation.getURL() != null) { eclipseContext.set(E4Workbench.INSTANCE_LOCATION, instanceLocation); } else { eclipseContext.set(IWorkbench.PERSIST_STATE, false); } // Persisted state Boolean clearPersistedState = getArgValue(IWorkbench.CLEAR_PERSISTED_STATE, appContext, true) .map(value -> Boolean.parseBoolean(value)) .orElse(Boolean.FALSE); eclipseContext.set(IWorkbench.CLEAR_PERSISTED_STATE, clearPersistedState); String resourceHandler = getArgValue(IWorkbench.MODEL_RESOURCE_HANDLER, appContext, false) .orElse("bundleclass://org.eclipse.e4.ui.workbench/" + ResourceHandler.class.getName()); IContributionFactory factory = eclipseContext.get(IContributionFactory.class); handler = (IModelResourceHandler) factory.create(resourceHandler, eclipseContext); eclipseContext.set(IModelResourceHandler.class, handler); Resource resource = handler.loadMostRecentModel(); theApp = (MApplication) resource.getContents().get(0); return theApp; }
private void setEnabled(MHandledMenuItem itemModel, MenuItem newItem) { ParameterizedCommand cmd = itemModel.getWbCommand(); if (cmd == null) { return; } final IEclipseContext lclContext = getContext(itemModel); EHandlerService service = lclContext.get(EHandlerService.class); final IEclipseContext staticContext = EclipseContextFactory.create(HMI_STATIC_CONTEXT); ContributionsAnalyzer.populateModelInterfaces( itemModel, staticContext, itemModel.getClass().getInterfaces()); try { itemModel.setEnabled(service.canExecute(cmd, staticContext)); } finally { staticContext.dispose(); } newItem.setEnabled(itemModel.isEnabled()); }
@Test public void testU() throws Exception { IEclipseContext parentContext = EclipseContextFactory.create(); parentContext.set("aString", ""); parentContext.set(MyTest.class.getName(), new TestFunction()); IEclipseContext context = parentContext.createChild(); MyTest test = (MyTest) context.get(MyTest.class.getName()); assertEquals(0, test.getCount()); context.dispose(); assertEquals("Context disposed, @PreDestroy should've been called", 1, test.getCount()); parentContext.dispose(); assertEquals( "Parent context disposed, @PreDestroy should not have been called again", 1, test.getCount()); }
/** * Initialize a part renderer from the extension point. * * @param context the context for the part factories */ @PostConstruct void initialize(IEclipseContext context) { this.appContext = context; // initialize the correct key-binding display formatter KeyFormatterFactory.setDefault(SWTKeySupport.getKeyFormatterForPlatform()); // Add the renderer to the context context.set(IPresentationEngine.class.getName(), this); IRendererFactory factory = null; IContributionFactory contribFactory = context.get(IContributionFactory.class); try { factory = (IRendererFactory) contribFactory.create(factoryUrl, context); } catch (Exception e) { logger.warn(e, "Could not create rendering factory"); } // Try to load the default one if (factory == null) { try { factory = (IRendererFactory) contribFactory.create(defaultFactoryUrl, context); } catch (Exception e) { logger.error(e, "Could not create default rendering factory"); } } if (factory == null) { throw new IllegalStateException("Could not create any rendering factory. Aborting ..."); } curFactory = factory; context.set(IRendererFactory.class, curFactory); // Hook up the widget life-cycle subscriber if (eventBroker != null) { eventBroker.subscribe(UIEvents.UIElement.TOPIC_TOBERENDERED, toBeRenderedHandler); eventBroker.subscribe(UIEvents.UIElement.TOPIC_VISIBLE, visibilityHandler); eventBroker.subscribe(UIEvents.ElementContainer.TOPIC_CHILDREN, childrenHandler); eventBroker.subscribe(UIEvents.Window.TOPIC_WINDOWS, windowsHandler); eventBroker.subscribe(UIEvents.Perspective.TOPIC_WINDOWS, windowsHandler); eventBroker.subscribe(UIEvents.TrimmedWindow.TOPIC_TRIMBARS, trimHandler); } }
private void handleNullRefPlaceHolders(MUIElement element, MWindow refWin, boolean resolve) { // use appContext as MApplication.getContext() is null during the processing of // the model processor classes EPlaceholderResolver resolver = appContext.get(EPlaceholderResolver.class); // Re-resolve any placeholder references List<MPlaceholder> phList = findElements(element, null, MPlaceholder.class, null); List<MPlaceholder> nullRefList = new ArrayList<>(); for (MPlaceholder ph : phList) { if (resolve) { resolver.resolvePlaceholderRef(ph, refWin); } if (ph.getRef() == null) { nullRefList.add(ph); } } for (MPlaceholder ph : nullRefList) { replacePlaceholder(ph); } return; }
// TODO This should go into a different bundle public static IEclipseContext createDefaultHeadlessContext() { IEclipseContext serviceContext = E4Workbench.getServiceContext(); IExtensionRegistry registry = RegistryFactory.getRegistry(); ExceptionHandler exceptionHandler = new ExceptionHandler(); ReflectionContributionFactory contributionFactory = new ReflectionContributionFactory(registry); serviceContext.set(IContributionFactory.class, contributionFactory); serviceContext.set(IExceptionHandler.class, exceptionHandler); serviceContext.set(IExtensionRegistry.class, registry); serviceContext.set( Adapter.class, ContextInjectionFactory.make(EclipseAdapter.class, serviceContext)); // No default log provider available if (serviceContext.get(ILoggerProvider.class) == null) { serviceContext.set( ILoggerProvider.class, ContextInjectionFactory.make(DefaultLoggerProvider.class, serviceContext)); } return serviceContext; }
public void testContextChildren() { final MWindow window = createWindowWithOneView(); wb = new E4Workbench(window, appContext); Widget topWidget = (Widget) window.getWidget(); assertTrue(topWidget instanceof Shell); Shell shell = (Shell) topWidget; assertEquals("MyWindow", shell.getText()); // should get the window context IEclipseContext child = appContext.getActiveChild(); assertNotNull(child); assertEquals(window.getContext(), child); MPart modelPart = getContributedPart(window); assertNotNull(modelPart); assertEquals(window, modelPart.getParent().getParent().getParent()); // "activate" the part, same as (in theory) an // SWT.Activate event. AbstractPartRenderer factory = (AbstractPartRenderer) modelPart.getRenderer(); factory.activate(modelPart); IEclipseContext next = child.getActiveChild(); while (next != null) { child = next; next = child.getActiveChild(); if (next == child) { fail("Cycle detected in part context"); break; } } assertFalse(window.getContext() == child); MPart contextPart = (MPart) child.get(MPart.class.getName()); assertNotNull(contextPart); assertEquals(window, contextPart.getParent().getParent().getParent()); }
protected void setItemText(MMenuItem model, MenuItem item) { String text = model.getLocalizedLabel(); if (model instanceof MHandledItem) { MHandledItem handledItem = (MHandledItem) model; IEclipseContext context = getContext(model); EBindingService bs = (EBindingService) context.get(EBindingService.class.getName()); ParameterizedCommand cmd = handledItem.getWbCommand(); if (cmd != null && (text == null || text.length() == 0)) { try { text = cmd.getName(); } catch (NotDefinedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } TriggerSequence sequence = bs.getBestSequenceFor(handledItem.getWbCommand()); if (sequence != null) { text = text + '\t' + sequence.format(); } item.setText(text == null ? handledItem.getCommand().getElementId() : text); } else { super.setItemText(model, item); } }
@Override protected void setUp() throws Exception { super.setUp(); parentContext = EclipseContextFactory.getServiceContext(CoreTestsActivator.getDefault().getBundleContext()); context = parentContext.createChild(getName()); // add some values to the contexts for (int i = 0; i < 100; i++) { context.set("Value-" + i, Integer.valueOf(i)); } // do some additional service lookups on non-existent keys for (int i = 0; i < 1000; i++) { context.get("NonExistentValue-" + i); } // lookup some OSGi services context.get(DebugOptions.class.getName()); context.get(IAdapterManager.class.getName()); context.get(IExtensionRegistry.class.getName()); context.get(IPreferencesService.class.getName()); context.get(Location.class.getName()); }
private void warn(String message) { Logger logger = appContext.get(Logger.class); if (logger != null) { logger.warn(message); } }
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); }