void createCommand(String commandId, Map parameters) {
    if (commandId == null) {
      WorkbenchPlugin.log(
          "Unable to create menu item \""
              + getId() //$NON-NLS-1$
              + "\", no command id"); //$NON-NLS-1$
      return;
    }
    Command cmd = commandService.getCommand(commandId);
    if (!cmd.isDefined()) {
      WorkbenchPlugin.log(
          "Unable to create menu item \""
              + getId() //$NON-NLS-1$
              + "\", command \""
              + commandId
              + "\" not defined"); //$NON-NLS-1$ //$NON-NLS-2$
      return;
    }

    if (parameters == null || parameters.size() == 0) {
      command = new ParameterizedCommand(cmd, null);
      return;
    }

    try {
      ArrayList parmList = new ArrayList();
      Iterator i = parameters.entrySet().iterator();
      while (i.hasNext()) {
        Map.Entry entry = (Map.Entry) i.next();
        String parmName = (String) entry.getKey();
        IParameter parm;
        parm = cmd.getParameter(parmName);
        if (parm == null) {
          WorkbenchPlugin.log(
              "Unable to create menu item \""
                  + getId() //$NON-NLS-1$
                  + "\", parameter \""
                  + parmName
                  + "\" for command \"" //$NON-NLS-1$ //$NON-NLS-2$
                  + commandId
                  + "\" is not defined"); //$NON-NLS-1$
          return;
        }
        parmList.add(new Parameterization(parm, (String) entry.getValue()));
      }
      command =
          new ParameterizedCommand(
              cmd, (Parameterization[]) parmList.toArray(new Parameterization[parmList.size()]));
    } catch (NotDefinedException e) {
      // this shouldn't happen as we checked for !defined, but we
      // won't take the chance
      WorkbenchPlugin.log(
          "Failed to create menu item " //$NON-NLS-1$
              + getId(),
          e);
    }
  }
