Search in sources :

Example 1 with ServiceLocator

use of org.eclipse.ui.internal.services.ServiceLocator in project eclipse.platform.ui by eclipse-platform.

the class WorkbenchWindow method setup.

@PostConstruct
public void setup() {
    try {
        // if workbench window is opened as a result of command execution,
        // the context in which the new workbench window's commands are
        // initialized has to to match the workbench context
        final IEclipseContext windowContext = model.getContext();
        HandlerServiceImpl.push(windowContext.getParent(), null);
        // update the preference store.
        if (getModel().getPersistedState().containsKey(IPreferenceConstants.COOLBAR_VISIBLE)) {
            this.coolBarVisible = Boolean.parseBoolean(getModel().getPersistedState().get(IPreferenceConstants.COOLBAR_VISIBLE));
        } else {
            this.coolBarVisible = PrefUtil.getInternalPreferenceStore().getBoolean(IPreferenceConstants.COOLBAR_VISIBLE);
            getModel().getPersistedState().put(IPreferenceConstants.COOLBAR_VISIBLE, Boolean.toString(this.coolBarVisible));
        }
        if (getModel().getPersistedState().containsKey(IPreferenceConstants.PERSPECTIVEBAR_VISIBLE)) {
            this.perspectiveBarVisible = Boolean.parseBoolean(getModel().getPersistedState().get(IPreferenceConstants.PERSPECTIVEBAR_VISIBLE));
        } else {
            this.perspectiveBarVisible = PrefUtil.getInternalPreferenceStore().getBoolean(IPreferenceConstants.PERSPECTIVEBAR_VISIBLE);
            getModel().getPersistedState().put(IPreferenceConstants.PERSPECTIVEBAR_VISIBLE, Boolean.toString(this.perspectiveBarVisible));
        }
        IServiceLocatorCreator slc = workbench.getService(IServiceLocatorCreator.class);
        this.serviceLocator = (ServiceLocator) slc.createServiceLocator(workbench, null, () -> {
            final Shell shell = getShell();
            if (shell != null && !shell.isDisposed()) {
                close();
            }
        }, windowContext);
        windowContext.set(IExtensionTracker.class.getName(), new ContextFunction() {

            @Override
            public Object compute(IEclipseContext context, String contextKey) {
                if (tracker == null) {
                    tracker = new UIExtensionTracker(getWorkbench().getDisplay());
                }
                return tracker;
            }
        });
        windowContext.set(IWindowCloseHandler.class.getName(), (IWindowCloseHandler) window -> getWindowAdvisor().preWindowShellClose() && WorkbenchWindow.this.close());
        final ISaveHandler defaultSaveHandler = windowContext.get(ISaveHandler.class);
        final PartServiceSaveHandler localSaveHandler = new WWinPartServiceSaveHandler() {

            @Override
            public Save promptToSave(MPart dirtyPart) {
                Object object = dirtyPart.getObject();
                if (object instanceof CompatibilityPart) {
                    IWorkbenchPart part = ((CompatibilityPart) object).getPart();
                    ISaveablePart saveable = SaveableHelper.getSaveable(part);
                    if (saveable != null) {
                        if (!saveable.isSaveOnCloseNeeded()) {
                            return Save.NO;
                        }
                        return SaveableHelper.savePart(saveable, part, WorkbenchWindow.this, true) ? Save.NO : Save.CANCEL;
                    }
                }
                return defaultSaveHandler.promptToSave(dirtyPart);
            }

            @Override
            public Save[] promptToSave(Collection<MPart> dirtyParts) {
                LabelProvider labelProvider = new LabelProvider() {

                    @Override
                    public String getText(Object element) {
                        return ((MPart) element).getLocalizedLabel();
                    }
                };
                List<MPart> parts = new ArrayList<>(dirtyParts);
                ListSelectionDialog dialog = new ListSelectionDialog(getShell(), parts, ArrayContentProvider.getInstance(), labelProvider, WorkbenchMessages.EditorManager_saveResourcesMessage);
                dialog.setInitialSelections(parts.toArray());
                dialog.setTitle(WorkbenchMessages.EditorManager_saveResourcesTitle);
                if (dialog.open() == IDialogConstants.CANCEL_ID) {
                    return new Save[] { Save.CANCEL };
                }
                Object[] toSave = dialog.getResult();
                Save[] retSaves = new Save[parts.size()];
                Arrays.fill(retSaves, Save.NO);
                for (int i = 0; i < retSaves.length; i++) {
                    MPart part = parts.get(i);
                    for (Object o : toSave) {
                        if (o == part) {
                            retSaves[i] = Save.YES;
                            break;
                        }
                    }
                }
                return retSaves;
            }

            @Override
            public boolean save(MPart dirtyPart, boolean confirm) {
                Object object = dirtyPart.getObject();
                if (object instanceof CompatibilityPart) {
                    IWorkbenchPart workbenchPart = ((CompatibilityPart) object).getPart();
                    if (SaveableHelper.isSaveable(workbenchPart)) {
                        SaveablesList saveablesList = (SaveablesList) PlatformUI.getWorkbench().getService(ISaveablesLifecycleListener.class);
                        Object saveResult = saveablesList.preCloseParts(Collections.singletonList(workbenchPart), true, WorkbenchWindow.this);
                        return saveResult != null;
                    }
                } else if (isSaveOnCloseNotNeededSplitEditorPart(dirtyPart)) {
                    return true;
                }
                return super.save(dirtyPart, confirm);
            }

            private boolean saveParts(ArrayList<MPart> dirtyParts, Save[] decisions) {
                if (decisions == null || decisions.length == 0) {
                    super.saveParts(dirtyParts, true);
                }
                if (dirtyParts.size() != decisions.length) {
                    for (Save decision : decisions) {
                        if (decision == Save.CANCEL) {
                            return false;
                        }
                    }
                }
                List<MPart> dirtyPartsList = Collections.unmodifiableList(new ArrayList<>(dirtyParts));
                for (Save decision : decisions) {
                    if (decision == Save.CANCEL) {
                        return false;
                    }
                }
                for (int i = 0; i < decisions.length; i++) {
                    if (decisions[i] == Save.YES) {
                        if (!save(dirtyPartsList.get(i), false)) {
                            return false;
                        }
                    }
                }
                return true;
            }

            private boolean saveMixedParts(ArrayList<MPart> nonCompParts, ArrayList<IWorkbenchPart> compParts, boolean confirm, boolean addNonPartSources) {
                SaveablesList saveablesList = (SaveablesList) PlatformUI.getWorkbench().getService(ISaveablesLifecycleListener.class);
                if (!confirm) {
                    boolean saved = super.saveParts(nonCompParts, confirm);
                    Object saveResult = saveablesList.preCloseParts(compParts, true, WorkbenchWindow.this);
                    return ((saveResult != null) && saved);
                }
                LabelProvider labelProvider = new LabelProvider() {

                    WorkbenchPartLabelProvider workbenchLabelProvider = new WorkbenchPartLabelProvider();

                    @Override
                    public String getText(Object element) {
                        if (element instanceof Saveable) {
                            return workbenchLabelProvider.getText(element);
                        }
                        return ((MPart) element).getLocalizedLabel();
                    }
                };
                ArrayList<Object> listParts = new ArrayList<>();
                Map<IWorkbenchPart, List<Saveable>> saveableMap = saveablesList.getSaveables(compParts);
                listParts.addAll(nonCompParts);
                LinkedHashSet<Saveable> saveablesSet = new LinkedHashSet<>();
                for (IWorkbenchPart workbenchPart : compParts) {
                    List<Saveable> list = saveableMap.get(workbenchPart);
                    if (list != null) {
                        saveablesSet.addAll(list);
                    }
                }
                if (addNonPartSources) {
                    for (ISaveablesSource nonPartSource : saveablesList.getNonPartSources()) {
                        Saveable[] saveables = nonPartSource.getSaveables();
                        for (Saveable saveable : saveables) {
                            if (saveable.isDirty()) {
                                saveablesSet.add(saveable);
                            }
                        }
                    }
                }
                listParts.addAll(saveablesSet);
                ListSelectionDialog dialog = new ListSelectionDialog(getShell(), listParts, ArrayContentProvider.getInstance(), labelProvider, WorkbenchMessages.EditorManager_saveResourcesMessage);
                dialog.setInitialSelections(listParts.toArray());
                dialog.setTitle(WorkbenchMessages.EditorManager_saveResourcesTitle);
                if (dialog.open() == IDialogConstants.CANCEL_ID) {
                    return false;
                }
                Object[] toSave = dialog.getResult();
                Save[] nonCompatSaves = new Save[nonCompParts.size()];
                Save[] compatSaves = new Save[saveablesSet.size()];
                Arrays.fill(nonCompatSaves, Save.NO);
                Arrays.fill(compatSaves, Save.NO);
                for (int i = 0; i < nonCompatSaves.length; i++) {
                    MPart part = nonCompParts.get(i);
                    for (Object o : toSave) {
                        if (o == part) {
                            nonCompatSaves[i] = Save.YES;
                            break;
                        }
                    }
                }
                Map<Saveable, Save> saveOptionMap = new HashMap<>();
                for (Saveable saveable : saveablesSet) {
                    boolean found = false;
                    for (Object o : toSave) {
                        if (o == saveable) {
                            saveOptionMap.put(saveable, Save.YES);
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        saveOptionMap.put(saveable, Save.NO);
                    }
                }
                boolean saved = saveParts(nonCompParts, nonCompatSaves);
                if (!saved) {
                    return saved;
                }
                Object saveResult = saveablesList.preCloseParts(compParts, false, true, WorkbenchWindow.this, saveOptionMap);
                return ((saveResult != null) && saved);
            }

            private void removeSaveOnCloseNotNeededParts(List<IWorkbenchPart> parts) {
                for (Iterator<IWorkbenchPart> it = parts.iterator(); it.hasNext(); ) {
                    IWorkbenchPart part = it.next();
                    ISaveablePart saveable = SaveableHelper.getSaveable(part);
                    if (saveable == null || !saveable.isSaveOnCloseNeeded()) {
                        it.remove();
                    }
                }
            }

            private void removeSaveOnCloseNotNeededSplitEditorParts(List<MPart> parts) {
                for (Iterator<MPart> it = parts.iterator(); it.hasNext(); ) {
                    MPart part = it.next();
                    if (isSaveOnCloseNotNeededSplitEditorPart(part)) {
                        it.remove();
                    }
                }
            }

            private boolean isSaveOnCloseNotNeededSplitEditorPart(MPart part) {
                boolean notNeeded = false;
                if (part instanceof MCompositePart && SplitHost.SPLIT_HOST_CONTRIBUTOR_URI.equals(part.getContributionURI())) {
                    MCompositePart compPart = (MCompositePart) part;
                    List<MPart> elements = modelService.findElements(compPart, null, MPart.class);
                    if (elements != null && elements.size() > 1) {
                        elements.remove(0);
                        for (MPart mpart : elements) {
                            Object object = mpart.getObject();
                            if (object instanceof CompatibilityPart) {
                                IWorkbenchPart workbenchPart = ((CompatibilityPart) object).getPart();
                                if (!SaveableHelper.isSaveable(workbenchPart)) {
                                    notNeeded = true;
                                } else {
                                    ISaveablePart saveable = SaveableHelper.getSaveable(workbenchPart);
                                    if (saveable == null || !saveable.isSaveOnCloseNeeded()) {
                                        notNeeded = true;
                                    } else {
                                        notNeeded = false;
                                        break;
                                    }
                                }
                            } else {
                                notNeeded = false;
                                break;
                            }
                        }
                    }
                }
                return notNeeded;
            }

            @Override
            public boolean saveParts(Collection<MPart> dirtyParts, boolean confirm, boolean closing, boolean addNonPartSources) {
                ArrayList<IWorkbenchPart> saveableParts = new ArrayList<>();
                ArrayList<MPart> nonCompatibilityParts = new ArrayList<>();
                for (MPart part : dirtyParts) {
                    Object object = part.getObject();
                    if (object instanceof CompatibilityPart) {
                        IWorkbenchPart workbenchPart = ((CompatibilityPart) object).getPart();
                        if (SaveableHelper.isSaveable(workbenchPart)) {
                            saveableParts.add(workbenchPart);
                        }
                    } else {
                        nonCompatibilityParts.add(part);
                    }
                }
                if (!saveableParts.isEmpty() && closing) {
                    removeSaveOnCloseNotNeededParts(saveableParts);
                }
                if (!nonCompatibilityParts.isEmpty() && closing) {
                    removeSaveOnCloseNotNeededSplitEditorParts(nonCompatibilityParts);
                }
                if (saveableParts.isEmpty()) {
                    if (nonCompatibilityParts.isEmpty()) {
                        // nothing to save
                        return true;
                    }
                    return super.saveParts(nonCompatibilityParts, confirm);
                } else if (!nonCompatibilityParts.isEmpty()) {
                    return saveMixedParts(nonCompatibilityParts, saveableParts, confirm, addNonPartSources);
                }
                SaveablesList saveablesList = (SaveablesList) PlatformUI.getWorkbench().getService(ISaveablesLifecycleListener.class);
                Object saveResult = saveablesList.preCloseParts(saveableParts, addNonPartSources, true, WorkbenchWindow.this, WorkbenchWindow.this);
                return (saveResult != null);
            }

            @Override
            public boolean saveParts(Collection<MPart> dirtyParts, boolean confirm) {
                return saveParts(dirtyParts, confirm, false, false);
            }
        };
        localSaveHandler.logger = logger;
        windowContext.set(ISaveHandler.class, localSaveHandler);
        windowContext.set(IWorkbenchWindow.class.getName(), this);
        windowContext.set(IPageService.class, this);
        windowContext.set(IPartService.class, partService);
        windowContext.set(ISources.ACTIVE_WORKBENCH_WINDOW_NAME, this);
        windowContext.set(ISources.ACTIVE_WORKBENCH_WINDOW_SHELL_NAME, getShell());
        EContextService cs = windowContext.get(EContextService.class);
        cs.activateContext(IContextService.CONTEXT_ID_WINDOW);
        cs.getActiveContextIds();
        initializeDefaultServices();
        /*
			 * Remove the second QuickAccess control if an older workspace is opened.
			 *
			 * An older workspace will create an ApplicationModel which already contains the
			 * QuickAccess elements, from the old "popuolateTopTrimContribution()" method.
			 * The new implementation of this method doesn't add the QuickAccess elements
			 * anymore but an old workbench.xmi still has these entries in it and so they
			 * need to be removed.
			 */
        cleanLegacyQuickAccessContribution();
        // register with the tracker
        fireWindowOpening();
        configureShell(getShell(), windowContext);
        try {
            page = new WorkbenchPage(this, input);
        } catch (WorkbenchException e) {
            WorkbenchPlugin.log(e);
        }
        menuOverride = new MenuOverrides(page);
        toolbarOverride = new ToolbarOverrides(page);
        ContextInjectionFactory.inject(page, model.getContext());
        windowContext.set(IWorkbenchPage.class, page);
        menuManager.setOverrides(menuOverride);
        ((CoolBarToTrimManager) getCoolBarManager2()).setOverrides(toolbarOverride);
        // Fill the action bars
        fillActionBars(FILL_ALL_ACTION_BARS);
        firePageOpened();
        populateTopTrimContributions();
        populateBottomTrimContributions();
        // Trim gets populated during rendering (?) so make sure we have al/
        // sides. See bug 383269 for details
        modelService.getTrim(model, SideValue.LEFT);
        modelService.getTrim(model, SideValue.RIGHT);
        // move the QuickAccess ToolControl to the correct position (only if
        // it exists)
        positionQuickAccess();
        Shell shell = (Shell) model.getWidget();
        if (model.getMainMenu() == null) {
            mainMenu = modelService.createModelElement(MMenu.class);
            mainMenu.setElementId(IWorkbenchConstants.MAIN_MENU_ID);
            mainMenu.getPersistedState().put(org.eclipse.e4.ui.workbench.IWorkbench.PERSIST_STATE, Boolean.FALSE.toString());
            renderer = (MenuManagerRenderer) rendererFactory.getRenderer(mainMenu, null);
            renderer.linkModelToManager(mainMenu, menuManager);
            renderer.reconcileManagerToModel(menuManager, mainMenu);
            model.setMainMenu(mainMenu);
            final Menu menu = (Menu) engine.createGui(mainMenu, model.getWidget(), model.getContext());
            shell.setMenuBar(menu);
            menuUpdater = () -> {
                try {
                    if (model.getMainMenu() == null || model.getWidget() == null || menu.isDisposed() || mainMenu.getWidget() == null) {
                        return;
                    }
                    MenuManagerRendererFilter.updateElementVisibility(mainMenu, renderer, menuManager, windowContext.getActiveLeaf(), 1, false);
                    menuManager.update(true);
                } finally {
                    canUpdateMenus = true;
                }
            };
            RunAndTrack menuChangeManager = new RunAndTrack() {

                @Override
                public boolean changed(IEclipseContext context) {
                    ExpressionInfo info = new ExpressionInfo();
                    IEclipseContext leafContext = windowContext.getActiveLeaf();
                    MenuManagerRendererFilter.collectInfo(info, mainMenu, renderer, leafContext, true);
                    // if one of these variables change, re-run the RAT
                    for (String name : info.getAccessedVariableNames()) {
                        leafContext.get(name);
                    }
                    if (canUpdateMenus && workbench.getDisplay() != null) {
                        canUpdateMenus = false;
                        workbench.getDisplay().asyncExec(menuUpdater);
                    }
                    return manageChanges;
                }
            };
            windowContext.runAndTrack(menuChangeManager);
        }
        eventBroker.subscribe(UIEvents.UIElement.TOPIC_WIDGET, windowWidgetHandler);
        boolean newWindow = setupPerspectiveStack(windowContext);
        partService.setPage(page);
        page.setPerspective(perspective);
        firePageActivated();
        if (newWindow) {
            page.fireInitialPartVisibilityEvents();
        } else {
            page.updatePerspectiveActionSets();
        }
        updateActionSets();
        IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore();
        boolean enableAnimations = preferenceStore.getBoolean(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS);
        preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, false);
        // Hack!! don't show the intro if there's more than one open
        // perspective
        List<MPerspective> persps = modelService.findElements(model, null, MPerspective.class, null);
        if (persps.size() > 1) {
            PrefUtil.getAPIPreferenceStore().setValue(IWorkbenchPreferenceConstants.SHOW_INTRO, false);
            PrefUtil.saveAPIPrefs();
        }
        if (Boolean.parseBoolean(getModel().getPersistedState().get(PERSISTED_STATE_RESTORED))) {
            SafeRunnable.run(new SafeRunnable() {

                @Override
                public void run() throws Exception {
                    getWindowAdvisor().postWindowRestore();
                }
            });
        } else {
            getModel().getPersistedState().put(PERSISTED_STATE_RESTORED, Boolean.TRUE.toString());
        }
        getWindowAdvisor().postWindowCreate();
        getWindowAdvisor().openIntro();
        preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, enableAnimations);
        getShell().setData(this);
        trackShellActivation();
        /**
         * When SWT zoom changes for primary monitor, prompt user to restart Eclipse to
         * apply the changes.
         */
        getShell().addListener(SWT.ZoomChanged, event -> {
            if (getShell().getDisplay().getPrimaryMonitor().equals(getShell().getMonitor())) {
                int dialogResponse = MessageDialog.open(MessageDialog.QUESTION, getShell(), WorkbenchMessages.Workbench_zoomChangedTitle, WorkbenchMessages.Workbench_zoomChangedMessage, SWT.NONE, WorkbenchMessages.Workbench_RestartButton, WorkbenchMessages.Workbench_DontRestartButton);
                if (event.doit && dialogResponse == 0) {
                    getWorkbenchImpl().restart(true);
                }
            }
        });
    } finally {
        HandlerServiceImpl.pop();
    }
}
Also used : Arrays(java.util.Arrays) ModeledPageLayout(org.eclipse.ui.internal.e4.compatibility.ModeledPageLayout) UIListenerLogging(org.eclipse.ui.internal.misc.UIListenerLogging) IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) EventHandler(org.osgi.service.event.EventHandler) IDialogConstants(org.eclipse.jface.dialogs.IDialogConstants) IServiceLocatorCreator(org.eclipse.ui.internal.services.IServiceLocatorCreator) Point(org.eclipse.swt.graphics.Point) IUpdateService(org.eclipse.e4.ui.internal.workbench.renderers.swt.IUpdateService) PropertyChangeEvent(org.eclipse.jface.util.PropertyChangeEvent) Map(java.util.Map) HandlerServiceImpl(org.eclipse.e4.core.commands.internal.HandlerServiceImpl) IServiceScopes(org.eclipse.ui.services.IServiceScopes) MCompositePart(org.eclipse.e4.ui.model.application.ui.basic.MCompositePart) IWindowCloseHandler(org.eclipse.e4.ui.workbench.modeling.IWindowCloseHandler) MessageDialog(org.eclipse.jface.dialogs.MessageDialog) MApplication(org.eclipse.e4.ui.model.application.MApplication) ServiceLocator(org.eclipse.ui.internal.services.ServiceLocator) ISaveablePart(org.eclipse.ui.ISaveablePart) EContextService(org.eclipse.e4.ui.services.EContextService) LegacyActionPersistence(org.eclipse.ui.internal.menus.LegacyActionPersistence) IEvaluationService(org.eclipse.ui.services.IEvaluationService) PlatformUI(org.eclipse.ui.PlatformUI) MenuManager(org.eclipse.jface.action.MenuManager) IActionSetDescriptor(org.eclipse.ui.internal.registry.IActionSetDescriptor) Assert(org.eclipse.core.runtime.Assert) Set(java.util.Set) IHandler(org.eclipse.core.commands.IHandler) InvocationTargetException(java.lang.reflect.InvocationTargetException) MTrimElement(org.eclipse.e4.ui.model.application.ui.basic.MTrimElement) GroupMarker(org.eclipse.jface.action.GroupMarker) ExpressionInfo(org.eclipse.core.expressions.ExpressionInfo) WorkbenchPartLabelProvider(org.eclipse.ui.model.WorkbenchPartLabelProvider) Saveable(org.eclipse.ui.Saveable) MTrimmedWindow(org.eclipse.e4.ui.model.application.ui.basic.MTrimmedWindow) TrimBarLayout(org.eclipse.e4.ui.workbench.renderers.swt.TrimBarLayout) SWT(org.eclipse.swt.SWT) SlaveCommandService(org.eclipse.ui.internal.commands.SlaveCommandService) IPageService(org.eclipse.ui.IPageService) MToolControl(org.eclipse.e4.ui.model.application.ui.menu.MToolControl) IActionSetsListener(org.eclipse.ui.internal.menus.IActionSetsListener) MPerspective(org.eclipse.e4.ui.model.application.ui.advanced.MPerspective) IWorkbenchPartReference(org.eclipse.ui.IWorkbenchPartReference) UIEventTopic(org.eclipse.e4.ui.di.UIEventTopic) SelectionService(org.eclipse.ui.internal.e4.compatibility.SelectionService) BusyIndicator(org.eclipse.swt.custom.BusyIndicator) EPartService(org.eclipse.e4.ui.workbench.modeling.EPartService) ICoolBarManager2(org.eclipse.jface.internal.provisional.action.ICoolBarManager2) ICommandService(org.eclipse.ui.commands.ICommandService) ListenerList(org.eclipse.core.runtime.ListenerList) Position(org.eclipse.e4.ui.model.internal.Position) MUIElement(org.eclipse.e4.ui.model.application.ui.MUIElement) SplitHost(org.eclipse.e4.ui.workbench.addons.splitteraddon.SplitHost) ArrayList(java.util.ArrayList) SideValue(org.eclipse.e4.ui.model.application.ui.SideValue) IWorkbenchPart(org.eclipse.ui.IWorkbenchPart) MPerspectiveStack(org.eclipse.e4.ui.model.application.ui.advanced.MPerspectiveStack) IConfigurationElement(org.eclipse.core.runtime.IConfigurationElement) MWindow(org.eclipse.e4.ui.model.application.ui.basic.MWindow) IPropertyChangeListener(org.eclipse.jface.util.IPropertyChangeListener) LinkedHashSet(java.util.LinkedHashSet) IActionCommandMappingService(org.eclipse.ui.internal.handlers.IActionCommandMappingService) LegacyHandlerService(org.eclipse.ui.internal.handlers.LegacyHandlerService) Shell(org.eclipse.swt.widgets.Shell) MMenu(org.eclipse.e4.ui.model.application.ui.menu.MMenu) MenuManagerRenderer(org.eclipse.e4.ui.workbench.renderers.swt.MenuManagerRenderer) ActiveShellExpression(org.eclipse.ui.ActiveShellExpression) EcoreUtil(org.eclipse.emf.ecore.util.EcoreUtil) ISaveablesLifecycleListener(org.eclipse.ui.ISaveablesLifecycleListener) IEvaluationContext(org.eclipse.core.expressions.IEvaluationContext) IPresentationEngine(org.eclipse.e4.ui.workbench.IPresentationEngine) ActionCommandMappingService(org.eclipse.ui.internal.handlers.ActionCommandMappingService) ShellAdapter(org.eclipse.swt.events.ShellAdapter) PrefUtil(org.eclipse.ui.internal.util.PrefUtil) MenuManagerRendererFilter(org.eclipse.e4.ui.workbench.renderers.swt.MenuManagerRendererFilter) EModelService(org.eclipse.e4.ui.workbench.modeling.EModelService) CustomizePerspectiveDialog(org.eclipse.ui.internal.dialogs.cpd.CustomizePerspectiveDialog) IMenuManager(org.eclipse.jface.action.IMenuManager) SubContributionItem(org.eclipse.jface.action.SubContributionItem) IContextService(org.eclipse.ui.contexts.IContextService) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) Platform(org.eclipse.core.runtime.Platform) ModalContext(org.eclipse.jface.operation.ModalContext) IEventBroker(org.eclipse.e4.core.services.events.IEventBroker) StartupRunnable(org.eclipse.ui.internal.StartupThreading.StartupRunnable) Event(org.osgi.service.event.Event) IPartService(org.eclipse.ui.IPartService) CoolBarManager2(org.eclipse.jface.internal.provisional.action.CoolBarManager2) IExtensionTracker(org.eclipse.core.runtime.dynamichelpers.IExtensionTracker) ContextInjectionFactory(org.eclipse.e4.core.contexts.ContextInjectionFactory) UIEvents(org.eclipse.e4.ui.workbench.UIEvents) WorkbenchException(org.eclipse.ui.WorkbenchException) IPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) WorkbenchAdvisor(org.eclipse.ui.application.WorkbenchAdvisor) URIHelper(org.eclipse.e4.ui.internal.workbench.URIHelper) TextProcessor(org.eclipse.osgi.util.TextProcessor) IAction(org.eclipse.jface.action.IAction) IMenuService(org.eclipse.ui.menus.IMenuService) IWorkbenchRegistryConstants(org.eclipse.ui.internal.registry.IWorkbenchRegistryConstants) IToolBarManager(org.eclipse.jface.action.IToolBarManager) ISaveablesSource(org.eclipse.ui.ISaveablesSource) UIExtensionTracker(org.eclipse.ui.internal.registry.UIExtensionTracker) SlaveMenuService(org.eclipse.ui.internal.menus.SlaveMenuService) PreDestroy(javax.annotation.PreDestroy) ActionHandler(org.eclipse.jface.commands.ActionHandler) IExtensionRegistry(org.eclipse.core.runtime.IExtensionRegistry) PositionInfo(org.eclipse.e4.ui.model.internal.PositionInfo) IToolBarManager2(org.eclipse.jface.internal.provisional.action.IToolBarManager2) MMenuElement(org.eclipse.e4.ui.model.application.ui.menu.MMenuElement) IContributionManagerOverrides(org.eclipse.jface.action.IContributionManagerOverrides) IActionBarConfigurer2(org.eclipse.ui.internal.provisional.application.IActionBarConfigurer2) ProgressRegion(org.eclipse.ui.internal.progress.ProgressRegion) ToolBarManager2(org.eclipse.jface.internal.provisional.action.ToolBarManager2) IRendererFactory(org.eclipse.e4.ui.workbench.swt.factories.IRendererFactory) MElementContainer(org.eclipse.e4.ui.model.application.ui.MElementContainer) IAdaptable(org.eclipse.core.runtime.IAdaptable) NLS(org.eclipse.osgi.util.NLS) IBindingService(org.eclipse.ui.keys.IBindingService) Collection(java.util.Collection) EObject(org.eclipse.emf.ecore.EObject) Optional(org.eclipse.e4.core.di.annotations.Optional) Display(org.eclipse.swt.widgets.Display) ContextService(org.eclipse.ui.internal.contexts.ContextService) ArrayContentProvider(org.eclipse.jface.viewers.ArrayContentProvider) IWorkbenchPage(org.eclipse.ui.IWorkbenchPage) IHandlerService(org.eclipse.ui.handlers.IHandlerService) List(java.util.List) CoolBarManager(org.eclipse.jface.action.CoolBarManager) IPerspectiveDescriptor(org.eclipse.ui.IPerspectiveDescriptor) IViewDescriptor(org.eclipse.ui.views.IViewDescriptor) Entry(java.util.Map.Entry) PostConstruct(javax.annotation.PostConstruct) IHandlerActivation(org.eclipse.ui.handlers.IHandlerActivation) WorkbenchWindowAdvisor(org.eclipse.ui.application.WorkbenchWindowAdvisor) CompatibilityPart(org.eclipse.ui.internal.e4.compatibility.CompatibilityPart) SafeRunnable(org.eclipse.jface.util.SafeRunnable) PartServiceSaveHandler(org.eclipse.e4.ui.internal.workbench.PartServiceSaveHandler) ISelectionService(org.eclipse.ui.ISelectionService) ToolBarManagerRenderer(org.eclipse.e4.ui.workbench.renderers.swt.ToolBarManagerRenderer) IPerspectiveRegistry(org.eclipse.ui.IPerspectiveRegistry) EvaluationReference(org.eclipse.ui.internal.services.EvaluationReference) Rectangle(org.eclipse.swt.graphics.Rectangle) HashMap(java.util.HashMap) Logger(org.eclipse.e4.core.services.log.Logger) IWorkbenchLocationService(org.eclipse.ui.internal.services.IWorkbenchLocationService) HashSet(java.util.HashSet) Inject(javax.inject.Inject) TrimmedPartLayout(org.eclipse.e4.ui.workbench.renderers.swt.TrimmedPartLayout) Expression(org.eclipse.core.expressions.Expression) MPlaceholder(org.eclipse.e4.ui.model.application.ui.advanced.MPlaceholder) MPart(org.eclipse.e4.ui.model.application.ui.basic.MPart) ContextFunction(org.eclipse.e4.core.contexts.ContextFunction) IEclipseContext(org.eclipse.e4.core.contexts.IEclipseContext) IWorkbenchPreferenceConstants(org.eclipse.ui.IWorkbenchPreferenceConstants) RunAndTrack(org.eclipse.e4.core.contexts.RunAndTrack) WorkbenchLocationService(org.eclipse.ui.internal.services.WorkbenchLocationService) ICoolBarManager(org.eclipse.jface.action.ICoolBarManager) IWorkbenchActionConstants(org.eclipse.ui.IWorkbenchActionConstants) Iterator(java.util.Iterator) Layout(org.eclipse.swt.widgets.Layout) IPageListener(org.eclipse.ui.IPageListener) E4Workbench(org.eclipse.e4.ui.internal.workbench.E4Workbench) ISaveHandler(org.eclipse.e4.ui.workbench.modeling.ISaveHandler) ShellEvent(org.eclipse.swt.events.ShellEvent) StatusLineManager(org.eclipse.jface.action.StatusLineManager) InjectionException(org.eclipse.e4.core.di.InjectionException) MTrimBar(org.eclipse.e4.ui.model.application.ui.basic.MTrimBar) ActionBarAdvisor(org.eclipse.ui.application.ActionBarAdvisor) CommandAction(org.eclipse.ui.internal.actions.CommandAction) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ListSelectionDialog(org.eclipse.ui.dialogs.ListSelectionDialog) IContributionItem(org.eclipse.jface.action.IContributionItem) IWorkbench(org.eclipse.ui.IWorkbench) Menu(org.eclipse.swt.widgets.Menu) Collections(java.util.Collections) LabelProvider(org.eclipse.jface.viewers.LabelProvider) Control(org.eclipse.swt.widgets.Control) ISources(org.eclipse.ui.ISources) LinkedHashSet(java.util.LinkedHashSet) MPart(org.eclipse.e4.ui.model.application.ui.basic.MPart) ISaveHandler(org.eclipse.e4.ui.workbench.modeling.ISaveHandler) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ISaveablesLifecycleListener(org.eclipse.ui.ISaveablesLifecycleListener) PartServiceSaveHandler(org.eclipse.e4.ui.internal.workbench.PartServiceSaveHandler) MPerspective(org.eclipse.e4.ui.model.application.ui.advanced.MPerspective) IWorkbenchPage(org.eclipse.ui.IWorkbenchPage) CompatibilityPart(org.eclipse.ui.internal.e4.compatibility.CompatibilityPart) IWorkbenchPart(org.eclipse.ui.IWorkbenchPart) ListenerList(org.eclipse.core.runtime.ListenerList) ArrayList(java.util.ArrayList) List(java.util.List) IServiceLocatorCreator(org.eclipse.ui.internal.services.IServiceLocatorCreator) Saveable(org.eclipse.ui.Saveable) SafeRunnable(org.eclipse.jface.util.SafeRunnable) EContextService(org.eclipse.e4.ui.services.EContextService) WorkbenchException(org.eclipse.ui.WorkbenchException) ExpressionInfo(org.eclipse.core.expressions.ExpressionInfo) MMenu(org.eclipse.e4.ui.model.application.ui.menu.MMenu) ContextFunction(org.eclipse.e4.core.contexts.ContextFunction) ISaveablesSource(org.eclipse.ui.ISaveablesSource) Collection(java.util.Collection) EObject(org.eclipse.emf.ecore.EObject) MCompositePart(org.eclipse.e4.ui.model.application.ui.basic.MCompositePart) ISaveablePart(org.eclipse.ui.ISaveablePart) Shell(org.eclipse.swt.widgets.Shell) MMenu(org.eclipse.e4.ui.model.application.ui.menu.MMenu) Menu(org.eclipse.swt.widgets.Menu) UIExtensionTracker(org.eclipse.ui.internal.registry.UIExtensionTracker) IWindowCloseHandler(org.eclipse.e4.ui.workbench.modeling.IWindowCloseHandler) IExtensionTracker(org.eclipse.core.runtime.dynamichelpers.IExtensionTracker) UIExtensionTracker(org.eclipse.ui.internal.registry.UIExtensionTracker) IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) Point(org.eclipse.swt.graphics.Point) WorkbenchPartLabelProvider(org.eclipse.ui.model.WorkbenchPartLabelProvider) InvocationTargetException(java.lang.reflect.InvocationTargetException) WorkbenchException(org.eclipse.ui.WorkbenchException) InjectionException(org.eclipse.e4.core.di.InjectionException) RunAndTrack(org.eclipse.e4.core.contexts.RunAndTrack) IEclipseContext(org.eclipse.e4.core.contexts.IEclipseContext) IPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) WorkbenchPartLabelProvider(org.eclipse.ui.model.WorkbenchPartLabelProvider) LabelProvider(org.eclipse.jface.viewers.LabelProvider) ListSelectionDialog(org.eclipse.ui.dialogs.ListSelectionDialog) PostConstruct(javax.annotation.PostConstruct)

