/**
   * Tests setting a value in a context that a RAT is listening to. This test mimics what occurs
   * when handlers change in e4. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=305038
   */
  public void testSetValueRunAndTrack() {
    context.set(
        "somefunction",
        new ContextFunction() {
          @Override
          public Object compute(IEclipseContext context, String contextKey) {
            // make sure this function has a large number of dependencies
            for (int i = 0; i < 1000; i++) {
              context.get("NonExistentValue-" + i);
            }
            return context.get("something");
          }
        });
    context.runAndTrack(
        new RunAndTrack() {
          @Override
          public boolean changed(IEclipseContext context) {
            context.get("somefunction");
            return true;
          }
        });
    new PerformanceTestRunner() {
      int i = 0;

      @Override
      protected void test() {
        context.set("something", "value-" + i++);
      }
    }.run(this, 10, 400);
  }
  /*
   * (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;
  }
 /**
  * @param menuModel
  * @param manager
  * @param menuContribution
  * @return true if the menuContribution was processed
  */
 private boolean processAddition(
     MMenu menuModel,
     final MenuManager manager,
     MMenuContribution menuContribution,
     final HashSet<String> existingMenuIds,
     HashSet<String> existingSeparatorNames,
     boolean menuBar) {
   final ContributionRecord record = new ContributionRecord(menuModel, menuContribution, this);
   if (!record.mergeIntoModel()) {
     return false;
   }
   if (menuBar) {
     final IEclipseContext parentContext = modelService.getContainingContext(menuModel);
     parentContext.runAndTrack(
         new RunAndTrack() {
           @Override
           public boolean changed(IEclipseContext context) {
             record.updateVisibility(parentContext.getActiveLeaf());
             manager.update(true);
             return true;
           }
         });
   }
   return true;
 }
  @Test
  public void testInjectWildCard() {
    IEclipseContext context = EclipseContextFactory.create();
    final Display d = Display.getDefault();

    context.set(Realm.class, DisplayRealm.getRealm(d));
    context.set(
        UISynchronize.class,
        new UISynchronize() {

          @Override
          public void syncExec(Runnable runnable) {
            d.syncExec(runnable);
          }

          @Override
          public void asyncExec(Runnable runnable) {
            d.asyncExec(runnable);
          }
        });

    InjectStarEvent target = ContextInjectionFactory.make(InjectStarEvent.class, context);

    // initial state
    assertEquals(0, target.counter1);
    assertNull(target.data);

    // send event
    helper.sendEvent("e4/test/eventInjection", "sample");

    assertEquals(1, target.counter1);
    assertEquals("sample", target.data);
  }