Example #2
0
 public final void savePreferences(final Scheme activeScheme, final Binding[] bindings)
     throws IOException {
   BindingPersistence.write(activeScheme, bindings);
   try {
     bindingManager.setActiveScheme(activeScheme);
   } catch (final NotDefinedException e) {
     WorkbenchPlugin.log(
         "The active scheme is not currently defined.", //$NON-NLS-1$
         WorkbenchPlugin.getStatus(e));
   }
   bindingManager.setBindings(bindings);
 }
  /* (non-Javadoc)
   * @see org.eclipse.ui.internal.wizards.preferences.WizardPreferencesPage#getTransfers()
   */
  protected PreferenceTransferElement[] getTransfers() {
    if (validFromFile()) {
      FileInputStream fis;

      try {
        fis = new FileInputStream(getDestinationValue());
      } catch (FileNotFoundException e) {
        WorkbenchPlugin.log(e.getMessage(), e);
        return new PreferenceTransferElement[0];
      }
      IPreferencesService service = Platform.getPreferencesService();
      try {
        IExportedPreferences prefs;
        prefs = service.readPreferences(fis);
        PreferenceTransferElement[] transfers = super.getTransfers();
        IPreferenceFilter[] filters = new IPreferenceFilter[transfers.length];
        for (int i = 0; i < transfers.length; i++) {
          PreferenceTransferElement transfer = transfers[i];
          filters[i] = transfer.getFilter();
        }
        IPreferenceFilter[] matches = service.matches(prefs, filters);
        PreferenceTransferElement[] returnTransfers = new PreferenceTransferElement[matches.length];
        int index = 0;
        for (int i = 0; i < matches.length; i++) {
          IPreferenceFilter filter = matches[i];
          for (int j = 0; j < transfers.length; j++) {
            PreferenceTransferElement element = transfers[j];
            if (element.getFilter().equals(filter)) {
              returnTransfers[index++] = element;
            }
          }
        }

        PreferenceTransferElement[] destTransfers = new PreferenceTransferElement[index];
        System.arraycopy(returnTransfers, 0, destTransfers, 0, index);
        return destTransfers;
      } catch (CoreException e) {
        // Do not log core exceptions, they indicate the chosen file is not valid
        // WorkbenchPlugin.log(e.getMessage(), e);
      } finally {
        try {
          fis.close();
        } catch (IOException e) {
          WorkbenchPlugin.log(e.getMessage(), e);
        }
      }
    }

    return new PreferenceTransferElement[0];
  }
  /**
   * @param filters
   * @return <code>true</code> if the transfer was succesful, and <code>false</code> otherwise
   */
  protected boolean transfer(IPreferenceFilter[] filters) {
    File importFile = new File(getDestinationValue());
    FileInputStream fis = null;
    try {
      if (filters.length > 0) {
        try {
          fis = new FileInputStream(importFile);
        } catch (FileNotFoundException e) {
          WorkbenchPlugin.log(e.getMessage(), e);
          MessageDialog.open(
              MessageDialog.ERROR,
              getControl().getShell(),
              new String(),
              e.getLocalizedMessage(),
              SWT.SHEET);
          return false;
        }
        IPreferencesService service = Platform.getPreferencesService();
        try {
          IExportedPreferences prefs = service.readPreferences(fis);

          service.applyPreferences(prefs, filters);
        } catch (CoreException e) {
          WorkbenchPlugin.log(e.getMessage(), e);
          MessageDialog.open(
              MessageDialog.ERROR,
              getControl().getShell(),
              new String(),
              e.getLocalizedMessage(),
              SWT.SHEET);
          return false;
        }
      }
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
          WorkbenchPlugin.log(e.getMessage(), e);
          MessageDialog.open(
              MessageDialog.ERROR,
              getControl().getShell(),
              new String(),
              e.getLocalizedMessage(),
              SWT.SHEET);
        }
      }
    }
    return true;
  }
  /**
   * @param definitions
   * @return
   */
  private static FontDefinition[] addDefaulted(FontDefinition[] definitions) {
    IThemeRegistry registry = WorkbenchPlugin.getDefault().getThemeRegistry();
    FontDefinition[] allDefs = registry.getFonts();

    SortedSet set = addDefaulted(definitions, allDefs);
    return (FontDefinition[]) set.toArray(new FontDefinition[set.size()]);
  }
 /**
  * Handle calls <i>from</i> Javascript functions on the browser. (This is called by reflection by
  * JavaFx so there won't be any apparent usages for this method.)
  *
  * @param functionId
  * @param argument
  */
 public void call(String functionId, String argument) {
   try {
     IConfigurationElement element =
         BrowserExtensions.getExtension(
             BrowserExtensions.EXTENSION_ID_BROWSER_TO_ECLIPSE,
             functionId,
             view.getEngine().locationProperty().get());
     if (element != null) {
       IBrowserToEclipseFunction function =
           (IBrowserToEclipseFunction)
               WorkbenchPlugin.createExtension(element, BrowserExtensions.ELEMENT_CLASS);
       function.call(argument);
     } else {
       StatusManager.getManager()
           .handle(
               new Status(
                   IStatus.ERROR,
                   IdeUiPlugin.PLUGIN_ID,
                   "Could not instantiate browser function extension: " + functionId));
     }
   } catch (CoreException ex) {
     StatusManager.getManager()
         .handle(
             new Status(
                 IStatus.ERROR, IdeUiPlugin.PLUGIN_ID, "Could not find dashboard extension", ex));
     return;
   }
 }
  private void adjustOutsideActions() {
    final ActionSetRegistry reg = WorkbenchPlugin.getDefault().getActionSetRegistry();
    final IActionSetDescriptor[] actionSets = reg.getActionSets();
    final String[] removeActionSets =
        new String[] {
          "org.eclipse.search.searchActionSet", "org.eclipse.ui.cheatsheets.actionSet",
          "org.eclipse.ui.actionSet.keyBindings", "org.eclipse.ui.edit.text.actionSet.navigation",
          "org.eclipse.ui.edit.text.actionSet.annotationNavigation",
              "org.eclipse.ui.edit.text.actionSet.convertLineDelimitersTo",
          "org.eclipse.ui.edit.text.actionSet.openExternalFile",
              "org.eclipse.ui.externaltools.ExternalToolsSet",
          "org.eclipse.ui.WorkingSetActionSet", "org.eclipse.update.ui.softwareUpdates",
          "org.eclipse.ui.actionSet.openFiles", "org.eclipse.mylyn.tasks.ui.navigation",
        };

    for (int i = 0; i < actionSets.length; i++) {
      boolean found = false;
      for (int j = 0; j < removeActionSets.length; j++) {
        if (removeActionSets[j].equals(actionSets[i].getId())) {
          found = true;
        }
      }
      if (!found) {
        continue;
      }
      final IExtension ext = actionSets[i].getConfigurationElement().getDeclaringExtension();
      reg.removeExtension(ext, new Object[] {actionSets[i]});
    }
  }
 public AbstractSourceProvider[] getSourceProviders() {
   ArrayList providers = new ArrayList();
   IExtensionPoint ep = getExtensionPoint();
   IConfigurationElement[] elements = ep.getConfigurationElements();
   for (int i = 0; i < elements.length; i++) {
     if (elements[i].getName().equals(IWorkbenchRegistryConstants.TAG_SOURCE_PROVIDER)) {
       try {
         Object sourceProvider =
             elements[i].createExecutableExtension(IWorkbenchRegistryConstants.ATTR_PROVIDER);
         if (!(sourceProvider instanceof AbstractSourceProvider)) {
           String attributeName =
               elements[i].getAttribute(IWorkbenchRegistryConstants.ATTR_PROVIDER);
           final String message =
               "Source Provider '"
                   + //$NON-NLS-1$
                   attributeName
                   + "' should extend AbstractSourceProvider"; //$NON-NLS-1$
           final IStatus status = new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, message);
           WorkbenchPlugin.log(status);
           continue;
         }
         providers.add(sourceProvider);
         processVariables(elements[i].getChildren(IWorkbenchRegistryConstants.TAG_VARIABLE));
       } catch (CoreException e) {
         StatusManager.getManager().handle(e.getStatus());
       }
     }
   }
   return (AbstractSourceProvider[])
       providers.toArray(new AbstractSourceProvider[providers.size()]);
 }
 public void setClient(WebView view) {
   this.view = view;
   this.engine = view.getEngine();
   JSObject window = (JSObject) engine.executeScript("window");
   window.setMember("ide", this);
   Collection<IEclipseToBrowserFunction> onLoadFunctions =
       new ArrayList<IEclipseToBrowserFunction>();
   IConfigurationElement[] extensions =
       BrowserExtensions.getExtensions(
           BrowserExtensions.EXTENSION_ID_ECLIPSE_TO_BROWSER,
           null,
           view.getEngine().locationProperty().get());
   for (IConfigurationElement element : extensions) {
     try {
       String onLoad = element.getAttribute(BrowserExtensions.ELEMENT_ONLOAD);
       if (onLoad != null && onLoad.equals("true")) {
         onLoadFunctions.add(
             (IEclipseToBrowserFunction)
                 WorkbenchPlugin.createExtension(element, BrowserExtensions.ELEMENT_CLASS));
       }
     } catch (CoreException ex) {
       StatusManager.getManager()
           .handle(
               new Status(
                   IStatus.ERROR,
                   IdeUiPlugin.PLUGIN_ID,
                   "Could not instantiate browser element provider extension.",
                   ex));
       return;
     }
   }
   callOnBrowser(onLoadFunctions);
 }
  /**
   * Tests whether the preference store will be read automatically when a change to the preference
   * store is made.
   *
   * @throws ParseException If "ALT+SHIFT+Q A" cannot be parsed by KeySequence.
   */
  public final void testAutoLoad() throws ParseException {
    // Get the services.
    ICommandService commandService = (ICommandService) fWorkbench.getAdapter(ICommandService.class);
    IBindingService bindingService = (IBindingService) fWorkbench.getAdapter(IBindingService.class);
    bindingService.readRegistryAndPreferences(commandService);

    // Check the pre-conditions.
    final String emacsSchemeId = EMACS_SCHEME_ID;
    assertFalse(
        "The active scheme should be Emacs yet",
        emacsSchemeId.equals(bindingService.getActiveScheme().getId()));
    final KeySequence formalKeySequence = KeySequence.getInstance("ALT+SHIFT+Q A");
    final String commandId = "org.eclipse.ui.views.showView";
    Binding[] bindings = bindingService.getBindings();
    int i;
    for (i = 0; i < bindings.length; i++) {
      final Binding binding = bindings[i];
      if ((binding.getType() == Binding.USER)
          && (formalKeySequence.equals(binding.getTriggerSequence()))) {
        final ParameterizedCommand command = binding.getParameterizedCommand();
        final String actualCommandId = (command == null) ? null : command.getCommand().getId();
        assertFalse("The command should not yet be bound", commandId.equals(actualCommandId));
        break;
      }
    }
    assertEquals("There shouldn't be a matching command yet", bindings.length, i);

    // Modify the preference store.
    final IPreferenceStore store = WorkbenchPlugin.getDefault().getPreferenceStore();
    store.setValue(
        "org.eclipse.ui.commands",
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?><org.eclipse.ui.commands><activeKeyConfiguration keyConfigurationId=\""
            + emacsSchemeId
            + "\"/><keyBinding commandId=\""
            + commandId
            + "\" contextId=\"org.eclipse.ui.contexts.window\" keyConfigurationId=\"org.eclipse.ui.defaultAcceleratorConfiguration\" keySequence=\""
            + formalKeySequence
            + "\"/></org.eclipse.ui.commands>");

    // Check that the values have changed.
    assertEquals(
        "The active scheme should now be Emacs",
        emacsSchemeId,
        bindingService.getActiveScheme().getId());
    bindings = bindingService.getBindings();
    for (i = 0; i < bindings.length; i++) {
      final Binding binding = bindings[i];
      if ((binding.getType() == Binding.USER)
          && (formalKeySequence.equals(binding.getTriggerSequence()))) {
        final ParameterizedCommand command = binding.getParameterizedCommand();
        final String actualCommandId = (command == null) ? null : command.getCommand().getId();
        assertEquals("The command should be bound to 'ALT+SHIFT+Q A'", commandId, actualCommandId);
        break;
      }
    }
    assertFalse("There should be a matching command now", (bindings.length == i));
  }
  /**
   * Return the definitions that should have their default preference value set but nothing else.
   *
   * @param definitions the definitions that will be fully handled
   * @return the remaining definitions that should be defaulted
   */
  private static FontDefinition[] getDefaults(FontDefinition[] definitions) {
    IThemeRegistry registry = WorkbenchPlugin.getDefault().getThemeRegistry();
    FontDefinition[] allDefs = registry.getFonts();

    SortedSet set = new TreeSet(IThemeRegistry.ID_COMPARATOR);
    set.addAll(Arrays.asList(allDefs));
    set.removeAll(Arrays.asList(definitions));
    return (FontDefinition[]) set.toArray(new FontDefinition[set.size()]);
  }
 protected void firePartPropertyChanged(String key, String oldValue, String newValue) {
   final PropertyChangeEvent event = new PropertyChangeEvent(this, key, oldValue, newValue);
   Object[] l = partChangeListeners.getListeners();
   for (int i = 0; i < l.length; i++) {
     try {
       ((IPropertyChangeListener) l[i]).propertyChange(event);
     } catch (RuntimeException e) {
       WorkbenchPlugin.log(e);
     }
   }
 }
 /**
  * Fires a property changed event.
  *
  * @param propertyId the id of the property that changed
  */
 protected void firePropertyChange(final int propertyId) {
   Object[] array = getListeners();
   for (int nX = 0; nX < array.length; nX++) {
     final IPropertyListener l = (IPropertyListener) array[nX];
     try {
       l.propertyChanged(WorkbenchPart.this, propertyId);
     } catch (RuntimeException e) {
       WorkbenchPlugin.log(e);
     }
   }
 }
 public ExportBarWizard() {
   setDefaultPageImageDescriptor(Pics.getWizban());
   setNeedsProgressMonitor(true);
   IDialogSettings workbenchSettings = WorkbenchPlugin.getDefault().getDialogSettings();
   IDialogSettings wizardSettings = workbenchSettings.getSection("ExportBarWizard"); // $NON-NLS-1$
   if (wizardSettings == null) {
     wizardSettings = workbenchSettings.addNewSection("ExportBarWizard"); // $NON-NLS-1$
   }
   setDialogSettings(wizardSettings);
   setWindowTitle(Messages.buildTitle);
 }
  @Override
  protected IDialogSettings getDialogBoundsSettings() {
    final String settingsName = getClass().getCanonicalName();

    IDialogSettings workbenchSettings = WorkbenchPlugin.getDefault().getDialogSettings();
    IDialogSettings section = workbenchSettings.getSection(settingsName);

    if (section == null) {
      section = workbenchSettings.addNewSection(settingsName);
    }

    return section;
  }
  /**
   * Create a new instance of this class.
   *
   * @param composite parent composite
   * @param currentSelection the initial working set selection to pass to the {@link
   *     WorkingSetConfigurationBlock}
   * @param workingSetTypes the types of working sets that can be selected by the {@link
   *     WorkingSetConfigurationBlock}
   */
  public WorkingSetGroup(
      Composite composite, IStructuredSelection currentSelection, String[] workingSetTypes) {
    Group workingSetGroup = new Group(composite, SWT.NONE);
    workingSetGroup.setFont(composite.getFont());
    workingSetGroup.setText(WorkbenchMessages.WorkingSetGroup_WorkingSets_group);
    workingSetGroup.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
    workingSetGroup.setLayout(new GridLayout(1, false));

    workingSetBlock =
        new WorkingSetConfigurationBlock(
            WorkbenchPlugin.getDefault().getDialogSettings(), workingSetTypes);
    workingSetBlock.setWorkingSets(workingSetBlock.findApplicableWorkingSets(currentSelection));
    workingSetBlock.createContent(workingSetGroup);
  }