Example 2 with ServiceLocator

use of org.eclipse.ui.internal.services.ServiceLocator in project eclipse.platform.ui by eclipse-platform.

the class MenuAdditionCacheEntry method addMenuChildren.

private void addMenuChildren(final MElementContainer<MMenuElement> container, IConfigurationElement parent, String filter) {
    for (final IConfigurationElement child : parent.getChildren()) {
        String itemType = child.getName();
        String id = MenuHelper.getId(child);
        if (IWorkbenchRegistryConstants.TAG_COMMAND.equals(itemType)) {
            MMenuElement element = createMenuCommandAddition(child);
            container.getChildren().add(element);
        } else if (IWorkbenchRegistryConstants.TAG_SEPARATOR.equals(itemType)) {
            MMenuElement element = createMenuSeparatorAddition(child);
            container.getChildren().add(element);
        } else if (IWorkbenchRegistryConstants.TAG_MENU.equals(itemType)) {
            MMenu element = createMenuAddition(child, filter);
            container.getChildren().add(element);
        } else if (IWorkbenchRegistryConstants.TAG_TOOLBAR.equals(itemType)) {
            // $NON-NLS-1$//$NON-NLS-2$
            System.out.println("Toolbar: " + id + " in " + location);
        } else if (IWorkbenchRegistryConstants.TAG_DYNAMIC.equals(itemType)) {
            ContextFunction generator = new ContextFunction() {

                @Override
                public Object compute(IEclipseContext context, String contextKey) {
                    ServiceLocator sl = new ServiceLocator();
                    sl.setContext(context);
                    return new DynamicMenuContributionItem(MenuHelper.getId(child), sl, child);
                }
            };
            MMenuItem menuItem = RenderedElementUtil.createRenderedMenuItem();
            menuItem.setElementId(id);
            RenderedElementUtil.setContributionManager(menuItem, generator);
            menuItem.setVisibleWhen(MenuHelper.getVisibleWhen(child));
            container.getChildren().add(menuItem);
        }
    }
}
Also used : ServiceLocator(org.eclipse.ui.internal.services.ServiceLocator) ContextFunction(org.eclipse.e4.core.contexts.ContextFunction) MMenuItem(org.eclipse.e4.ui.model.application.ui.menu.MMenuItem) IEclipseContext(org.eclipse.e4.core.contexts.IEclipseContext) IConfigurationElement(org.eclipse.core.runtime.IConfigurationElement) MMenu(org.eclipse.e4.ui.model.application.ui.menu.MMenu) MMenuElement(org.eclipse.e4.ui.model.application.ui.menu.MMenuElement)

