/**
   * @param appContext
   * @return
   */
  private URI determineApplicationModelURI(IApplicationContext appContext) {
    Optional<String> appModelPath = getArgValue(IWorkbench.XMI_URI_ARG, appContext, false);

    String appModelPathValue =
        appModelPath
            .filter(path -> !path.isEmpty())
            .orElseGet(
                () -> {
                  Bundle brandingBundle = appContext.getBrandingBundle();
                  if (brandingBundle != null) {
                    return brandingBundle.getSymbolicName()
                        + "/"
                        + E4Application.APPLICATION_MODEL_PATH_DEFAULT;
                  } else {
                    Logger logger = new WorkbenchLogger(PLUGIN_ID);
                    logger.error(
                        new Exception(),
                        "applicationXMI parameter not set and no branding plugin defined. "); //$NON-NLS-1$
                  }
                  return null;
                });

    URI applicationModelURI = null;

    // check if the appModelPath is already a platform-URI and if so use it
    if (URIHelper.isPlatformURI(appModelPathValue)) {
      applicationModelURI = URI.createURI(appModelPathValue, true);
    } else {
      applicationModelURI = URI.createPlatformPluginURI(appModelPathValue, true);
    }
    return applicationModelURI;
  }
 @Execute
 public void execute(
     @OSGiBundle BundleContext bundleContext,
     @Named(PLUGIN_LOCATION_PARAMETER) String pluginLocation,
     @Optional Logger logger) {
   try {
     URL fileURL = FileLocator.toFileURL(new URL(pluginLocation));
     String refLocation = "reference:" + fileURL.toExternalForm();
     Bundle installedBundle = bundleContext.installBundle(refLocation);
     installedBundle.start(Bundle.START_TRANSIENT);
     Activator.getDefault().addDynamicBundle(installedBundle);
   } catch (BundleException e) {
     if (logger != null) {
       logger.warn(e, "Failed to load plugin from: " + pluginLocation);
     }
   } catch (MalformedURLException e) {
     if (logger != null) {
       logger.warn(e, "Failed to load plugin from: " + pluginLocation);
     }
   } catch (IOException e) {
     if (logger != null) {
       logger.warn(e, "Failed to load plugin from: " + pluginLocation);
     }
   }
 }
  /**
   * Look at the argument URL for the workspace's version information. Return that version if found
   * and null otherwise.
   */
  private static String readWorkspaceVersion(URL workspace) {
    File versionFile = getVersionFile(workspace, false);
    if (versionFile == null || !versionFile.exists()) {
      return null;
    }

    try {
      // Although the version file is not spec'ed to be a Java properties
      // file, it happens to follow the same format currently, so using
      // Properties to read it is convenient.
      Properties props = new Properties();
      FileInputStream is = new FileInputStream(versionFile);
      try {
        props.load(is);
      } finally {
        is.close();
      }

      return props.getProperty(WORKSPACE_VERSION_KEY);
    } catch (IOException e) {
      Logger logger = new WorkbenchLogger(PLUGIN_ID);
      logger.error(e);
      return null;
    }
  }
  /**
   * Write the version of the metadata into a known file overwriting any existing file contents.
   * Writing the version file isn't really crucial, so the function is silent about failure
   */
  private static void writeWorkspaceVersion() {
    Location instanceLoc = Platform.getInstanceLocation();
    if (instanceLoc == null || instanceLoc.isReadOnly()) {
      return;
    }

    File versionFile = getVersionFile(instanceLoc.getURL(), true);
    if (versionFile == null) {
      return;
    }

    OutputStream output = null;
    try {
      String versionLine = WORKSPACE_VERSION_KEY + '=' + WORKSPACE_VERSION_VALUE;

      output = new FileOutputStream(versionFile);
      output.write(versionLine.getBytes(StandardCharsets.UTF_8));
    } catch (IOException e) {
      Logger logger = new WorkbenchLogger(PLUGIN_ID);
      logger.error(e);
    } finally {
      try {
        if (output != null) {
          output.close();
        }
      } catch (IOException e) {
        // do nothing
      }
    }
  }
 private void log(String unidentifiedMessage, String identifiedMessage, String id, Exception e) {
   if (id == null || id.length() == 0) {
     logger.error(e, unidentifiedMessage);
   } else {
     logger.error(e, NLS.bind(identifiedMessage, id));
   }
 }
  /**
   * Simplified copy of IDEAplication processing that does not offer to choose a workspace location.
   */
  private boolean checkInstanceLocation(
      Location instanceLocation, Shell shell, IEclipseContext context) {

    // Eclipse has been run with -data @none or -data @noDefault options so
    // we don't need to validate the location
    if (instanceLocation == null && Boolean.FALSE.equals(context.get(IWorkbench.PERSIST_STATE))) {
      return true;
    }

    if (instanceLocation == null) {
      MessageDialog.openError(
          shell,
          WorkbenchSWTMessages.IDEApplication_workspaceMandatoryTitle,
          WorkbenchSWTMessages.IDEApplication_workspaceMandatoryMessage);
      return false;
    }

    // -data "/valid/path", workspace already set
    if (instanceLocation.isSet()) {
      // make sure the meta data version is compatible (or the user
      // has
      // chosen to overwrite it).
      if (!checkValidWorkspace(shell, instanceLocation.getURL())) {
        return false;
      }

      // at this point its valid, so try to lock it and update the
      // metadata version information if successful
      try {
        if (instanceLocation.lock()) {
          writeWorkspaceVersion();
          return true;
        }

        // we failed to create the directory.
        // Two possibilities:
        // 1. directory is already in use
        // 2. directory could not be created
        File workspaceDirectory = new File(instanceLocation.getURL().getFile());
        if (workspaceDirectory.exists()) {
          MessageDialog.openError(
              shell,
              WorkbenchSWTMessages.IDEApplication_workspaceCannotLockTitle,
              WorkbenchSWTMessages.IDEApplication_workspaceCannotLockMessage);
        } else {
          MessageDialog.openError(
              shell,
              WorkbenchSWTMessages.IDEApplication_workspaceCannotBeSetTitle,
              WorkbenchSWTMessages.IDEApplication_workspaceCannotBeSetMessage);
        }
      } catch (IOException e) {
        Logger logger = new WorkbenchLogger(PLUGIN_ID);
        logger.error(e);
        MessageDialog.openError(shell, WorkbenchSWTMessages.InternalError, e.getMessage());
      }
      return false;
    }
    return false;
  }
 private PreferenceNodeElement[] getElements() {
   final IConfigurationElement[] extensions =
       registry.getConfigurationElementsFor(PREF_EXTENSION_POINT);
   final PreferenceNodeElement[] elements = new PreferenceNodeElement[extensions.length];
   final int length = extensions.length;
   for (int i = 0; i < length; i++) {
     final PreferenceNodeElement nodeElement = new PreferenceNodeElement();
     nodeElement.name = extensions[i].getAttribute(PREF_PAGE_ATTR_NAME);
     nodeElement.className = extensions[i].getAttribute(PREF_PAGE_ATTR_CLASS);
     nodeElement.bundleID = extensions[i].getContributor().getName();
     nodeElement.id = extensions[i].getAttribute(PREF_PAGE_ATTR_ID);
     nodeElement.category = extensions[i].getAttribute(PREF_PAGE_ATTR_CATEGORY);
     if (nodeElement.id != null
         && nodeElement.name != null
         && nodeElement.className != null
         && nodeElement.bundleID != null) {
       elements[i] = nodeElement;
     } else {
       logger.warn(
           MessageFormat.format(
               "Couldn''t load the preferences extension for the page {0}, of the plugin {1}.",
               nodeElement.name, nodeElement.bundleID));
     }
   }
   Arrays.sort(elements);
   return elements;
 }
  /**
   * Initialize a part renderer from the extension point.
   *
   * @param context the context for the part factories
   */
  @PostConstruct
  void initialize(IEclipseContext context) {
    this.appContext = context;

    // initialize the correct key-binding display formatter
    KeyFormatterFactory.setDefault(SWTKeySupport.getKeyFormatterForPlatform());

    // Add the renderer to the context
    context.set(IPresentationEngine.class.getName(), this);

    IRendererFactory factory = null;
    IContributionFactory contribFactory = context.get(IContributionFactory.class);
    try {
      factory = (IRendererFactory) contribFactory.create(factoryUrl, context);
    } catch (Exception e) {
      logger.warn(e, "Could not create rendering factory");
    }

    // Try to load the default one
    if (factory == null) {
      try {
        factory = (IRendererFactory) contribFactory.create(defaultFactoryUrl, context);
      } catch (Exception e) {
        logger.error(e, "Could not create default rendering factory");
      }
    }

    if (factory == null) {
      throw new IllegalStateException("Could not create any rendering factory. Aborting ...");
    }

    curFactory = factory;
    context.set(IRendererFactory.class, curFactory);

    // Hook up the widget life-cycle subscriber
    if (eventBroker != null) {
      eventBroker.subscribe(UIEvents.UIElement.TOPIC_TOBERENDERED, toBeRenderedHandler);
      eventBroker.subscribe(UIEvents.UIElement.TOPIC_VISIBLE, visibilityHandler);
      eventBroker.subscribe(UIEvents.ElementContainer.TOPIC_CHILDREN, childrenHandler);
      eventBroker.subscribe(UIEvents.Window.TOPIC_WINDOWS, windowsHandler);
      eventBroker.subscribe(UIEvents.Perspective.TOPIC_WINDOWS, windowsHandler);
      eventBroker.subscribe(UIEvents.TrimmedWindow.TOPIC_TRIMBARS, trimHandler);
    }
  }
 @Override
 public boolean post(String topic, Object data) {
   Event event = constructEvent(topic, data);
   Activator activator = Activator.getDefault();
   if (activator == null) {
     if (logger != null) {
       logger.error(NLS.bind(ServiceMessages.NO_EVENT_ADMIN, event.toString()));
     }
     return false;
   }
   EventAdmin eventAdmin = activator.getEventAdmin();
   if (eventAdmin == null) {
     if (logger != null) {
       logger.error(NLS.bind(ServiceMessages.NO_EVENT_ADMIN, event.toString()));
     }
     return false;
   }
   eventAdmin.postEvent(event);
   return true;
 }
 @Execute
 void relationRemove(final IBrowserManager inBrowserManager) {
   try {
     final CentralAssociationsModel lModel = inBrowserManager.getCenterModel();
     final ItemAdapter[] lSelected = new ItemAdapter[] {inBrowserManager.getSelectedModel()};
     lModel.removeAssociations(lSelected);
     lModel.saveChanges();
     Display.getCurrent().beep();
   } catch (final BOMException exc) {
     log.error(exc, exc.getMessage());
   }
 }
  public void saveModel() {
    // Save the model into the targetURI
    if (lcManager != null && workbench != null) {
      ContextInjectionFactory.invoke(lcManager, PreSave.class, workbench.getContext(), null);
    }

    try {
      if (!(handler instanceof ResourceHandler)
          || ((ResourceHandler) handler).hasTopLevelWindows()) {
        handler.save();
      } else {
        Logger logger = new WorkbenchLogger(PLUGIN_ID);
        logger.error(
            new Exception(), // log a stack trace for debugging
            "Attempted to save a workbench model that had no top-level windows! " //$NON-NLS-1$
                + "Skipped saving the model to avoid corruption."); //$NON-NLS-1$
      }
    } catch (IOException e) {
      Logger logger = new WorkbenchLogger(PLUGIN_ID);
      logger.error(e, "Error saving the workbench model"); // $NON-NLS-1$
    }
  }
  @Override
  public boolean load() {
    if (sessionService == null) {
      // we abort
      logger.info("Aborting catalog " + params.getName() + " loading : session is not set yet");
      return false;
    }
    Session session = sessionService.getSession();
    logger.info(
        "[PadreCatalog] Session service instanciated. Session username is "
            + sessionService.getSession().getUsername());
    this.layertreeAsJsonNode = getLayertree();

    // if null, then it failed. We exit the function.
    if (this.layertreeAsJsonNode == null) {
      logger.error("ERROR parsing layertree (" + this.getClass().getName() + ")");
      return false;
    }

    // create a new local_ context
    IEclipseContext catalogContext = EclipseContextFactory.create();
    catalogState = new PadreCatalogState();
    catalogContext.set(PadreCatalogState.class, catalogState);

    // connect new local context with context hierarchy
    catalogContext.setParent(context);

    this.rootNode = ContextInjectionFactory.make(FolderNode.class, catalogContext);
    // this.rootNode = new FolderNode();
    this.rootNode.setName(params.getName());
    this.catalogState.addExpandedNode(this.rootNode);
    this.rootNode.loadFromJson(this.layertreeAsJsonNode);

    this.checkInitialNodes(this.catalogState.getCheckedNodes());

    return true;
  }
 @Execute
 public void execute(
     @OSGiBundle BundleContext bundleContext,
     @Named(PLUGIN_ID_PARAMETER) String pluginId,
     @Optional Logger logger) {
   Bundle bundle = Platform.getBundle(pluginId);
   if (bundle != null) {
     try {
       bundle.uninstall();
       Activator.getDefault().removeDynamicBundle(bundle);
     } catch (BundleException e) {
       logger.warn(e, "Failed to uninstall bundle " + bundle.getSymbolicName());
     }
   }
 }
 private void defineContexts(MBindingContext parent, MBindingContext current) {
   if (current.getName() == null || current.getElementId() == null) {
     logger.error("Binding context name or id is null for: " + current); // $NON-NLS-1$
     return;
   }
   Context context = contextManager.getContext(current.getElementId());
   if (!context.isDefined()) {
     String localizedName =
         LocalizationHelper.getLocalized(current.getName(), current, application.getContext());
     String localizedDescriptor =
         LocalizationHelper.getLocalized(
             current.getDescription(), current, application.getContext());
     context.define(
         localizedName, localizedDescriptor, parent == null ? null : parent.getElementId());
   }
   for (MBindingContext child : current.getChildren()) {
     defineContexts(current, child);
   }
 }
 @Override
 public boolean subscribe(
     String topic, String filter, EventHandler eventHandler, boolean headless) {
   BundleContext bundleContext = Activator.getDefault().getBundleContext();
   if (bundleContext == null) {
     if (logger != null) {
       logger.error(NLS.bind(ServiceMessages.NO_BUNDLE_CONTEXT, topic));
     }
     return false;
   }
   String[] topics = new String[] {topic};
   Dictionary<String, Object> d = new Hashtable<String, Object>();
   d.put(EventConstants.EVENT_TOPIC, topics);
   if (filter != null) d.put(EventConstants.EVENT_FILTER, filter);
   EventHandler wrappedHandler = new UIEventHandler(eventHandler, headless ? null : uiSync);
   ServiceRegistration<?> registration =
       bundleContext.registerService(EventHandler.class.getName(), wrappedHandler, d);
   Collection<ServiceRegistration<?>> handled = registrations.get(eventHandler);
   if (handled == null) {
     registrations.put(eventHandler, handled = new ArrayList<ServiceRegistration<?>>());
   }
   handled.add(registration);
   return true;
 }
 private void warn(String message) {
   Logger logger = appContext.get(Logger.class);
   if (logger != null) {
     logger.warn(message);
   }
 }
  /*
   * (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(MUIElement element, Object parent) {
    if (!(element instanceof MMenu)) return null;

    final MMenu menuModel = (MMenu) element;
    Menu newMenu = null;
    MenuManager menuManager = null;
    boolean menuBar = false;

    if (parent instanceof Decorations) {
      MUIElement container = (MUIElement) ((EObject) element).eContainer();
      if (container instanceof MWindow) {
        menuManager = getManager(menuModel);
        if (menuManager == null) {
          menuManager = new MenuManager(NO_LABEL, menuModel.getElementId());
          linkModelToManager(menuModel, menuManager);
        }
        newMenu = menuManager.createMenuBar((Decorations) parent);
        ((Decorations) parent).setMenuBar(newMenu);
        newMenu.setData(menuManager);
        menuBar = true;
      } else {
        menuManager = getManager(menuModel);
        if (menuManager == null) {
          menuManager = new MenuManager(NO_LABEL, menuModel.getElementId());
          linkModelToManager(menuModel, menuManager);
        }
        newMenu = menuManager.createContextMenu((Control) parent);
        // we can't be sure this is the correct parent.
        // ((Control) parent).setMenu(newMenu);
        newMenu.setData(menuManager);
      }
    } else if (parent instanceof Menu) {
      // Object data = ((Menu) parent).getData();
      logger.debug(
          new Exception(),
          "Trying to render a sub menu " //$NON-NLS-1$
              + menuModel
              + "\n\t"
              + parent); //$NON-NLS-1$
      return null;

    } else if (parent instanceof Control) {
      menuManager = getManager(menuModel);
      if (menuManager == null) {
        menuManager = new MenuManager(NO_LABEL, menuModel.getElementId());
        linkModelToManager(menuModel, menuManager);
      }
      newMenu = menuManager.createContextMenu((Control) parent);
      // we can't be sure this is the correct parent.
      // ((Control) parent).setMenu(newMenu);
      newMenu.setData(menuManager);
    }
    if (!menuManager.getRemoveAllWhenShown()) {
      processContributions(menuModel, menuBar, menuModel instanceof MPopupMenu);
    }
    if (newMenu != null) {
      newMenu.addDisposeListener(
          new DisposeListener() {
            public void widgetDisposed(DisposeEvent e) {
              cleanUp(menuModel);
            }
          });
    }
    return newMenu;
  }
  private void safeRemoveGui(MUIElement element) {
    if (removeRoot == null) removeRoot = element;
    renderedElements.remove(element);

    // We call 'hideChild' *before* checking if the actual element
    // has been rendered in order to pick up cases of 'lazy loading'
    MUIElement parent = element.getParent();
    AbstractPartRenderer parentRenderer = parent != null ? getRendererFor(parent) : null;
    if (parentRenderer != null) {
      parentRenderer.hideChild(element.getParent(), element);
    }

    AbstractPartRenderer renderer = getRendererFor(element);

    // If the element hasn't been rendered then this is a NO-OP
    if (renderer != null) {

      if (element instanceof MElementContainer<?>) {
        MElementContainer<MUIElement> container = (MElementContainer<MUIElement>) element;
        MUIElement selectedElement = container.getSelectedElement();
        List<MUIElement> children = container.getChildren();
        for (MUIElement child : children) {
          // remove stuff in the "back" first
          if (child != selectedElement) {
            removeGui(child);
          }
        }

        if (selectedElement != null && children.contains(selectedElement)) {
          // now remove the selected element
          removeGui(selectedElement);
        }
      }

      if (element instanceof MPerspective) {
        MPerspective perspective = (MPerspective) element;
        for (MWindow subWindow : perspective.getWindows()) {
          removeGui(subWindow);
        }
      } else if (element instanceof MWindow) {
        MWindow window = (MWindow) element;
        for (MWindow subWindow : window.getWindows()) {
          removeGui(subWindow);
        }

        if (window instanceof MTrimmedWindow) {
          MTrimmedWindow trimmedWindow = (MTrimmedWindow) window;
          for (MUIElement trimBar : trimmedWindow.getTrimBars()) {
            removeGui(trimBar);
          }
        }
      }

      if (element instanceof MContribution) {
        MContribution contribution = (MContribution) element;
        Object client = contribution.getObject();
        IEclipseContext parentContext = renderer.getContext(element);
        if (parentContext != null && client != null) {
          try {
            ContextInjectionFactory.invoke(client, PersistState.class, parentContext, null);
          } catch (Exception e) {
            if (logger != null) {
              logger.error(e);
            }
          }
        }
      }

      renderer.disposeWidget(element);

      // unset the client object
      if (element instanceof MContribution) {
        MContribution contribution = (MContribution) element;
        Object client = contribution.getObject();
        IEclipseContext parentContext = renderer.getContext(element);
        if (parentContext != null && client != null) {
          try {
            ContextInjectionFactory.uninject(client, parentContext);
          } catch (Exception e) {
            if (logger != null) {
              logger.error(e);
            }
          }
        }
        contribution.setObject(null);
      }

      // dispose the context
      if (element instanceof MContext) {
        clearContext((MContext) element);
      }
    }

    if (removeRoot == element) removeRoot = null;
  }