Example #17
0
  private ServiceFactoryHandle loadFromRegistry(Class key) {
    ServiceFactoryHandle result = null;
    IConfigurationElement[] serviceFactories = getExtensionPoint().getConfigurationElements();
    try {
      final String requestedName = key.getName();
      boolean done = false;
      for (int i = 0; i < serviceFactories.length && !done; i++) {
        final IConfigurationElement[] serviceNameElements =
            serviceFactories[i].getChildren(IWorkbenchRegistryConstants.TAG_SERVICE);
        for (int j = 0; j < serviceNameElements.length && !done; j++) {
          String serviceName =
              serviceNameElements[j].getAttribute(IWorkbenchRegistryConstants.ATTR_SERVICE_CLASS);
          if (requestedName.equals(serviceName)) {
            done = true;
          }
        }
        if (done) {
          final AbstractServiceFactory f =
              (AbstractServiceFactory)
                  serviceFactories[i].createExecutableExtension(
                      IWorkbenchRegistryConstants.ATTR_FACTORY_CLASS);
          ServiceFactoryHandle handle = new ServiceFactoryHandle(f);
          PlatformUI.getWorkbench()
              .getExtensionTracker()
              .registerObject(
                  serviceFactories[i].getDeclaringExtension(), handle, IExtensionTracker.REF_WEAK);

          List serviceNames = new ArrayList();
          for (int j = 0; j < serviceNameElements.length; j++) {
            String serviceName =
                serviceNameElements[j].getAttribute(IWorkbenchRegistryConstants.ATTR_SERVICE_CLASS);
            if (factories.containsKey(serviceName)) {
              WorkbenchPlugin.log(
                  "Factory already exists for " //$NON-NLS-1$
                      + serviceName);
            } else {
              factories.put(serviceName, handle);
              serviceNames.add(serviceName);
            }
          }
          handle.serviceNames = (String[]) serviceNames.toArray(new String[serviceNames.size()]);
          result = handle;
        }
      }
    } catch (CoreException e) {
      StatusManager.getManager().handle(e.getStatus());
    }
    return result;
  }
  private void handleWidgetSelection(Event event) {
    // Special check for ToolBar dropdowns...
    if (openDropDownMenu(event)) return;

    if ((style & (SWT.TOGGLE | SWT.CHECK)) != 0) {
      if (event.widget instanceof ToolItem) {
        checkedState = ((ToolItem) event.widget).getSelection();
      } else if (event.widget instanceof MenuItem) {
        checkedState = ((MenuItem) event.widget).getSelection();
      }
    }

    try {
      handlerService.executeCommand(command, event);
    } catch (ExecutionException e) {
      WorkbenchPlugin.log(
          "Failed to execute item " //$NON-NLS-1$
              + getId(),
          e);
    } catch (NotDefinedException e) {
      WorkbenchPlugin.log(
          "Failed to execute item " //$NON-NLS-1$
              + getId(),
          e);
    } catch (NotEnabledException e) {
      WorkbenchPlugin.log(
          "Failed to execute item " //$NON-NLS-1$
              + getId(),
          e);
    } catch (NotHandledException e) {
      WorkbenchPlugin.log(
          "Failed to execute item " //$NON-NLS-1$
              + getId(),
          e);
    }
  }