Example 3 with ServiceLocator

use of org.eclipse.ui.internal.services.ServiceLocator in project eclipse.platform.ui by eclipse-platform.

the class MenuAdditionCacheEntry method processToolbarChildren.

private void processToolbarChildren(ArrayList<MToolBarContribution> contributions, IConfigurationElement toolbar, String parentId, String position, boolean hasAdditions) {
    MToolBarContribution toolBarContribution = MenuFactoryImpl.eINSTANCE.createToolBarContribution();
    toolBarContribution.getPersistedState().put(IWorkbench.PERSIST_STATE, Boolean.FALSE.toString());
    String idContrib = MenuHelper.getId(toolbar);
    if (idContrib != null && idContrib.length() > 0) {
        toolBarContribution.setElementId(idContrib);
    }
    toolBarContribution.setParentId(parentId);
    toolBarContribution.setPositionInParent(position);
    // $NON-NLS-1$
    toolBarContribution.getTags().add("scheme:" + location.getScheme());
    for (final IConfigurationElement child : toolbar.getChildren()) {
        String itemType = child.getName();
        if (IWorkbenchRegistryConstants.TAG_COMMAND.equals(itemType)) {
            MToolBarElement element = createToolBarCommandAddition(child);
            toolBarContribution.getChildren().add(element);
        } else if (IWorkbenchRegistryConstants.TAG_SEPARATOR.equals(itemType)) {
            MToolBarElement element = createToolBarSeparatorAddition(child);
            toolBarContribution.getChildren().add(element);
        } else if (IWorkbenchRegistryConstants.TAG_CONTROL.equals(itemType)) {
            MToolBarElement element = createToolControlAddition(child);
            toolBarContribution.getChildren().add(element);
        } else if (IWorkbenchRegistryConstants.TAG_DYNAMIC.equals(itemType)) {
            ContextFunction generator = new ContextFunction() {

                @Override
                public Object compute(IEclipseContext context, String contextKey) {
                    ServiceLocator sl = new ServiceLocator();
                    sl.setContext(context);
                    return new DynamicToolBarContributionItem(MenuHelper.getId(child), sl, child);
                }
            };
            MToolBarElement element = createToolDynamicAddition(child);
            RenderedElementUtil.setContributionManager(element, generator);
            toolBarContribution.getChildren().add(element);
        }
    }
    if (hasAdditions) {
        contributions.add(0, toolBarContribution);
    } else {
        contributions.add(toolBarContribution);
    }
}
Also used : ServiceLocator(org.eclipse.ui.internal.services.ServiceLocator) ContextFunction(org.eclipse.e4.core.contexts.ContextFunction) MToolBarContribution(org.eclipse.e4.ui.model.application.ui.menu.MToolBarContribution) IEclipseContext(org.eclipse.e4.core.contexts.IEclipseContext) MToolBarElement(org.eclipse.e4.ui.model.application.ui.menu.MToolBarElement) IConfigurationElement(org.eclipse.core.runtime.IConfigurationElement)

