private void makeActions() { action1 = new Action() { public void run() { showMessage("Action 1 executed"); } }; action1.setText("Action 1"); action1.setToolTipText("Action 1 tooltip"); action1.setImageDescriptor( PlatformUI.getWorkbench() .getSharedImages() .getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK)); action2 = new Action() { public void run() { showMessage("Action 2 executed"); } }; action2.setText("Action 2"); action2.setToolTipText("Action 2 tooltip"); action2.setImageDescriptor( PlatformUI.getWorkbench() .getSharedImages() .getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK)); doubleClickAction = new Action() { public void run() { ISelection selection = viewer.getSelection(); Object obj = ((IStructuredSelection) selection).getFirstElement(); showMessage("Double-click detected on " + obj.toString()); } }; }
/** This is a callback that will allow us to create the viewer and initialize it. */ public void createPartControl(Composite parent) { Table table = createTableWithColumns(parent); viewer = new TableViewer(table); GridData gd = new GridData(GridData.FILL_BOTH); viewer.getControl().setLayoutData(gd); // Create the help context id for the viewer's control PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "YetiPlugIn.viewer"); viewer.setContentProvider(new OverviewContentProvider()); // Get the content for the viewer, setInput will call getElements in the // contentProvider viewer.setLabelProvider(new OverviewLabelProvider()); viewer.setInput(YetiPlugIn.getOverviewArrayList()); /* viewer.setContentProvider( new ViewSummaryContentProvider()); // Get the content for the viewer, setInput will call getElements in the // contentProvider viewer.setLabelProvider(new ViewSummaryLabelProvider()); viewer.setInput(YetiPlugIn.getSummaryInfoArrayList()); // Share Viewer Selection with other workbench parts getViewSite().setSelectionProvider(viewer); viewer.addSelectionChangedListener(this); */ }
private void validatePage() { String errorMessage = null; String newText = fWorkingSetName.getText(); if (newText.trim().length() == 0) { errorMessage = PDEUIMessages.PluginWorkingSet_emptyName; if (fFirstCheck) { setPageComplete(false); fFirstCheck = false; return; } } if (errorMessage == null && fTree.getCheckboxTreeViewer().getCheckedElements().length == 0) { errorMessage = PDEUIMessages.PluginWorkingSet_noPluginsChecked; } if (errorMessage == null && fWorkingSet == null) { IWorkingSet[] workingSets = PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSets(); for (int i = 0; i < workingSets.length; i++) { if (newText.equals(workingSets[i].getName())) { errorMessage = PDEUIMessages.PluginWorkingSet_nameInUse; break; } } } setErrorMessage(errorMessage); setPageComplete(errorMessage == null); }
public boolean performFinish() { try { String perspId = selection.getAttribute("perspectiveId"); // $NON-NLS-1$ IWorkbenchPage page = PDEPlugin.getActivePage(); if (perspId != null && switchPerspective) { PlatformUI.getWorkbench().showPerspective(perspId, page.getWorkbenchWindow()); } SampleOperation op = new SampleOperation(selection, namesPage.getProjectNames(), new ImportOverwriteQuery()); getContainer().run(true, true, op); IFile sampleManifest = op.getSampleManifest(); if (selectRevealEnabled) { selectReveal(getShell()); } if (activitiesEnabled) enableActivities(); if (sampleEditorNeeded && sampleManifest != null) IDE.openEditor(page, sampleManifest, true); } catch (InvocationTargetException e) { PDEPlugin.logException(e); return false; } catch (InterruptedException e) { // PDEPlugin.logException(e); return false; } catch (CoreException e) { PDEPlugin.logException(e); return false; } catch (OperationCanceledException e) { return false; } return true; }
private void handleConvert() { try { // remove listeners of Info section before we convert. If we don't // we may get a model changed event while disposing the page. Bug 156414 fInfoSection.removeListeners(); PDEFormEditor editor = getPDEEditor(); IPluginModelBase model = (IPluginModelBase) editor.getAggregateModel(); IRunnableWithProgress op = new CreateManifestOperation(model); IProgressService service = PlatformUI.getWorkbench().getProgressService(); editor.doSave(null); service.runInUI(service, op, PDEPlugin.getWorkspace().getRoot()); updateBuildProperties(); editor.doSave(null); } catch (InvocationTargetException e) { MessageDialog.openError( PDEPlugin.getActiveWorkbenchShell(), PDEUIMessages.OverviewPage_error, e.getCause().getMessage()); // if convert failed and this OverviewPage hasn't been removed from the editor, reattach // listeners if (!fDisposed) fInfoSection.addListeners(); } catch (InterruptedException e) { // if convert failed and this OverviewPage hasn't been removed from the editor, reattach // listeners if (!fDisposed) fInfoSection.addListeners(); } }
/** * Runs task in Eclipse progress dialog. NOTE: this call can't be canceled if it will block in IO */ public static void runInProgressDialog(final DBRRunnableWithProgress runnable) throws InvocationTargetException { try { IRunnableContext runnableContext; IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow(); if (workbenchWindow != null) { runnableContext = new ProgressMonitorDialog(workbench.getActiveWorkbenchWindow().getShell()); } else { runnableContext = workbench.getProgressService(); } runnableContext.run( true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { runnable.run(RuntimeUtils.makeMonitor(monitor)); } }); } catch (InterruptedException e) { // do nothing } }
/** * Registers the given action with the workbench command support. * * @param action the action to register. */ private void registerKeybindings(IAction action) { final IHandler handler = new ActionHandler(action); final IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); final IHandlerActivation activation = handlerService.activateHandler( action.getActionDefinitionId(), handler, new ActiveShellExpression(dialog.getShell())); activations.add(activation); }
/** Dispose the receiver and clear out the references. */ public void dispose() { final IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); final Iterator iterator = activations.iterator(); while (iterator.hasNext()) { handlerService.deactivateHandler((IHandlerActivation) iterator.next()); } activations.clear(); }
/** Called when the action is executed. */ public void run(IAction action) { wizard = new P5ExportWizard(); IWorkbench wb = PlatformUI.getWorkbench(); wizard.init(wb, null); Shell shell = wb.getActiveWorkbenchWindow().getShell(); WizardDialog wd = new WizardDialog(shell, wizard); wd.open(); // System.err.println("WIZARD="+wizard); }
/** * Creates the SWT controls for this workbench part. * * @param parent the parent control */ public void createSection(Composite parent) { super.createSection(parent); FormToolkit toolkit = getFormToolkit(parent.getDisplay()); Section section = toolkit.createSection( parent, ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR | Section.DESCRIPTION | ExpandableComposite.FOCUS_TITLE); section.setText(Messages.configurationEditorPortsSection); section.setDescription(Messages.configurationEditorPortsDescription); section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL)); // ports Composite composite = toolkit.createComposite(section); GridLayout layout = new GridLayout(); layout.marginHeight = 8; layout.marginWidth = 8; composite.setLayout(layout); composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.FILL_HORIZONTAL)); IWorkbenchHelpSystem whs = PlatformUI.getWorkbench().getHelpSystem(); whs.setHelp(composite, ContextIds.CONFIGURATION_EDITOR_PORTS); toolkit.paintBordersFor(composite); section.setClient(composite); ports = toolkit.createTable(composite, SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION); ports.setHeaderVisible(true); ports.setLinesVisible(true); whs.setHelp(ports, ContextIds.CONFIGURATION_EDITOR_PORTS_LIST); TableLayout tableLayout = new TableLayout(); TableColumn col = new TableColumn(ports, SWT.NONE); col.setText(Messages.configurationEditorPortNameColumn); ColumnWeightData colData = new ColumnWeightData(15, 150, true); tableLayout.addColumnData(colData); col = new TableColumn(ports, SWT.NONE); col.setText(Messages.configurationEditorPortValueColumn); colData = new ColumnWeightData(8, 80, true); tableLayout.addColumnData(colData); GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); data.widthHint = 230; data.heightHint = 100; ports.setLayoutData(data); ports.setLayout(tableLayout); viewer = new TableViewer(ports); viewer.setColumnProperties(new String[] {"name", "port"}); initialize(); }
public static void removeFocusTracker(IServiceLocator serviceLocator, Control control) { if (PlatformUI.getWorkbench().isClosing()) { // TODO: it is a bug in eclipse. During workbench shutdown disposed service returned. return; } final IFocusService focusService = serviceLocator.getService(IFocusService.class); if (focusService != null) { focusService.removeFocusTracker(control); } else { log.debug("Focus service not found in " + serviceLocator); } }
@NotNull public static IWorkbenchWindow getActiveWorkbenchWindow() { IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); if (window != null) { return window; } IWorkbenchWindow[] windows = workbench.getWorkbenchWindows(); if (windows.length > 0) { return windows[0]; } throw new IllegalStateException("No workbench window"); }
public static boolean isContextActive(String contextId) { Collection<?> contextIds = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getService(IContextService.class) .getActiveContextIds(); for (Object id : contextIds) { if (contextId.equals(id)) { return true; } } return false; }
private IEditorInput getEditorInput() throws IOException { IWorkbench wb = PlatformUI.getWorkbench(); IWorkbenchWindow[] wws = wb.getWorkbenchWindows(); if (wws.length != 1) throw new IOException("Failed to find workbench window"); IWorkbenchWindow ww = wws[0]; IWorkbenchPage[] wps = ww.getPages(); if (wws.length != 1) throw new IOException("Failed to find workbench page"); IWorkbenchPage wp = wps[0]; IEditorPart ep = wp.getActiveEditor(); if (ep == null) throw new IOException("Failed to find active editor"); return ep.getEditorInput(); }
public static DBRRunnableContext getDefaultRunnableContext() { IWorkbench workbench = PlatformUI.getWorkbench(); if (workbench != null && workbench.getActiveWorkbenchWindow() != null) { return new RunnableContextDelegate(workbench.getActiveWorkbenchWindow()); } else { return new DBRRunnableContext() { @Override public void run(boolean fork, boolean cancelable, DBRRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException { runnable.run(VoidProgressMonitor.INSTANCE); } }; } }
/** This is a callback that will allow us to create the viewer and initialize it. */ public void createPartControl(Composite parent) { viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); viewer.setContentProvider(new ViewContentProvider()); viewer.setLabelProvider(new ViewLabelProvider()); viewer.setSorter(new NameSorter()); viewer.setInput(getViewSite()); // Delegator // Create the help context id for the viewer's control PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "test.viewer"); makeActions(); hookContextMenu(); hookDoubleClickAction(); contributeToActionBars(); }
/*private void doSelectReveal() { if (selection == null || createdProjects==null) return; String viewId = selection.getAttribute("targetViewId"); //$NON-NLS-1$ if (viewId == null) return; IWorkbenchWindow window = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); if (window == null) return; IWorkbenchPage page = window.getActivePage(); if (page == null) return; IViewPart view = page.findView(viewId); if (view == null || !(view instanceof ISetSelectionTarget)) return; ISetSelectionTarget target = (ISetSelectionTarget) view; IConfigurationElement[] projects = selection.getChildren("project"); //$NON-NLS-1$ ArrayList items = new ArrayList(); for (int i = 0; i < projects.length; i++) { String path = projects[i].getAttribute("selectReveal"); //$NON-NLS-1$ if (path == null) continue; IResource resource = createdProjects[i].findMember(path); if (resource.exists()) items.add(resource); } if (items.size() > 0) target.selectReveal(new StructuredSelection(items)); } */ public void enableActivities() { IConfigurationElement[] elements = selection.getChildren("activity"); // $NON-NLS-1$ HashSet activitiesToEnable = new HashSet(); IWorkbenchActivitySupport workbenchActivitySupport = PlatformUI.getWorkbench().getActivitySupport(); for (int i = 0; i < elements.length; i++) { IConfigurationElement element = elements[i]; String id = element.getAttribute("id"); // $NON-NLS-1$ if (id == null) continue; activitiesToEnable.add(id); } HashSet set = new HashSet(workbenchActivitySupport.getActivityManager().getEnabledActivityIds()); set.addAll(activitiesToEnable); workbenchActivitySupport.setEnabledActivityIds(set); }
public static CompareHandlerService createFor(ICompareContainer container, Shell shell) { IServiceLocator serviceLocator = container.getServiceLocator(); if (serviceLocator != null) { IHandlerService service = (IHandlerService) serviceLocator.getService(IHandlerService.class); if (service != null) return new CompareHandlerService(container, null); } if (container.getWorkbenchPart() == null && shell != null) { // We're in a dialog so we can use an active shell expression IHandlerService service = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); if (service != null) { Expression e = new ActiveShellExpression(shell); return new CompareHandlerService(container, e); } } return new CompareHandlerService(null, null); }
protected void createFormContent(IManagedForm managedForm) { super.createFormContent(managedForm); ScrolledForm form = managedForm.getForm(); FormToolkit toolkit = managedForm.getToolkit(); if (isFragment()) { form.setImage( PDEPlugin.getDefault().getLabelProvider().get(PDEPluginImages.DESC_FRAGMENT_MF_OBJ)); } else { form.setImage( PDEPlugin.getDefault().getLabelProvider().get(PDEPluginImages.DESC_PLUGIN_MF_OBJ)); } form.setText(PDEUIMessages.MonitorEditor_OverviewPage_title); fillBody(managedForm, toolkit); PlatformUI.getWorkbench() .getHelpSystem() .setHelp(form.getBody(), IHelpContextIds.MONITOR_PLUGIN_OVERVIEW); }
/* (non-Javadoc) * @see org.eclipse.ui.dialogs.IWorkingSetPage#finish() */ public void finish() { Object[] checked = fTree.getCheckboxTreeViewer().getCheckedElements(); ArrayList<PersistablePluginObject> list = new ArrayList<PersistablePluginObject>(); for (int i = 0; i < checked.length; i++) { String id = ((IPluginModelBase) checked[i]).getPluginBase().getId(); if (id != null && id.length() > 0) list.add(new PersistablePluginObject(id)); } PersistablePluginObject[] objects = list.toArray(new PersistablePluginObject[list.size()]); String workingSetName = fWorkingSetName.getText().trim(); if (fWorkingSet == null) { IWorkingSetManager workingSetManager = PlatformUI.getWorkbench().getWorkingSetManager(); fWorkingSet = workingSetManager.createWorkingSet(workingSetName, objects); } else { fWorkingSet.setName(workingSetName); fWorkingSet.setElements(objects); } }
private void handleWorkingSets() { IWorkingSetManager manager = PlatformUI.getWorkbench().getWorkingSetManager(); IWorkingSetSelectionDialog dialog = manager.createWorkingSetSelectionDialog(getShell(), true); if (dialog.open() == Window.OK) { ArrayList models = new ArrayList(); IWorkingSet[] workingSets = dialog.getSelection(); for (int i = 0; i < workingSets.length; i++) { IAdaptable[] elements = workingSets[i].getElements(); for (int j = 0; j < elements.length; j++) { IModel model = findModelFor(elements[j]); if (isValidModel(model)) { models.add(model); } } } fExportPart.setSelection(models.toArray()); } }
private void initialize() { if (fHandlerService == null) { IServiceLocator serviceLocator = fContainer.getServiceLocator(); if (serviceLocator != null) { IHandlerService service = (IHandlerService) serviceLocator.getService(IHandlerService.class); if (service != null) fHandlerService = service; } if (fHandlerService == null && fContainer.getWorkbenchPart() == null && fExpression != null) { // We're in a dialog so we can use an active shell expression IHandlerService service = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); if (service != null) { fHandlerService = service; } } } }
private void handleOpenProperties() { Object[] selected = ((IStructuredSelection) fPackageViewer.getSelection()).toArray(); ExportPackageObject first = (ExportPackageObject) selected[0]; DependencyPropertiesDialog dialog = new DependencyPropertiesDialog(isEditable(), first); dialog.create(); PlatformUI.getWorkbench() .getHelpSystem() .setHelp(dialog.getShell(), IHelpContextIds.EXPORTED_PACKAGE_PROPERTIES); SWTUtil.setDialogSize(dialog, 400, -1); if (selected.length == 1) dialog.setTitle(((ExportPackageObject) selected[0]).getName()); else dialog.setTitle(PDEUIMessages.ExportPackageSection_props); if (dialog.open() == Window.OK && isEditable()) { String newVersion = dialog.getVersion(); for (Object selectedObject : selected) { ExportPackageObject object = (ExportPackageObject) selectedObject; if (!newVersion.equals(object.getVersion())) object.setVersion(newVersion); } } }
public static void runInUI(IRunnableContext context, final DBRRunnableWithProgress runnable) { try { PlatformUI.getWorkbench() .getProgressService() .runInUI( context, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { runnable.run(RuntimeUtils.makeMonitor(monitor)); } }, DBeaverActivator.getWorkspace().getRoot()); } catch (InvocationTargetException e) { UIUtils.showErrorDialog(null, null, null, e.getTargetException()); } catch (InterruptedException e) { // do nothing } }
private void handleAddWorkingSet() { IWorkingSetManager manager = PlatformUI.getWorkbench().getWorkingSetManager(); IWorkingSetSelectionDialog dialog = manager.createWorkingSetSelectionDialog(PDEPlugin.getActiveWorkbenchShell(), true); if (dialog.open() == Window.OK) { IWorkingSet[] workingSets = dialog.getSelection(); IProduct product = getProduct(); IProductModelFactory factory = product.getModel().getFactory(); ArrayList<IProductPlugin> pluginList = new ArrayList<IProductPlugin>(); for (int i = 0; i < workingSets.length; i++) { IAdaptable[] elements = workingSets[i].getElements(); for (int j = 0; j < elements.length; j++) { IPluginModelBase model = findModel(elements[j]); if (model != null) { IProductPlugin plugin = factory.createPlugin(); IPluginBase base = model.getPluginBase(); plugin.setId(base.getId()); pluginList.add(plugin); } } } product.addPlugins(pluginList.toArray(new IProductPlugin[pluginList.size()])); } }
/** * Returns the default title image. * * @return the default image */ protected Image getDefaultImage() { return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_DEF_VIEW); }
@Override protected Control createControl(Composite parent) { Composite propertyComposite = new Composite(parent, SWT.BORDER); GridLayout layout = new GridLayout(1, false); layout.marginWidth = layout.marginHeight = 0; propertyComposite.setLayout(layout); if (mPage instanceof Page) { ((Page) mPage) .init( new IPageSite() { public void registerContextMenu( String menuId, MenuManager menuManager, ISelectionProvider selectionProvider) {} public IActionBars getActionBars() { return null; } public IWorkbenchPage getPage() { return getWorkbenchWindow().getActivePage(); } public ISelectionProvider getSelectionProvider() { return null; } public Shell getShell() { return getWorkbenchWindow().getShell(); } public IWorkbenchWindow getWorkbenchWindow() { return PlatformUI.getWorkbench().getActiveWorkbenchWindow(); } public void setSelectionProvider(ISelectionProvider provider) {} @SuppressWarnings("unchecked") public Object getAdapter(Class adapter) { return null; } @SuppressWarnings("unchecked") public Object getService(Class api) { return null; } @SuppressWarnings("unchecked") public boolean hasService(Class api) { return false; } }); } if (mPage instanceof PropertySheetPage) { ((PropertySheetPage) mPage).setPropertySourceProvider(this); } mPage.createControl(propertyComposite); mPage.setActionBars(new DummyActionBars()); final Control control = mPage.getControl(); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); if (control instanceof Tree) { final Tree tree = (Tree) control; data.heightHint = tree.getItemHeight() * 13 + (tree.getLinesVisible() ? 12 * tree.getGridLineWidth() : 0) + (tree.getHeaderVisible() ? tree.getHeaderHeight() : 0) + 2 * tree.getBorderWidth() + (tree.getHorizontalBar() != null ? tree.getHorizontalBar().getSize().x : 0); tree.addControlListener( new ControlAdapter() { @Override public void controlResized(ControlEvent e) { Rectangle area = tree.getClientArea(); TreeColumn[] columns = tree.getColumns(); if (area.width > 0) { columns[0].setWidth(area.width * 40 / 100); columns[1].setWidth(area.width - columns[0].getWidth() - 4); } } }); } else if (control instanceof Composite) { control.addControlListener( new ControlAdapter() { @Override public void controlResized(ControlEvent e) { ((Composite) control).layout(true, true); } }); } control.setLayoutData(data); ISelection selection; if (mCurrentWidget == null) { Collection<InstallOptionsModelTypeDef> typeDefs = InstallOptionsModel.INSTANCE.getControlTypeDefs(); if (typeDefs.size() > 0) { InstallOptionsModelTypeDef typeDef = typeDefs.iterator().next(); InstallOptionsElementFactory factory = InstallOptionsElementFactory.getFactory(typeDef.getType()); mCurrentWidget = (InstallOptionsWidget) factory.getNewObject(); mDialog.addChild(mCurrentWidget); } } if (mCurrentWidget != null) { mCurrentWidget.addModelCommandListener(InstallOptionsWidgetEditorDialog.this); mCurrentWidget.addPropertyChangeListener(InstallOptionsWidgetEditorDialog.this); if (mCurrentWidget.getParent() != null) { mCurrentWidget.getParent().addPropertyChangeListener(InstallOptionsWidgetEditorDialog.this); } selection = new StructuredSelection(mCurrentWidget); } else { selection = StructuredSelection.EMPTY; } mPage.selectionChanged(null, selection); PlatformUI.getWorkbench().getHelpSystem().setHelp(mPage.getControl(), HELP_CONTEXT); PlatformUI.getWorkbench().getHelpSystem().setHelp(propertyComposite, HELP_CONTEXT); return propertyComposite; }
/** * A menu for opening file revisions in the workbench. * * <p>An <code>OpenWithMenu</code> is used to populate a menu with "Open With" actions. One action * is added for each editor which is applicable to the selected file. If the user selects one of * these items, the corresponding editor is opened on the file. */ public class OpenWithMenu extends ContributionItem { private IStructuredSelection selection; private HistoryPage page; private IEditorRegistry registry = PlatformUI.getWorkbench().getEditorRegistry(); private static Hashtable imageCache = new Hashtable(11); /** The id of this action. */ public static final String ID = PlatformUI.PLUGIN_ID + ".OpenWithMenu"; // $NON-NLS-1$ /** * Match both the input and id, so that different types of editor can be opened on the same input. */ private static final int MATCH_BOTH = IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID; /* * Compares the labels from two IEditorDescriptor objects */ private static final Comparator comparer = new Comparator() { private Collator collator = Collator.getInstance(); public int compare(Object arg0, Object arg1) { String s1 = ((IEditorDescriptor) arg0).getLabel(); String s2 = ((IEditorDescriptor) arg1).getLabel(); return collator.compare(s1, s2); } }; /** * Constructs a new instance of <code>OpenWithMenu</code>. * * @param page the page where the editor is opened if an item within the menu is selected */ public OpenWithMenu(HistoryPage page) { super(ID); this.page = page; } /** * Returns an image to show for the corresponding editor descriptor. * * @param editorDesc the editor descriptor, or null for the system editor * @return the image or null */ private Image getImage(IEditorDescriptor editorDesc) { ImageDescriptor imageDesc = getImageDescriptor(editorDesc); if (imageDesc == null) { return null; } Image image = (Image) imageCache.get(imageDesc); if (image == null) { image = imageDesc.createImage(); imageCache.put(imageDesc, image); } return image; } /** Returns the image descriptor for the given editor descriptor, or null if it has no image. */ private ImageDescriptor getImageDescriptor(IEditorDescriptor editorDesc) { ImageDescriptor imageDesc = null; if (editorDesc == null) { imageDesc = registry.getImageDescriptor(getFileRevision().getName()); // TODO: is this case valid, and if so, what are the implications // for content-type editor bindings? } else { imageDesc = editorDesc.getImageDescriptor(); } if (imageDesc == null) { if (editorDesc.getId().equals(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID)) { imageDesc = registry.getSystemExternalEditorImageDescriptor(getFileRevision().getName()); } } return imageDesc; } /** * Creates the menu item for the editor descriptor. * * @param menu the menu to add the item to * @param descriptor the editor descriptor, or null for the system editor * @param preferredEditor the descriptor of the preferred editor, or <code>null</code> */ private MenuItem createMenuItem( Menu menu, final IEditorDescriptor descriptor, final IEditorDescriptor preferredEditor) { // XXX: Would be better to use bold here, but SWT does not support it. final MenuItem menuItem = new MenuItem(menu, SWT.RADIO); boolean isPreferred = preferredEditor != null && descriptor.getId().equals(preferredEditor.getId()); menuItem.setSelection(isPreferred); menuItem.setText(descriptor.getLabel()); Image image = getImage(descriptor); if (image != null) { menuItem.setImage(image); } Listener listener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.Selection: if (menuItem.getSelection()) { openEditor(descriptor, false); } break; } } }; menuItem.addListener(SWT.Selection, listener); return menuItem; } /** * Creates the Other... menu item * * @param menu the menu to add the item to */ private void createOtherMenuItem(final Menu menu) { final IFileRevision fileResource = getFileRevision(); if (fileResource == null) { return; } new MenuItem(menu, SWT.SEPARATOR); final MenuItem menuItem = new MenuItem(menu, SWT.PUSH); menuItem.setText(TeamUIMessages.LocalHistoryPage_OpenWithMenu_Other); Listener listener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.Selection: EditorSelectionDialog dialog = new EditorSelectionDialog(menu.getShell()); dialog.setMessage( NLS.bind( TeamUIMessages.LocalHistoryPage_OpenWithMenu_OtherDialogDescription, fileResource.getName())); if (dialog.open() == Window.OK) { IEditorDescriptor editor = dialog.getSelectedEditor(); if (editor != null) { openEditor(editor, editor.isOpenExternal()); } } break; } } }; menuItem.addListener(SWT.Selection, listener); } public void fill(Menu menu, int index) { final IFileRevision fileRevision = getFileRevision(); if (fileRevision == null) { return; } IEditorDescriptor defaultTextEditor = registry.findEditor("org.eclipse.ui.DefaultTextEditor"); // $NON-NLS-1$ IEditorDescriptor preferredEditor = Utils.getDefaultEditor(fileRevision); Object[] editors = Utils.getEditors(fileRevision); Collections.sort(Arrays.asList(editors), comparer); boolean defaultFound = false; // Check that we don't add it twice. This is possible // if the same editor goes to two mappings. ArrayList alreadyMapped = new ArrayList(); for (int i = 0; i < editors.length; i++) { IEditorDescriptor editor = (IEditorDescriptor) editors[i]; if (!alreadyMapped.contains(editor)) { createMenuItem(menu, editor, preferredEditor); if (defaultTextEditor != null && editor.getId().equals(defaultTextEditor.getId())) { defaultFound = true; } alreadyMapped.add(editor); } } // Only add a separator if there is something to separate if (editors.length > 0) { new MenuItem(menu, SWT.SEPARATOR); } // Add default editor. Check it if it is saved as the preference. if (!defaultFound && defaultTextEditor != null) { createMenuItem(menu, defaultTextEditor, preferredEditor); } // TODO : We might perhaps enable inplace and system external editors menu items /*// Add system editor IEditorDescriptor descriptor = registry .findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); final MenuItem systemEditorMenuItem = createMenuItem(menu, descriptor, preferredEditor); systemEditorMenuItem.setEnabled(false); // Add system in-place editor descriptor = registry .findEditor(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID); final MenuItem inPlaceEditorMenuItem = (descriptor != null) ? createMenuItem( menu, descriptor, preferredEditor) : null; if (inPlaceEditorMenuItem != null) inPlaceEditorMenuItem.setEnabled(false); Job job = new Job("updateOpenWithMenu") { //$NON-NLS-1$ protected IStatus run(IProgressMonitor monitor) { try { final boolean isFile = fileRevision.getStorage(monitor) instanceof IFile; Display.getDefault().asyncExec(new Runnable() { public void run() { if (inPlaceEditorMenuItem != null && !inPlaceEditorMenuItem.isDisposed()) inPlaceEditorMenuItem.setEnabled(isFile); if (!systemEditorMenuItem.isDisposed()) systemEditorMenuItem.setEnabled(isFile); } }); return Status.OK_STATUS; } catch (CoreException e) { return new Status(IStatus.WARNING, TeamUIPlugin.ID, null, e); } }; }; job.setSystem(true); job.schedule();*/ createDefaultMenuItem(menu, fileRevision); // add Other... menu item createOtherMenuItem(menu); } public void createDefaultMenuItem(Menu menu, final IFileRevision revision) { final MenuItem menuItem = new MenuItem(menu, SWT.RADIO); menuItem.setSelection(Utils.getDefaultEditor(revision) == null); menuItem.setText(TeamUIMessages.LocalHistoryPage_OpenWithMenu_DefaultEditorDescription); Listener listener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.Selection: if (menuItem.getSelection()) { openEditor(Utils.getDefaultEditor(revision), false); } break; } } }; menuItem.addListener(SWT.Selection, listener); } /** Opens the given editor on the selected file revision. */ protected void openEditor(IEditorDescriptor editorDescriptor, boolean openUsingDescriptor) { IFileRevision fileRevision = getFileRevision(); if (fileRevision == null) { return; } try { IProgressMonitor monitor = new NullProgressMonitor(); IStorage storage = fileRevision.getStorage(monitor); boolean isFile = storage instanceof IFile; if (openUsingDescriptor) { // discouraged access to open system editors ((WorkbenchPage) (page.getSite().getPage())) .openEditorFromDescriptor( isFile ? new FileEditorInput((IFile) storage) : (IEditorInput) FileRevisionEditorInput.createEditorInputFor(fileRevision, monitor), editorDescriptor, true, null); } else { String editorId = editorDescriptor == null ? IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID : editorDescriptor.getId(); page.getSite() .getPage() .openEditor( isFile ? new FileEditorInput((IFile) storage) : (IEditorInput) FileRevisionEditorInput.createEditorInputFor(fileRevision, monitor), editorId, true, MATCH_BOTH); } } catch (PartInitException e) { StatusAdapter statusAdapter = new StatusAdapter(e.getStatus()); statusAdapter.setProperty( IStatusAdapterConstants.TITLE_PROPERTY, TeamUIMessages.LocalHistoryPage_OpenEditorError); StatusManager.getManager().handle(statusAdapter, StatusManager.SHOW); } catch (CoreException e) { StatusAdapter statusAdapter = new StatusAdapter(e.getStatus()); statusAdapter.setProperty( IStatusAdapterConstants.TITLE_PROPERTY, TeamUIMessages.LocalHistoryPage_OpenEditorError); StatusManager.getManager().handle(statusAdapter, StatusManager.LOG); } } private IFileRevision getFileRevision() { IStructuredSelection structSel = selection; IFileRevision revision = null; if (structSel == null) return null; Object[] objArray = structSel.toArray(); for (int i = 0; i < objArray.length; i++) { Object tempRevision = objArray[i]; // If not a revision, don't try opening if (tempRevision instanceof AbstractHistoryCategory) continue; revision = (IFileRevision) tempRevision; } return revision; } /* * (non-Javadoc) Returns whether this menu is dynamic. */ public boolean isDynamic() { return true; } public void selectionChanged(IStructuredSelection selection) { if (selection instanceof IStructuredSelection) { this.selection = selection; } else { this.selection = StructuredSelection.EMPTY; } } }
public static void setHelp(Control control, String pluginId, String helpContextID) { PlatformUI.getWorkbench() .getHelpSystem() .setHelp(control, pluginId + "." + helpContextID); // $NON-NLS-1$ }
@Nullable public static Shell getActiveShell() { IWorkbench workbench = PlatformUI.getWorkbench(); return workbench == null ? null : getShell(workbench.getActiveWorkbenchWindow()); }