Example #19
0
 /* (non-Javadoc)
  * Method declared on DropTargetAdapter.
  * The user has dropped something on the desktop viewer.
  */
 public void drop(DropTargetEvent event) {
   try {
     if (PluginTransfer.getInstance().isSupportedType(event.currentDataType)) {
       PluginTransferData pluginData = (PluginTransferData) event.data;
       IDropActionDelegate delegate = getPluginAdapter(pluginData);
       if (!delegate.run(pluginData.getData(), getCurrentTarget())) {
         event.detail = DND.DROP_NONE;
       }
     } else {
       super.drop(event);
     }
   } catch (CoreException e) {
     WorkbenchPlugin.log("Drop Failed", e.getStatus()); // $NON-NLS-1$
   }
 }
 public void mergeIntoModel(
     ArrayList<MMenuContribution> menuContributions,
     ArrayList<MToolBarContribution> toolBarContributions,
     ArrayList<MTrimContribution> trimContributions) {
   if (location.getPath() == null || location.getPath().length() == 0) {
     WorkbenchPlugin.log(
         "MenuFactoryGenerator.mergeIntoModel: Invalid menu URI: " + location); // $NON-NLS-1$
     return;
   }
   if (inToolbar()) {
     if (MenuAdditionCacheEntry.isInWorkbenchTrim(location)) {
       // processTrimChildren(trimContributions, toolBarContributions,
       // configElement);
     } else {
       String query = location.getQuery();
       if (query == null || query.length() == 0) {
         query = "after=additions"; // $NON-NLS-1$
       }
       processToolbarChildren(toolBarContributions, configElement, location.getPath(), query);
     }
     return;
   }
   MMenuContribution menuContribution = MenuFactoryImpl.eINSTANCE.createMenuContribution();
   String idContrib = MenuHelper.getId(configElement);
   if (idContrib != null && idContrib.length() > 0) {
     menuContribution.setElementId(idContrib);
   }
   if ("org.eclipse.ui.popup.any".equals(location.getPath())) { // $NON-NLS-1$
     menuContribution.setParentId("popup"); // $NON-NLS-1$
   } else {
     menuContribution.setParentId(location.getPath());
   }
   String query = location.getQuery();
   if (query == null || query.length() == 0) {
     query = "after=additions"; // $NON-NLS-1$
   }
   menuContribution.setPositionInParent(query);
   menuContribution.getTags().add("scheme:" + location.getScheme()); // $NON-NLS-1$
   String filter = ContributionsAnalyzer.MC_MENU;
   if ("popup".equals(location.getScheme())) { // $NON-NLS-1$
     filter = ContributionsAnalyzer.MC_POPUP;
   }
   menuContribution.getTags().add(filter);
   menuContribution.setVisibleWhen(MenuHelper.getVisibleWhen(configElement));
   ContextFunction generator = new ContributionFactoryGenerator(configElement, 0);
   menuContribution.getTransientData().put(ContributionRecord.FACTORY, generator);
   menuContributions.add(menuContribution);
 }
  /*
   * Report the specified exception to the log and to the user.
   */
  final void reportException(Throwable t) {
    // get any nested exceptions
    Throwable nestedException = StatusUtil.getCause(t);
    Throwable exception = (nestedException == null) ? t : nestedException;

    // Messages
    String exceptionMessage = exception.getMessage();
    if (exceptionMessage == null) {
      exceptionMessage = WorkbenchMessages.WorkbenchWindow_exceptionMessage;
    }
    IStatus status =
        StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, exceptionMessage, exception);

    // Log and show the problem
    WorkbenchPlugin.log(exceptionMessage, status);
    StatusUtil.handleStatus(status, StatusManager.SHOW, getWorkbenchWindow().getShell());
  }
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.ui.tests.harness.util.UITestCase#doTearDown()
   */
  protected void doTearDown() throws Exception {
    final IPreferenceStore store = WorkbenchPlugin.getDefault().getPreferenceStore();
    store.setValue(
        "org.eclipse.ui.commands",
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?><org.eclipse.ui.commands><activeKeyConfiguration keyConfigurationId=\""
            + IBindingService.DEFAULT_DEFAULT_ACTIVE_SCHEME_ID
            + "\"/></org.eclipse.ui.commands>");
    IBindingService bindingService = (IBindingService) fWorkbench.getAdapter(IBindingService.class);

    // reset keybindings
    bindingService.readRegistryAndPreferences(null);
    final Scheme activeScheme =
        bindingService.getScheme(IBindingService.DEFAULT_DEFAULT_ACTIVE_SCHEME_ID);
    final Binding[] originalBindings = bindingService.getBindings();
    bindingService.savePreferences(activeScheme, originalBindings);
    super.doTearDown();
  }
  @Override
  public Image getImage(Object element) {
    if (element instanceof SampleCategory) {
      String iconFile = ((SampleCategory) element).getIconFile();
      if (iconFile != null) {
        File file = new File(iconFile);
        if (file.exists()) {
          String iconFilename = file.getAbsolutePath();
          Image image = imageRegistry.get(iconFilename);
          if (image == null) {
            image = new Image(Display.getDefault(), iconFilename);
            imageRegistry.put(iconFilename, image);
          }
          return image;
        }
      }
      // uses folder as the default image
      return IMAGE_FOLDER;
    }
    if (element instanceof SampleEntry) {
      File file = ((SampleEntry) element).getFile();
      if (file != null) {
        if (file.isDirectory()) {
          return IMAGE_FOLDER;
        }

        IEditorDescriptor editorDescriptor =
            WorkbenchPlugin.getDefault().getEditorRegistry().getDefaultEditor(file.getName());
        if (editorDescriptor == null || editorDescriptor.getImageDescriptor() == null) {
          return IMAGE_FILE;
        }
        String key = editorDescriptor.getId();
        Image image = imageRegistry.get(key);
        if (image == null) {
          image = editorDescriptor.getImageDescriptor().createImage();
          imageRegistry.put(key, image);
        }
        return image;
      }
    }
    if (element instanceof SamplesReference) {
      return SamplesUIPlugin.getImage(ICON_REMOTE);
    }
    return super.getImage(element);
  }
  /**
   * @param theme
   * @param property
   * @return
   */
  public static String[] splitPropertyName(Theme theme, String property) {
    IThemeDescriptor[] descriptors = WorkbenchPlugin.getDefault().getThemeRegistry().getThemes();
    for (int i = 0; i < descriptors.length; i++) {
      IThemeDescriptor themeDescriptor = descriptors[i];
      String id = themeDescriptor.getId();
      if (property.startsWith(id + '.')) { // the property starts with
        // a known theme ID -
        // extract and return it and
        // the remaining property
        return new String[] {
          property.substring(0, id.length()), property.substring(id.length() + 1)
        };
      }
    }

    // default is simply return the default theme ID and the raw property
    return new String[] {IThemeManager.DEFAULT_THEME, property};
  }
  private static void runStartupExtension(IConfigurationElement configurationElement) {
    try {
      Object object = WorkbenchPlugin.createExtension(configurationElement, ELEMENT_CLASS);
      if (!(object instanceof IIdeUiStartup)) {
        StatusHandler.log(
            new Status(
                IStatus.ERROR,
                UiPlugin.PLUGIN_ID,
                "Could not load "
                    + object.getClass().getCanonicalName()
                    + " must implement "
                    + IIdeUiStartup.class.getCanonicalName()));
        return;
      }

      IIdeUiStartup startup = (IIdeUiStartup) object;
      startup.lazyStartup();
    } catch (CoreException e) {
      StatusHandler.log(
          new Status(IStatus.ERROR, UiPlugin.PLUGIN_ID, "Could not load startup extension", e));
    }
  }