Example 4 with ServiceLocator

use of org.eclipse.ui.internal.services.ServiceLocator in project eclipse.platform.ui by eclipse-platform.

the class Workbench method initializeDefaultServices.

/**
 * Initializes all of the default services for the workbench. For initializing
 * the command-based services, this also parses the registry and hooks up all
 * the required listeners.
 */
private void initializeDefaultServices() {
    final IContributionService contributionService = new ContributionService(getAdvisor());
    serviceLocator.registerService(IContributionService.class, contributionService);
    // TODO Correctly order service initialization
    // there needs to be some serious consideration given to
    // the services, and hooking them up in the correct order
    final IEvaluationService evaluationService = serviceLocator.getService(IEvaluationService.class);
    StartupThreading.runWithoutExceptions(new StartupRunnable() {

        @Override
        public void runWithException() {
            serviceLocator.registerService(ISaveablesLifecycleListener.class, new SaveablesList());
        }
    });
    /*
		 * Phase 1 of the initialization of commands. When this phase completes, all the
		 * services and managers will exist, and be accessible via the
		 * getService(Object) method.
		 */
    StartupThreading.runWithoutExceptions(new StartupRunnable() {

        @Override
        public void runWithException() {
            Command.DEBUG_COMMAND_EXECUTION = Policy.DEBUG_COMMANDS;
            commandManager = e4Context.get(CommandManager.class);
        }
    });
    final CommandService[] commandService = new CommandService[1];
    StartupThreading.runWithoutExceptions(new StartupRunnable() {

        @Override
        public void runWithException() {
            commandService[0] = initializeCommandService(e4Context);
        }
    });
    StartupThreading.runWithoutExceptions(new StartupRunnable() {

        @Override
        public void runWithException() {
            ContextManager.DEBUG = Policy.DEBUG_CONTEXTS;
            contextManager = e4Context.get(ContextManager.class);
        }
    });
    IContextService cxs = ContextInjectionFactory.make(ContextService.class, e4Context);
    final IContextService contextService = cxs;
    StartupThreading.runWithoutExceptions(new StartupRunnable() {

        @Override
        public void runWithException() {
            contextManager.addContextManagerListener(contextManagerEvent -> {
                if (contextManagerEvent.isContextChanged()) {
                    String id = contextManagerEvent.getContextId();
                    if (id != null) {
                        defineBindingTable(id);
                    }
                }
            });
            EContextService ecs = e4Context.get(EContextService.class);
            ecs.activateContext(IContextService.CONTEXT_ID_DIALOG_AND_WINDOW);
        }
    });
    serviceLocator.registerService(IContextService.class, contextService);
    final IBindingService[] bindingService = new BindingService[1];
    StartupThreading.runWithoutExceptions(new StartupRunnable() {

        @Override
        public void runWithException() {
            BindingManager.DEBUG = Policy.DEBUG_KEY_BINDINGS;
            bindingManager = e4Context.get(BindingManager.class);
            bindingService[0] = ContextInjectionFactory.make(BindingService.class, e4Context);
        }
    });
    // bindingService[0].readRegistryAndPreferences(commandService[0]);
    serviceLocator.registerService(IBindingService.class, bindingService[0]);
    final CommandImageManager commandImageManager = new CommandImageManager();
    final CommandImageService commandImageService = new CommandImageService(commandImageManager, commandService[0]);
    commandImageService.readRegistry();
    serviceLocator.registerService(ICommandImageService.class, commandImageService);
    final WorkbenchMenuService menuService = new WorkbenchMenuService(serviceLocator, e4Context);
    serviceLocator.registerService(IMenuService.class, menuService);
    // the service must be registered before it is initialized - its
    // initialization uses the service locator to address a dependency on
    // the menu service
    StartupThreading.runWithoutExceptions(new StartupRunnable() {

        @Override
        public void runWithException() {
            menuService.readRegistry();
        }
    });
    /*
		 * Phase 2 of the initialization of commands. The source providers that the
		 * workbench provides are creating and registered with the above services. These
		 * source providers notify the services when particular pieces of workbench
		 * state change.
		 */
    final SourceProviderService sourceProviderService = new SourceProviderService(serviceLocator);
    serviceLocator.registerService(ISourceProviderService.class, sourceProviderService);
    StartupThreading.runWithoutExceptions(new StartupRunnable() {

        @Override
        public void runWithException() {
            // this currently instantiates all players ... sigh
            sourceProviderService.readRegistry();
            ISourceProvider[] sourceproviders = sourceProviderService.getSourceProviders();
            for (ISourceProvider sp : sourceproviders) {
                evaluationService.addSourceProvider(sp);
                if (!(sp instanceof ActiveContextSourceProvider)) {
                    contextService.addSourceProvider(sp);
                }
            }
        }
    });
    StartupThreading.runWithoutExceptions(new StartupRunnable() {

        @Override
        public void runWithException() {
            // these guys are need to provide the variables they say
            // they source
            FocusControlSourceProvider focusControl = (FocusControlSourceProvider) sourceProviderService.getSourceProvider(ISources.ACTIVE_FOCUS_CONTROL_ID_NAME);
            serviceLocator.registerService(IFocusService.class, focusControl);
            menuSourceProvider = (MenuSourceProvider) sourceProviderService.getSourceProvider(ISources.ACTIVE_MENU_NAME);
        }
    });
    /*
		 * Phase 3 of the initialization of commands. This handles the creation of
		 * wrappers for legacy APIs. By the time this phase completes, any code trying
		 * to access commands through legacy APIs should work.
		 */
    final IHandlerService[] handlerService = new IHandlerService[1];
    StartupThreading.runWithoutExceptions(new StartupRunnable() {

        @Override
        public void runWithException() {
            handlerService[0] = new LegacyHandlerService(e4Context);
            e4Context.set(IHandlerService.class, handlerService[0]);
            handlerService[0].readRegistry();
        }
    });
    workbenchContextSupport = new WorkbenchContextSupport(this, contextManager);
    workbenchCommandSupport = new WorkbenchCommandSupport(bindingManager, commandManager, contextManager, handlerService[0]);
    initializeCommandResolver();
    bindingManager.addBindingManagerListener(bindingManagerListener);
    serviceLocator.registerService(ISelectionConversionService.class, new SelectionConversionService());
    backForwardListener = createBackForwardListener();
    StartupThreading.runWithoutExceptions(new StartupRunnable() {

        @Override
        public void runWithException() {
            getDisplay().addFilter(SWT.MouseDown, backForwardListener);
        }
    });
}
Also used : BufferedInputStream(java.io.BufferedInputStream) CommandService(org.eclipse.ui.internal.commands.CommandService) ISaveableFilter(org.eclipse.ui.ISaveableFilter) IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) IViewReference(org.eclipse.ui.IViewReference) Point(org.eclipse.swt.graphics.Point) IIntroManager(org.eclipse.ui.intro.IIntroManager) E4XMIResource(org.eclipse.e4.ui.internal.workbench.E4XMIResource) AbstractSplashHandler(org.eclipse.ui.splash.AbstractSplashHandler) ULocale(com.ibm.icu.util.ULocale) Map(java.util.Map) SWTException(org.eclipse.swt.SWTException) IServiceScopes(org.eclipse.ui.services.IServiceScopes) StatusManager(org.eclipse.ui.statushandlers.StatusManager) MessageDialog(org.eclipse.jface.dialogs.MessageDialog) IEditorPart(org.eclipse.ui.IEditorPart) IEvaluationService(org.eclipse.ui.services.IEvaluationService) IEditorInput(org.eclipse.ui.IEditorInput) PlatformUI(org.eclipse.ui.PlatformUI) StatusUtil(org.eclipse.ui.internal.misc.StatusUtil) IThemeManager(org.eclipse.ui.themes.IThemeManager) IRunnableContext(org.eclipse.jface.operation.IRunnableContext) OpenStrategy(org.eclipse.jface.util.OpenStrategy) ActiveContextSourceProvider(org.eclipse.ui.internal.contexts.ActiveContextSourceProvider) Window(org.eclipse.jface.window.Window) WorkbenchMenuService(org.eclipse.ui.internal.menus.WorkbenchMenuService) BindingManager(org.eclipse.jface.bindings.BindingManager) IApplicationContext(org.eclipse.equinox.app.IApplicationContext) XMLMemento(org.eclipse.ui.XMLMemento) IShellProvider(org.eclipse.jface.window.IShellProvider) SafeRunner(org.eclipse.core.runtime.SafeRunner) MPartDescriptor(org.eclipse.e4.ui.model.application.descriptor.basic.MPartDescriptor) SubMonitor(org.eclipse.core.runtime.SubMonitor) CommandsFactoryImpl(org.eclipse.e4.ui.model.application.commands.impl.CommandsFactoryImpl) BusyIndicator(org.eclipse.swt.custom.BusyIndicator) EPartService(org.eclipse.e4.ui.workbench.modeling.EPartService) ICommandService(org.eclipse.ui.commands.ICommandService) ListenerList(org.eclipse.core.runtime.ListenerList) IWorkbenchPart(org.eclipse.ui.IWorkbenchPart) WorkbenchContextSupport(org.eclipse.ui.internal.contexts.WorkbenchContextSupport) ColorDefinition(org.eclipse.ui.internal.themes.ColorDefinition) SplashHandlerFactory(org.eclipse.ui.internal.splash.SplashHandlerFactory) MWindow(org.eclipse.e4.ui.model.application.ui.basic.MWindow) IPropertyChangeListener(org.eclipse.jface.util.IPropertyChangeListener) ContributionService(org.eclipse.ui.internal.model.ContributionService) IMemento(org.eclipse.ui.IMemento) IWorkbenchContextSupport(org.eclipse.ui.contexts.IWorkbenchContextSupport) ProgressManager(org.eclipse.ui.internal.progress.ProgressManager) MCategory(org.eclipse.e4.ui.model.application.commands.MCategory) EcoreUtil(org.eclipse.emf.ecore.util.EcoreUtil) ISaveablesLifecycleListener(org.eclipse.ui.ISaveablesLifecycleListener) CompatibilityEditor(org.eclipse.ui.internal.e4.compatibility.CompatibilityEditor) IOException(java.io.IOException) ServiceLocatorCreator(org.eclipse.ui.internal.services.ServiceLocatorCreator) ImageDescriptor(org.eclipse.jface.resource.ImageDescriptor) WorkbenchCommandSupport(org.eclipse.ui.internal.commands.WorkbenchCommandSupport) EModelService(org.eclipse.e4.ui.workbench.modeling.EModelService) StringReader(java.io.StringReader) IContextService(org.eclipse.ui.contexts.IContextService) EvaluationService(org.eclipse.ui.internal.services.EvaluationService) ViewDescriptor(org.eclipse.ui.internal.registry.ViewDescriptor) ContextInjectionFactory(org.eclipse.e4.core.contexts.ContextInjectionFactory) UIEvents(org.eclipse.e4.ui.workbench.UIEvents) WorkbenchException(org.eclipse.ui.WorkbenchException) IPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) WorkbenchAdvisor(org.eclipse.ui.application.WorkbenchAdvisor) URISyntaxException(java.net.URISyntaxException) IAction(org.eclipse.jface.action.IAction) IBindingManagerListener(org.eclipse.jface.bindings.IBindingManagerListener) ErrorDialog(org.eclipse.jface.dialogs.ErrorDialog) Policy(org.eclipse.ui.internal.misc.Policy) IWorkbenchRegistryConstants(org.eclipse.ui.internal.registry.IWorkbenchRegistryConstants) MCommandsFactory(org.eclipse.e4.ui.model.application.commands.MCommandsFactory) IStatus(org.eclipse.core.runtime.IStatus) IExtensionRegistry(org.eclipse.core.runtime.IExtensionRegistry) IExtensionPoint(org.eclipse.core.runtime.IExtensionPoint) FontDefinition(org.eclipse.ui.internal.themes.FontDefinition) IAdaptable(org.eclipse.core.runtime.IAdaptable) IWizardRegistry(org.eclipse.ui.wizards.IWizardRegistry) IBindingService(org.eclipse.ui.keys.IBindingService) Collection(java.util.Collection) UUID(java.util.UUID) ShowKeysListener(org.eclipse.ui.internal.keys.show.ShowKeysListener) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) SourceProviderService(org.eclipse.ui.internal.services.SourceProviderService) Objects(java.util.Objects) ISourceProvider(org.eclipse.ui.ISourceProvider) WorkbenchThemeManager(org.eclipse.ui.internal.themes.WorkbenchThemeManager) ISourceProviderService(org.eclipse.ui.services.ISourceProviderService) ISelection(org.eclipse.jface.viewers.ISelection) IEditorRegistry(org.eclipse.ui.IEditorRegistry) CommandCallback(org.eclipse.jface.action.ExternalActionManager.CommandCallback) CompatibilityPart(org.eclipse.ui.internal.e4.compatibility.CompatibilityPart) SafeRunnable(org.eclipse.jface.util.SafeRunnable) WWinPartServiceSaveHandler(org.eclipse.ui.internal.WorkbenchWindow.WWinPartServiceSaveHandler) IExtensionDelta(org.eclipse.core.runtime.IExtensionDelta) IDecoratorManager(org.eclipse.ui.IDecoratorManager) IPerspectiveRegistry(org.eclipse.ui.IPerspectiveRegistry) Image(org.eclipse.swt.graphics.Image) IEventLoopAdvisor(org.eclipse.e4.ui.internal.workbench.swt.IEventLoopAdvisor) BundleEvent(org.osgi.framework.BundleEvent) HashSet(java.util.HashSet) E4Util(org.eclipse.ui.internal.e4.compatibility.E4Util) E4Application(org.eclipse.e4.ui.internal.workbench.swt.E4Application) MPart(org.eclipse.e4.ui.model.application.ui.basic.MPart) DeviceData(org.eclipse.swt.graphics.DeviceData) IWorkbenchPreferenceConstants(org.eclipse.ui.IWorkbenchPreferenceConstants) WorkbenchLocationService(org.eclipse.ui.internal.services.WorkbenchLocationService) NotHandledException(org.eclipse.core.commands.NotHandledException) BindingService(org.eclipse.ui.internal.keys.BindingService) ServiceRegistration(org.osgi.framework.ServiceRegistration) IRegistryChangeListener(org.eclipse.core.runtime.IRegistryChangeListener) ISaveHandler(org.eclipse.e4.ui.workbench.modeling.ISaveHandler) FileInputStream(java.io.FileInputStream) EclipseSplashHandler(org.eclipse.ui.internal.splash.EclipseSplashHandler) UIStats(org.eclipse.ui.internal.misc.UIStats) ITheme(org.eclipse.ui.themes.ITheme) SynchronousBundleListener(org.osgi.framework.SynchronousBundleListener) FrameworkUtil(org.osgi.framework.FrameworkUtil) Arrays(java.util.Arrays) NotDefinedException(org.eclipse.core.commands.common.NotDefinedException) MultiStatus(org.eclipse.core.runtime.MultiStatus) MTrimContribution(org.eclipse.e4.ui.model.application.ui.menu.MTrimContribution) ActionContributionItem(org.eclipse.jface.action.ActionContributionItem) CoreException(org.eclipse.core.runtime.CoreException) PartRenderingEngine(org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine) IServiceLocatorCreator(org.eclipse.ui.internal.services.IServiceLocatorCreator) MenuSourceProvider(org.eclipse.ui.internal.services.MenuSourceProvider) IUpdateService(org.eclipse.e4.ui.internal.workbench.renderers.swt.IUpdateService) PartInitException(org.eclipse.ui.PartInitException) MBindingContext(org.eclipse.e4.ui.model.application.commands.MBindingContext) BidiUtils(org.eclipse.jface.util.BidiUtils) WorkbenchHelpSystem(org.eclipse.ui.internal.help.WorkbenchHelpSystem) MApplication(org.eclipse.e4.ui.model.application.MApplication) ServiceLocator(org.eclipse.ui.internal.services.ServiceLocator) Realm(org.eclipse.core.databinding.observable.Realm) EContextService(org.eclipse.e4.ui.services.EContextService) PreferenceConverter(org.eclipse.jface.preference.PreferenceConverter) MenuManager(org.eclipse.jface.action.MenuManager) Assert(org.eclipse.core.runtime.Assert) Set(java.util.Set) Status(org.eclipse.core.runtime.Status) IModelResourceHandler(org.eclipse.e4.ui.workbench.IModelResourceHandler) Saveable(org.eclipse.ui.Saveable) DisplayRealm(org.eclipse.jface.databinding.swt.DisplayRealm) IFocusService(org.eclipse.ui.swt.IFocusService) SWT(org.eclipse.swt.SWT) ICommandImageService(org.eclipse.ui.commands.ICommandImageService) IWorkbenchOperationSupport(org.eclipse.ui.operations.IWorkbenchOperationSupport) Dictionary(java.util.Dictionary) MCommand(org.eclipse.e4.ui.model.application.commands.MCommand) WorkbenchJob(org.eclipse.ui.progress.WorkbenchJob) IWorkbenchBrowserSupport(org.eclipse.ui.browser.IWorkbenchBrowserSupport) ArrayList(java.util.ArrayList) Listener(org.eclipse.swt.widgets.Listener) IConfigurationElement(org.eclipse.core.runtime.IConfigurationElement) IApplication(org.eclipse.equinox.app.IApplication) IViewRegistry(org.eclipse.ui.views.IViewRegistry) NotEnabledException(org.eclipse.core.commands.NotEnabledException) FocusControlSourceProvider(org.eclipse.ui.internal.menus.FocusControlSourceProvider) LegacyHandlerService(org.eclipse.ui.internal.handlers.LegacyHandlerService) CommandManager(org.eclipse.core.commands.CommandManager) Shell(org.eclipse.swt.widgets.Shell) IWorkbenchHelpSystem(org.eclipse.ui.help.IWorkbenchHelpSystem) StringWriter(java.io.StringWriter) IElementFactory(org.eclipse.ui.IElementFactory) ExecutionException(org.eclipse.core.commands.ExecutionException) IPresentationEngine(org.eclipse.e4.ui.workbench.IPresentationEngine) PrefUtil(org.eclipse.ui.internal.util.PrefUtil) EventManager(org.eclipse.core.commands.common.EventManager) Command(org.eclipse.core.commands.Command) IWorkbenchListener(org.eclipse.ui.IWorkbenchListener) IIntroRegistry(org.eclipse.ui.internal.intro.IIntroRegistry) ServiceTracker(org.osgi.util.tracker.ServiceTracker) Platform(org.eclipse.core.runtime.Platform) ModalContext(org.eclipse.jface.operation.ModalContext) IEventBroker(org.eclipse.e4.core.services.events.IEventBroker) StartupRunnable(org.eclipse.ui.internal.StartupThreading.StartupRunnable) IExtensionTracker(org.eclipse.core.runtime.dynamichelpers.IExtensionTracker) Constants(org.osgi.framework.Constants) URL(java.net.URL) IWorkbenchCommandConstants(org.eclipse.ui.IWorkbenchCommandConstants) CommandImageManager(org.eclipse.ui.internal.commands.CommandImageManager) IMenuService(org.eclipse.ui.menus.IMenuService) UIExtensionTracker(org.eclipse.ui.internal.registry.UIExtensionTracker) ThemeElementHelper(org.eclipse.ui.internal.themes.ThemeElementHelper) IProgressService(org.eclipse.ui.progress.IProgressService) URI(java.net.URI) ProgressManagerUtil(org.eclipse.ui.internal.progress.ProgressManagerUtil) IExtension(org.eclipse.core.runtime.IExtension) MElementContainer(org.eclipse.e4.ui.model.application.ui.MElementContainer) NLS(org.eclipse.osgi.util.NLS) ExternalActionManager(org.eclipse.jface.action.ExternalActionManager) EObject(org.eclipse.emf.ecore.EObject) Display(org.eclipse.swt.widgets.Display) ContextService(org.eclipse.ui.internal.contexts.ContextService) IWorkbenchPage(org.eclipse.ui.IWorkbenchPage) BundleContext(org.osgi.framework.BundleContext) ISharedImages(org.eclipse.ui.ISharedImages) IHandlerService(org.eclipse.ui.handlers.IHandlerService) List(java.util.List) IDisposable(org.eclipse.ui.services.IDisposable) Category(com.ibm.icu.util.ULocale.Category) IPerspectiveDescriptor(org.eclipse.ui.IPerspectiveDescriptor) IViewDescriptor(org.eclipse.ui.views.IViewDescriptor) IProduct(org.eclipse.core.runtime.IProduct) Resource(org.eclipse.emf.ecore.resource.Resource) ContributionInfoMessages(org.eclipse.ui.internal.testing.ContributionInfoMessages) IWindowListener(org.eclipse.ui.IWindowListener) ILocalWorkingSetManager(org.eclipse.ui.ILocalWorkingSetManager) MBindingTable(org.eclipse.e4.ui.model.application.commands.MBindingTable) StartupMonitor(org.eclipse.osgi.service.runnable.StartupMonitor) PropertyPageContributorManager(org.eclipse.ui.internal.dialogs.PropertyPageContributorManager) HashMap(java.util.HashMap) IWorkbenchLocationService(org.eclipse.ui.internal.services.IWorkbenchLocationService) ContextManager(org.eclipse.core.commands.contexts.ContextManager) IntroDescriptor(org.eclipse.ui.internal.intro.IntroDescriptor) ContextFunction(org.eclipse.e4.core.contexts.ContextFunction) IEclipseContext(org.eclipse.e4.core.contexts.IEclipseContext) PreferenceManager(org.eclipse.jface.preference.PreferenceManager) IWorkbenchActivitySupport(org.eclipse.ui.activities.IWorkbenchActivitySupport) IWorkbenchCommandSupport(org.eclipse.ui.commands.IWorkbenchCommandSupport) ContributionInfo(org.eclipse.ui.testing.ContributionInfo) Hashtable(java.util.Hashtable) WorkbenchActivitySupport(org.eclipse.ui.internal.activities.ws.WorkbenchActivitySupport) Job(org.eclipse.core.runtime.jobs.Job) E4Workbench(org.eclipse.e4.ui.internal.workbench.E4Workbench) InjectionException(org.eclipse.e4.core.di.InjectionException) CommandAction(org.eclipse.ui.internal.actions.CommandAction) WorkbenchTestable(org.eclipse.ui.internal.testing.WorkbenchTestable) CommandImageService(org.eclipse.ui.internal.commands.CommandImageService) FontData(org.eclipse.swt.graphics.FontData) WorkbenchBrowserSupport(org.eclipse.ui.internal.browser.WorkbenchBrowserSupport) IWorkbench(org.eclipse.ui.IWorkbench) IWorkingSetManager(org.eclipse.ui.IWorkingSetManager) Collections(java.util.Collections) InputStream(java.io.InputStream) BasicFactoryImpl(org.eclipse.e4.ui.model.application.ui.basic.impl.BasicFactoryImpl) ISources(org.eclipse.ui.ISources) IContributionService(org.eclipse.ui.model.IContributionService) FocusControlSourceProvider(org.eclipse.ui.internal.menus.FocusControlSourceProvider) WorkbenchMenuService(org.eclipse.ui.internal.menus.WorkbenchMenuService) CommandService(org.eclipse.ui.internal.commands.CommandService) ICommandService(org.eclipse.ui.commands.ICommandService) StartupRunnable(org.eclipse.ui.internal.StartupThreading.StartupRunnable) ISaveablesLifecycleListener(org.eclipse.ui.ISaveablesLifecycleListener) IFocusService(org.eclipse.ui.swt.IFocusService) SourceProviderService(org.eclipse.ui.internal.services.SourceProviderService) ISourceProviderService(org.eclipse.ui.services.ISourceProviderService) IContextService(org.eclipse.ui.contexts.IContextService) IBindingService(org.eclipse.ui.keys.IBindingService) IBindingService(org.eclipse.ui.keys.IBindingService) BindingService(org.eclipse.ui.internal.keys.BindingService) ISourceProvider(org.eclipse.ui.ISourceProvider) WorkbenchContextSupport(org.eclipse.ui.internal.contexts.WorkbenchContextSupport) IWorkbenchContextSupport(org.eclipse.ui.contexts.IWorkbenchContextSupport) WorkbenchCommandSupport(org.eclipse.ui.internal.commands.WorkbenchCommandSupport) IWorkbenchCommandSupport(org.eclipse.ui.commands.IWorkbenchCommandSupport) EContextService(org.eclipse.e4.ui.services.EContextService) MenuSourceProvider(org.eclipse.ui.internal.services.MenuSourceProvider) IHandlerService(org.eclipse.ui.handlers.IHandlerService) LegacyHandlerService(org.eclipse.ui.internal.handlers.LegacyHandlerService) ActiveContextSourceProvider(org.eclipse.ui.internal.contexts.ActiveContextSourceProvider) IContributionService(org.eclipse.ui.model.IContributionService) ICommandImageService(org.eclipse.ui.commands.ICommandImageService) CommandImageService(org.eclipse.ui.internal.commands.CommandImageService) ContributionService(org.eclipse.ui.internal.model.ContributionService) IContributionService(org.eclipse.ui.model.IContributionService) IEvaluationService(org.eclipse.ui.services.IEvaluationService) CommandImageManager(org.eclipse.ui.internal.commands.CommandImageManager)