示例#5
0
  @Execute
  public void execute(
      IEclipseContext context,
      @Named(IServiceConstants.ACTIVE_SHELL) Shell shell,
      @Named(IServiceConstants.ACTIVE_PART) final MContribution contribution)
      throws InvocationTargetException, InterruptedException {
    final IEclipseContext pmContext = context.createChild();

    ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
    dialog.open();
    dialog.run(
        true,
        true,
        new IRunnableWithProgress() {
          @Override
          public void run(IProgressMonitor monitor)
              throws InvocationTargetException, InterruptedException {
            pmContext.set(IProgressMonitor.class.getName(), monitor);
            if (contribution != null) {
              //			Object clientObject = contribution.getObject();
              //					ContextInjectionFactory.invoke(clientObject, Persist.class, //$NON-NLS-1$
              //							pmContext, null);
            }
          }
        });

    pmContext.dispose();
  }
  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);
        }
      }
    }
  }
  public static void initializeApplicationServices(IEclipseContext appContext) {
    final IEclipseContext theContext = appContext;
    // we add a special tracker to bring up current selection from
    // the active window to the application level
    appContext.runAndTrack(
        new RunAndTrack() {
          @Override
          public boolean changed(IEclipseContext context) {
            IEclipseContext activeChildContext = context.getActiveChild();
            if (activeChildContext != null) {
              Object selection = activeChildContext.get(IServiceConstants.ACTIVE_SELECTION);
              theContext.set(IServiceConstants.ACTIVE_SELECTION, selection);
            }
            return true;
          }
        });

    // we create a selection service handle on every node that we are asked
    // about as handle needs to know its context
    appContext.set(
        ESelectionService.class.getName(),
        new ContextFunction() {
          @Override
          public Object compute(IEclipseContext context, String contextKey) {
            return ContextInjectionFactory.make(SelectionServiceImpl.class, context);
          }
        });
  }
 public boolean canExecute(ParameterizedCommand command) {
   final IEclipseContext staticContext = EclipseContextFactory.create(TMP_STATIC_CONTEXT);
   try {
     return canExecute(command, staticContext);
   } finally {
     staticContext.dispose();
   }
 }
 /*
  * (non-Javadoc)
  *
  * @seeorg.eclipse.e4.core.commands.EHandlerService#executeHandler(org.eclipse.core.commands.
  * ParameterizedCommand)
  */
 public Object executeHandler(ParameterizedCommand command) {
   final IEclipseContext staticContext = EclipseContextFactory.create(TMP_STATIC_CONTEXT);
   try {
     return executeHandler(command, staticContext);
   } finally {
     staticContext.dispose();
   }
 }
 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]);
   }
 }
 public IEclipseContext getActiveLeaf() {
   IEclipseContext activeContext = this;
   IEclipseContext child = getActiveChild();
   while (child != null) {
     activeContext = child;
     child = child.getActiveChild();
   }
   return activeContext;
 }
 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;
 }
 @PostConstruct
 public void init(MApplication application, IEclipseContext context) {
   IEclipseContext appContext = application.getContext();
   appContext.set(Preferences.class, ContextInjectionFactory.make(Preferences.class, appContext));
   appContext.set(
       PreferenceStore.class, ContextInjectionFactory.make(PreferenceStore.class, appContext));
   ContextInjectionFactory.make(Services.class, context);
   ProgressManager progressManager = ContextInjectionFactory.make(ProgressManager.class, context);
   appContext.set(ProgressManager.class, progressManager);
 }
  @Override
  public void switchPerspective(MPerspective perspective) {
    Assert.isNotNull(perspective);
    MWindow window = getWindow();
    if (window != null && isInContainer(window, perspective)) {
      perspective.getParent().setSelectedElement(perspective);
      List<MPart> newPerspectiveParts =
          modelService.findElements(perspective, null, MPart.class, null);
      // if possible, keep the same active part across perspective switches
      if (newPerspectiveParts.contains(activePart)
          && partActivationHistory.isValid(perspective, activePart)) {
        MPart target = activePart;
        IEclipseContext activeChild = activePart.getContext().getParent().getActiveChild();
        if (activeChild != null) {
          activeChild.deactivate();
        }
        if (target.getContext() != null
            && target.getContext().get(MPerspective.class) != null
            && target.getContext().get(MPerspective.class).getContext()
                == perspective.getContext()) {
          target.getContext().activateBranch();
        } else {
          perspective.getContext().activate();
        }

        modelService.bringToTop(target);
        activate(target, true, false);
        return;
      }

      MPart newActivePart = perspective.getContext().getActiveLeaf().get(MPart.class);
      if (newActivePart == null) {
        // whatever part was previously active can no longer be found, find another one
        MPart candidate = partActivationHistory.getActivationCandidate(perspective);
        if (candidate != null) {
          modelService.bringToTop(candidate);
          activate(candidate, true, false);
          return;
        }
      }

      // there seems to be no parts in this perspective, just activate it as is then
      if (newActivePart == null) {
        modelService.bringToTop(perspective);
        perspective.getContext().activate();
      } else {
        if ((modelService.getElementLocation(newActivePart) & EModelService.IN_SHARED_AREA) != 0) {
          if (newActivePart.getParent().getSelectedElement() != newActivePart) {
            newActivePart = (MPart) newActivePart.getParent().getSelectedElement();
          }
        }
        activate(newActivePart, true, false);
      }
    }
  }