Example #26
0
  /**
   * Loads the class that will perform the action associated with the given drop data.
   *
   * @param data the drop data
   * @return the viewer drop adapter
   */
  protected static IDropActionDelegate getPluginAdapter(PluginTransferData data)
      throws CoreException {

    IExtensionRegistry registry = Platform.getExtensionRegistry();
    String adapterName = data.getExtensionId();
    IExtensionPoint xpt =
        registry.getExtensionPoint(
            PlatformUI.PLUGIN_ID, IWorkbenchRegistryConstants.PL_DROP_ACTIONS);
    IExtension[] extensions = xpt.getExtensions();
    for (int i = 0; i < extensions.length; i++) {
      IConfigurationElement[] configs = extensions[i].getConfigurationElements();
      if (configs != null && configs.length > 0) {
        for (int j = 0; j < configs.length; j++) {
          String id = configs[j].getAttribute("id"); // $NON-NLS-1$
          if (id != null && id.equals(adapterName)) {
            return (IDropActionDelegate) WorkbenchPlugin.createExtension(configs[j], ATT_CLASS);
          }
        }
      }
    }
    return null;
  }
  /**
   * Get the value of the encodings preference.
   *
   * @return List
   */
  private static List getIDEEncodingsPreference() {

    boolean updateRequired = false;

    String encodings =
        IDEWorkbenchPlugin.getDefault().getPreferenceStore().getString(IDE_ENCODINGS_PREFERENCE);

    if (encodings == null || encodings.length() == 0) {
      return new ArrayList();
    }

    String[] preferenceEncodings = encodings.split(PREFERENCE_SEPARATOR);
    ArrayList result = new ArrayList();

    // Drop any encodings that are not valid
    for (int i = 0; i < preferenceEncodings.length; i++) {
      String string = preferenceEncodings[i];
      boolean isSupported;
      try {
        isSupported = Charset.isSupported(string);
      } catch (IllegalCharsetNameException e) {
        isSupported = false;
      }
      if (isSupported) {
        result.add(string);
      } else {
        WorkbenchPlugin.log(
            NLS.bind(IDEWorkbenchMessages.WorkbenchEncoding_invalidCharset, string));
        updateRequired = true;
      }
    }

    if (updateRequired) {
      writeEncodingsPreference(null, result);
    }
    return result;
  }
  /*
   * Report the specified execution exception to the log and to the user.
   */
  private void reportException(Exception e, IAdaptable uiInfo) {
    Throwable nestedException = StatusUtil.getCause(e);
    Throwable exception = (nestedException == null) ? e : nestedException;
    String title = WorkbenchMessages.Error;
    String message = WorkbenchMessages.WorkbenchWindow_exceptionMessage;
    String exceptionMessage = exception.getMessage();
    if (exceptionMessage == null) {
      exceptionMessage = message;
    }
    IStatus status =
        new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, 0, exceptionMessage, exception);
    WorkbenchPlugin.log(message, status);

    boolean createdShell = false;
    Shell shell = getShell(uiInfo);
    if (shell == null) {
      createdShell = true;
      shell = new Shell();
    }
    ErrorDialog.openError(shell, title, message, status);
    if (createdShell) {
      shell.dispose();
    }
  }