Example 5 with ServiceLocator

use of org.eclipse.ui.internal.services.ServiceLocator in project eclipse.platform.ui by eclipse-platform.

the class ContributionFactoryGenerator method compute.

@Override
public Object compute(IEclipseContext context, String contextKey) {
    AbstractContributionFactory factory = getFactory();
    final IMenuService menuService = context.get(IMenuService.class);
    final ContributionRoot root = new ContributionRoot(menuService, new HashSet<>(), null, factory);
    ServiceLocator sl = new ServiceLocator();
    sl.setContext(context);
    factory.createContributionItems(sl, root);
    final List contributionItems = root.getItems();
    final Map<IContributionItem, Expression> itemsToExpression = root.getVisibleWhen();
    List<MUIElement> menuElements = new ArrayList<>();
    for (Object obj : contributionItems) {
        if (obj instanceof IContributionItem) {
            IContributionItem ici = (IContributionItem) obj;
            MUIElement opaqueItem = createUIElement(ici);
            if (opaqueItem != null) {
                if (itemsToExpression.containsKey(ici)) {
                    final Expression ex = itemsToExpression.get(ici);
                    MCoreExpression exp = UiFactoryImpl.eINSTANCE.createCoreExpression();
                    // $NON-NLS-1$
                    exp.setCoreExpressionId("programmatic." + ici.getId());
                    exp.setCoreExpression(ex);
                    opaqueItem.setVisibleWhen(exp);
                }
                menuElements.add(opaqueItem);
            }
        }
    }
    context.set(List.class, menuElements);
    // return something disposable
    return (Runnable) root::release;
}
Also used : IContributionItem(org.eclipse.jface.action.IContributionItem) ArrayList(java.util.ArrayList) AbstractContributionFactory(org.eclipse.ui.menus.AbstractContributionFactory) ServiceLocator(org.eclipse.ui.internal.services.ServiceLocator) IMenuService(org.eclipse.ui.menus.IMenuService) MCoreExpression(org.eclipse.e4.ui.model.application.ui.MCoreExpression) Expression(org.eclipse.core.expressions.Expression) ArrayList(java.util.ArrayList) List(java.util.List) MUIElement(org.eclipse.e4.ui.model.application.ui.MUIElement) MCoreExpression(org.eclipse.e4.ui.model.application.ui.MCoreExpression)

Aggregations

ServiceLocator (org.eclipse.ui.internal.services.ServiceLocator)5 IConfigurationElement (org.eclipse.core.runtime.IConfigurationElement)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 ContextFunction (org.eclipse.e4.core.contexts.ContextFunction)3 IEclipseContext (org.eclipse.e4.core.contexts.IEclipseContext)3 Arrays (java.util.Arrays)2 Collection (java.util.Collection)2 Collections (java.util.Collections)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 Set (java.util.Set)2 Expression (org.eclipse.core.expressions.Expression)2 Assert (org.eclipse.core.runtime.Assert)2 IAdaptable (org.eclipse.core.runtime.IAdaptable)2 MMenu (org.eclipse.e4.ui.model.application.ui.menu.MMenu)2 MMenuElement (org.eclipse.e4.ui.model.application.ui.menu.MMenuElement)2 IMenuService (org.eclipse.ui.menus.IMenuService)2 ULocale (com.ibm.icu.util.ULocale)1