示例#15
0
  public static void createParts(
      MApplication application, EModelService service, EPartService partService) {
    // Sometimes, when switching windows at startup, the active context
    // is null or doesn't have a window, and the part instantiation fails.
    // Ensure that a child context with a window is activated:
    IEclipseContext activeChild = application.getContext().getActiveChild();
    if (activeChild == null || activeChild.get(MTrimmedWindow.class) == null) {
      boolean activated = false;
      if (application.getContext() instanceof EclipseContext) {
        for (IEclipseContext child : ((EclipseContext) application.getContext()).getChildren()) {
          MTrimmedWindow window = child.get(MTrimmedWindow.class);
          if (window != null) {
            child.activate();
            activated = true;
            break;
          }
        }
      }
      if (!activated) {
        logger.error("Could not activate window for part instantiation"); // $NON-NLS-1$
        return;
      }
    }

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

    // reactivate ontop parts to ensure they are on-top
    for (MPart ontop : ontops) {
      partService.activate(ontop);
    }
  }
  /**
   * 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));
  }
 @Override
 public IServiceLocator createServiceLocator(
     IServiceLocator parent, AbstractServiceFactory factory, IDisposable owner) {
   ServiceLocator serviceLocator = new ServiceLocator(parent, factory, owner);
   // System.err.println("parentLocator: " + parent); //$NON-NLS-1$
   if (parent != null) {
     IEclipseContext ctx = parent.getService(IEclipseContext.class);
     if (ctx != null) {
       serviceLocator.setContext(ctx.createChild());
     }
   }
   return serviceLocator;
 }
 /**
  * Fill in a temporary static context for execution.
  *
  * @param command
  * @return a context not part of the normal hierarchy
  */
 private void addParms(ParameterizedCommand command, IEclipseContext staticContext) {
   final Map parms = command.getParameterMap();
   Iterator i = parms.entrySet().iterator();
   while (i.hasNext()) {
     Map.Entry entry = (Map.Entry) i.next();
     String parameterId = (String) entry.getKey();
     staticContext.set(
         parameterId,
         convertParameterValue(command.getCommand(), parameterId, (String) entry.getValue()));
   }
   staticContext.set(PARM_MAP, parms);
   staticContext.set(ParameterizedCommand.class, command);
 }
  /** Tests the Registration of an Event Hanlder in the event broker of the eclpse context. */
  @Test
  public void testEventBrokerEventHanlderRegistration() {
    TestProtocolService protocolService = new TestProtocolService();
    IEclipseContext context = EclipseContextFactory.create();
    final Map<String, EventHandler> topics = new HashMap<String, EventHandler>();
    context.set(
        IEventBroker.class,
        new IEventBroker() {

          @Override
          public boolean send(String topic, Object data) {
            return false;
          }

          @Override
          public boolean post(String topic, Object data) {
            return false;
          }

          @Override
          public boolean subscribe(String topic, EventHandler eventHandler) {
            topics.put(topic, eventHandler);
            return true;
          }

          @Override
          public boolean subscribe(
              String topic, String filter, EventHandler eventHandler, boolean headless) {
            return false;
          }

          @Override
          public boolean unsubscribe(EventHandler eventHandler) {
            return false;
          }
        });
    protocolService.compute(context, null);
    EventHandler handler =
        topics.get(TestEditorCoreEventConstants.TESTSTRUCTURE_MODEL_CHANGED_DELETED);
    assertNotNull("Hanlder should be registered", handler);
    TestCase testCase = new TestCase();
    testCase.setName("TestCase1");
    protocolService.set(testCase, new TestResult());
    assertNotNull(protocolService.get(testCase));
    Map<String, String> properties = new HashMap<String, String>();
    properties.put("org.eclipse.e4.data", testCase.getFullName());
    Event event =
        new Event(TestEditorCoreEventConstants.TESTSTRUCTURE_MODEL_CHANGED_DELETED, properties);
    handler.handleEvent(event);
    assertNull(protocolService.get(testCase));
  }
 private IEclipseContext getStaticContext() {
   if (infoContext == null) {
     IEclipseContext parentContext = renderer.getContext(toolbarModel);
     if (parentContext != null) {
       infoContext = parentContext.createChild(STATIC_CONTEXT);
     } else {
       infoContext = EclipseContextFactory.create(STATIC_CONTEXT);
     }
     ContributionsAnalyzer.populateModelInterfaces(
         toolbarModel, infoContext, toolbarModel.getClass().getInterfaces());
     infoContext.set(ToolBarRenderer.class, renderer);
   }
   return infoContext;
 }
        public void selectionChanged(MPart part, Object selection) {
          selection = createCompatibilitySelection(selection);
          context.set(ISources.ACTIVE_CURRENT_SELECTION_NAME, selection);

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

          Object client = part.getObject();
          if (client instanceof CompatibilityPart) {
            IWorkbenchPart workbenchPart = ((CompatibilityPart) client).getPart();
            notifyListeners(part.getElementId(), workbenchPart, (ISelection) selection);
          }
        }
 @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");
   }
 }