/** Deletes a method on an RPC async or sync interface. */
@SuppressWarnings("restriction")
public class DeleteMethodProposal extends ASTRewriteCorrectionProposal {

  private static final Image ICON =
      WorkbenchPlugin.getDefault().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);

  private static final int RELEVANCE = 99;

  public static List<IJavaCompletionProposal> createProposalsForProblemOnAsyncType(
      ASTNode problemNode, String extraSyncMethodBindingKey) {
    TypeDeclaration asyncTypeDecl =
        (TypeDeclaration) ASTResolving.findAncestor(problemNode, ASTNode.TYPE_DECLARATION);
    assert (asyncTypeDecl != null);

    IType syncType = RemoteServiceUtilities.findSyncType(asyncTypeDecl);
    if (syncType == null) {
      return null;
    }

    MethodDeclaration extraSyncMethodDecl =
        JavaASTUtils.findMethodDeclaration(
            syncType.getCompilationUnit(), extraSyncMethodBindingKey);
    if (extraSyncMethodDecl == null) {
      return null;
    }

    return Collections.<IJavaCompletionProposal>singletonList(
        new DeleteMethodProposal(syncType.getCompilationUnit(), extraSyncMethodDecl));
  }

  public static List<IJavaCompletionProposal> createProposalsForProblemOnExtraMethod(
      ASTNode problemNode) {
    MethodDeclaration methodDecl = ASTResolving.findParentMethodDeclaration(problemNode);

    return Collections.<IJavaCompletionProposal>singletonList(
        new DeleteMethodProposal(JavaASTUtils.getCompilationUnit(methodDecl), methodDecl));
  }

  public static List<IJavaCompletionProposal> createProposalsForProblemOnSyncType(
      ASTNode problemNode, String extraAsyncMethodBindingKey) {
    TypeDeclaration syncTypeDecl =
        (TypeDeclaration) ASTResolving.findAncestor(problemNode, ASTNode.TYPE_DECLARATION);
    assert (syncTypeDecl != null);

    IType asyncType = RemoteServiceUtilities.findAsyncType(syncTypeDecl);
    if (asyncType == null) {
      return null;
    }

    MethodDeclaration extraAsyncMethodDecl =
        JavaASTUtils.findMethodDeclaration(
            asyncType.getCompilationUnit(), extraAsyncMethodBindingKey);
    if (extraAsyncMethodDecl == null) {
      return null;
    }

    return Collections.<IJavaCompletionProposal>singletonList(
        new DeleteMethodProposal(asyncType.getCompilationUnit(), extraAsyncMethodDecl));
  }

  private static String generateDisplayName(MethodDeclaration methodDecl) {
    TypeDeclaration typeDecl = (TypeDeclaration) ASTResolving.findParentType(methodDecl);
    return MessageFormat.format(
        "Remove method ''{0}'' from type ''{1}''",
        methodDecl.getName().getIdentifier(), typeDecl.getName().getIdentifier());
  }

  private final MethodDeclaration methodDecl;

  private DeleteMethodProposal(ICompilationUnit cu, MethodDeclaration methodDecl) {
    super(generateDisplayName(methodDecl), cu, null, RELEVANCE, ICON);
    this.methodDecl = methodDecl;
  }

  @Override
  protected ASTRewrite getRewrite() throws CoreException {
    CompilationUnit targetAstRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
    createImportRewrite(targetAstRoot);

    ASTRewrite rewrite = ASTRewrite.create(targetAstRoot.getAST());

    // Find the method declaration in the AST we just generated (the one that
    // the AST rewriter is hooked up to).
    MethodDeclaration rewriterAstMethodDecl =
        JavaASTUtils.findMethodDeclaration(targetAstRoot, methodDecl.resolveBinding().getKey());
    if (rewriterAstMethodDecl == null) {
      return null;
    }

    // Remove the extra method declaration
    rewrite.remove(rewriterAstMethodDecl, null);

    return rewrite;
  }
}
  /* (non-Javadoc)
   * @see org.eclipse.ui.presentations.AbstractPresentationFactory#createEditorPresentation(org.eclipse.swt.widgets.Composite, org.eclipse.ui.presentations.IStackPresentationSite)
   */
  public StackPresentation createEditorPresentation(Composite parent, IStackPresentationSite site) {
    DefaultTabFolder folder =
        new DefaultTabFolder(
            parent,
            editorTabPosition | SWT.BORDER,
            site.supportsState(IStackPresentationSite.STATE_MINIMIZED),
            site.supportsState(IStackPresentationSite.STATE_MAXIMIZED));

    /*
     * Set the minimum characters to display, if the preference is something
     * other than the default. This is mainly intended for RCP applications
     * or for expert users (i.e., via the plug-in customization file).
     *
     * Bug 32789.
     */
    final IPreferenceStore store = PlatformUI.getPreferenceStore();
    if (store.contains(IWorkbenchPreferenceConstants.EDITOR_MINIMUM_CHARACTERS)) {
      final int minimumCharacters =
          store.getInt(IWorkbenchPreferenceConstants.EDITOR_MINIMUM_CHARACTERS);
      if (minimumCharacters >= 0) {
        folder.setMinimumCharacters(minimumCharacters);
      }
    }

    PresentablePartFolder partFolder = new PresentablePartFolder(folder);

    TabbedStackPresentation result =
        new TabbedStackPresentation(site, partFolder, new StandardEditorSystemMenu(site));

    DefaultThemeListener themeListener = new DefaultThemeListener(folder, result.getTheme());
    result.getTheme().addListener(themeListener);

    IDynamicPropertyMap workbenchPreferences =
        result.getPluginPreferences(WorkbenchPlugin.getDefault());

    // RAP [bm]:
    if (!Workbench.getInstance().isClosing()) {
      final DefaultMultiTabListener defaultMultiTabListener =
          new DefaultMultiTabListener(
              workbenchPreferences,
              IWorkbenchPreferenceConstants.SHOW_MULTIPLE_EDITOR_TABS,
              folder);
      result
          .getControl()
          .addDisposeListener(
              new DisposeListener() {
                public void widgetDisposed(DisposeEvent event) {
                  defaultMultiTabListener.attach(
                      null, IWorkbenchPreferenceConstants.SHOW_MULTIPLE_EDITOR_TABS, true);
                }
              });
    }
    // RAPEND: [bm]

    // RAP [bm]: tab style cannot change
    //		new DefaultSimpleTabListener(result.getApiPreferences(),
    //				IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS,
    //				folder);
    //		TODO: needs SessionStoreListener too when activated
    // RAPEND: [bm]

    return result;
  }