Как сбросить перспективу для приложения Eclipse e4 RCP?

После создания перспективы в файле application.e4xmi я не могу сбросить перспективу, вызвав IWorkbenchPage.resetPerspective ().


person n8n8baby    schedule 31.10.2013    source источник
comment
Вы должны написать часть вопроса как вопрос и поставить ответ как ответ. Затем вы можете принять его самостоятельно (что совершенно нормально!) Через 24 часа.   -  person oers    schedule 20.11.2013
comment
Спасибо за совет.   -  person n8n8baby    schedule 21.11.2013


Ответы (2)


Я думал, что это может сэкономить время другим, а также задокументировать это для себя.

Уловка, позволяющая сбросить перспективу e4, заключается в следующем (предполагается, что базовое приложение e4xmi с элементом PerspectiveStack):

  1. В файле application.e4xmi найдите PerspectiveStack в узле Application / TrimmedWindow. Запишите / установите его ID.
  2. В редакторе моделей Eclipse 4 перетащите свои перспективы из-под PerspectiveStack в Application / Snippets. (Это приведет к тому, что ваши идентификаторы перспективы будут зарегистрированы в IPerspectiveRegistry и обеспечат исходное состояние).
  3. Создайте новый CopyPerspectiveSnippetProcessor. Это скопирует перспективы из ваших фрагментов в ваш PerspectiveStack при запуске. Благодаря этому вам не нужно поддерживать по две копии каждого элемента перспективы в вашем файле e4xmi.

    package com.example.application.processors;
    
    import org.eclipse.e4.core.di.annotations.Execute;
    import org.eclipse.e4.ui.model.application.MApplication;
    import org.eclipse.e4.ui.model.application.ui.MUIElement;
    import org.eclipse.e4.ui.model.application.ui.advanced.MPerspective;
    import org.eclipse.e4.ui.model.application.ui.advanced.MPerspectiveStack;
    import org.eclipse.e4.ui.workbench.modeling.EModelService;
    
    /**
     * Copies all snippet perspectives to perspective stack called "MainPerspectiveStack" In order to register/reset perspective and not have to sync two copies in
     * e4xmi.
     * 
     */
    public class CopyPerspectiveSnippetProcessor {
        private static final String MAIN_PERSPECTIVE_STACK_ID = "MainPerspectiveStack";
    
        @Execute
        public void execute(EModelService modelService, MApplication application) {
            MPerspectiveStack perspectiveStack = (MPerspectiveStack) modelService.find(MAIN_PERSPECTIVE_STACK_ID, application);
    
            // Only do this when no other children, or the restored workspace state will be overwritten.
            if (!perspectiveStack.getChildren().isEmpty())
                return;
    
            // clone each snippet that is a perspective and add the cloned perspective into the main PerspectiveStack
            boolean isFirst = true;
            for (MUIElement snippet : application.getSnippets()) {
                if (snippet instanceof MPerspective) {
                    MPerspective perspectiveClone = (MPerspective) modelService.cloneSnippet(application, snippet.getElementId(), null);
                    perspectiveStack.getChildren().add(perspectiveClone);
                    if (isFirst) {
                        perspectiveStack.setSelectedElement(perspectiveClone);
                        isFirst = false;
                    }
                }
            }
        }
    }
    
  4. Зарегистрируйте свой CopyPerspectiveSnippetProcess в файле plugin.xml.

    <extension id="MainAppModel" point="org.eclipse.e4.workbench.model">
        <processor beforefragment="false" class="com.example.application.processors.CopyPerspectiveSnippetProcessor"/>
    </extension>
    
  5. Восстановите перспективу как обычно. Вам также может потребоваться сделать видимыми стек перспектив и текущую перспективу, поскольку иногда их можно сделать невидимыми. Пример обработчика может выглядеть так:

    import org.eclipse.e4.core.di.annotations.Execute;
    import org.eclipse.e4.ui.model.application.MApplication;
    import org.eclipse.e4.ui.model.application.ui.advanced.MPerspectiveStack;
    import org.eclipse.e4.ui.workbench.modeling.EModelService;
    import org.eclipse.ui.PlatformUI;
    
    public class ResetPerspectiveHandler {
        private static final String MAIN_PERSPECTIVE_STACK_ID = "MainPerspectiveStack";
    
        @Execute
        public void execute(EModelService modelService, MApplication application) {
             MPerspectiveStack perspectiveStack = (MPerspectiveStack) modelService.find(MAIN_PERSPECTIVE_STACK_ID, application);
             PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().resetPerspective();
             perspectiveStack.getSelectedElement().setVisible(true);
             perspectiveStack.setVisible(true);
        }
    }
    