示例#23
0
 /**
  * Dispatch the given object to a dispatch handler if a matching filter can be found for the
  * object's class. The dispatch handler is instantiated using the {@link ContextInjectionFactory},
  * which injects the handler using the provided context.
  *
  * @param object Object to dispatch
  * @param intent Intent that loaded the dispatched object, <code>null</code> if object is not the
  *     result of an intent
  * @param context Context to use for injection into the handler
  * @return True if a dispatch handler was found to handle the object
  */
 public boolean dispatch(Object object, Intent intent, IEclipseContext context) {
   if (object == null) {
     return false;
   }
   DispatchFilter filter = findFilter(object);
   Class<? extends IDispatchHandler> handlerClass = filter == null ? null : filter.getHandler();
   if (handlerClass == null) {
     logger.error("Could not find dispatch handler for object: " + object); // $NON-NLS-1$
     return false;
   }
   IEclipseContext activeLeaf = context.getActiveLeaf();
   IEclipseContext child = activeLeaf.createChild();
   IDispatchHandler handler = ContextInjectionFactoryThreadSafe.make(handlerClass, child);
   handler.handle(object, intent);
   return true;
 }
示例#24
0
  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);
  }
 /*
  * (non-Javadoc)
  *
  * @see junit.framework.TestCase#tearDown()
  */
 @Override
 protected void tearDown() throws Exception {
   if (wb != null) {
     wb.close();
   }
   appContext.dispose();
 }
 @Override
 public void initialize(String nodeID, IEclipseContext context) {
   alternative = (InputAlternative) context.get(IEditorInputResource.class);
   if (alternative != null) {
     alternative.addPropertyChangeListener(projectListener);
   }
 }
  public void testCreateView() {
    final MWindow window = createWindowWithOneView("Part Name");

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

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

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

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

    assertFalse(part.isDirty());

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

    part.setDirty(false);
    assertEquals("Part Name", item.getText());
  }
 @After
 public void tearDown() throws Exception {
   if (wb != null) {
     wb.close();
   }
   appContext.dispose();
 }
  /**
   * 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;
  }
 @Override
 public int hashCode() {
   final int prime = 31;
   int hashRresult = 1;
   hashRresult = prime * hashRresult + ((context == null) ? 0 : context.hashCode());
   hashRresult = prime * hashRresult + ((requestor == null) ? 0 : requestor.hashCode());
   return hashRresult;
 }