person n8n8baby    schedule 20.11.2013
comment
Я добавил тест для предотвращения перезаписи постоянного состояния рабочей области. - person n8n8baby; 16.03.2014
comment
Я обнаружил, что использование этого метода может повлиять на такие вещи, как сохранение размеров элемента пользовательского интерфейса, поэтому будьте осторожны, это может иметь неприемлемые побочные эффекты. В итоге мы смогли ограничить пользовательский интерфейс таким образом, что он убрал наше требование сброса перспективы. - person n8n8baby; 23.05.2014
comment
Использование PlatformUI не является подходящим решением для чистого приложения e4. - person alphakermit; 02.10.2018
comment
Не забывайте объяснять, почему не было никому, у кого есть подобные проблемы? В настоящее время я действительно не работаю на Java, поэтому у меня мало контекста, но я знаю, что E4 был довольно новым, когда я работал над этой проблемой. - person n8n8baby; 03.10.2018
comment
Использование PlatformUI вынуждает вас реализовать множество старых зависимостей пакетов рабочей среды 3.x, которые обычно пытаются избежать установки чистого приложения e4. См. Ответ V Kash Singh для правильного пути e4 (2-й подход в его коде). - person alphakermit; 04.10.2018

Сбросить перспективу (когда вы запускаете приложение e4, не освобождая рабочее место, когда вы переключаете другую перспективу на свое восприятие).

Шаг 1. Добавьте надстройку во фрагмент модели на уровне приложения. введите здесь описание изображения

Шаг 2. Создайте класс надстройки и реализуйте EventHandler.

Шаг 3: добавьте в класс следующий код.

public class ResetPrespectiveAddOn implements EventHandler {

private static final String MY_PERSPECTIVE_ID = "myPrespectiveId";

@Inject
private IEventBroker broker;

@PostConstruct
public void loadPrespective() {

    broker.subscribe(UIEvents.ElementContainer.TOPIC_SELECTEDELEMENT, this);
}

@SuppressWarnings("restriction")
@Override
public void handleEvent(Event event) {

    //UIEvents.EventTags.ELEMENT is trigger  for all UI activity
    Object property = event.getProperty(UIEvents.EventTags.ELEMENT);
    if (!(property instanceof PerspectiveStackImpl)) {
        return;

    }

    // Reset perspective logic .
    IEclipseContext serviceContext = E4Workbench.getServiceContext();
    final IEclipseContext appContext = (IEclipseContext) serviceContext.getActiveChild();
    EModelService modelService = appContext.get(EModelService.class);
    MApplication application = serviceContext.get(MApplication.class);
    MWindow mWindow = application.getChildren().get(0);

    PerspectiveStackImpl perspectiveStack = (PerspectiveStackImpl) property;
    List<MPerspective> children = perspectiveStack.getChildren();
    for (MPerspective myPerspective : children) {
        if (myPerspective.getElementId().equals(MY_PERSPECTIVE_ID)) {

            //find active perspective
            MPerspective activePerspective = modelService.getActivePerspective(mWindow);
            if(activePerspective.getElementId().equals(MY_PERSPECTIVE_ID))

            //Reseting perspective  e3 way 
            PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().resetPerspective();


            // till now there is no direct e4 way to reset perspective 
            // but u can Add and remove e4 perspective with this code code              
            EPartService partService = serviceContext.get(EPartService.class);
            MPerspectiveStack perspectiveStack = (MPerspectiveStack) (MElementContainer<?>) activePerspective.getParent();
            int indexOf = perspectiveStack.getChildren().indexOf(activePerspective);
            perspectiveStack.getChildren().remove(indexOf);

            perspectiveStack.getChildren().add(myPerspective);
            partService.switchPerspective(myPerspective);
        }   
    }
}}
person V Kash Singh    schedule 24.09.2018