Example usage for org.eclipse.jface.action IAction setText

List of usage examples for org.eclipse.jface.action IAction setText

Introduction

In this page you can find the example usage for org.eclipse.jface.action IAction setText.

Prototype

void setText(String text);

Source Link

Document

Sets the text for this action.

Usage

From source file:ca.uvic.chisel.javasketch.ui.internal.presentation.JavaThreadSequenceView.java

License:Open Source License

/**
 * Opens the context menu to be filled with actions.
 * // ww  w  .  j  a  v a  2 s.c  o m
 * @param manager
 */
private void fillContextMenu(IMenuManager manager, Object elementUnderCursor) {
    if (elementUnderCursor instanceof IMessageGrouping) {
        IMessageGrouping grouping = (IMessageGrouping) elementUnderCursor;
        if (elementUnderCursor instanceof IAdaptable) {
            ASTMessageGroupingTree node = (ASTMessageGroupingTree) ((IAdaptable) elementUnderCursor)
                    .getAdapter(ASTMessageGroupingTree.class);
            if (node != null) {
                IActivation activation = (IActivation) grouping.getActivationElement();
                ASTMessageGroupingTree[] iterations = node.getIterations();
                int selected = 0;
                for (int i = 0; i < iterations.length; i++) {
                    ASTMessageGroupingTree iteration = iterations[i];
                    if (!isEmptyIteration(iteration)) {
                        selected++;
                        IAction swapAction = new SwapLoopAction(activation, iteration);
                        swapAction.setText("Iteration " + iteration.getIteration());
                        manager.add(swapAction);
                        if (selected >= 9) {
                            SelectIterationAction selector = new SelectIterationAction(activation, iterations,
                                    this);
                            selector.setText("Select Iteration...");
                            manager.add(selector);
                            break;
                        }
                    }

                }
            }
            return;
        }

    }
    if (focusInAction.isEnabled()) {
        manager.add(focusInAction);
    }
    if (focusUpAction.isEnabled()) {
        manager.add(focusUpAction);
    }
    if (collapseAllAction.isEnabled()) {
        manager.add(collapseAllAction);
    }
    if (expandAllAction.isEnabled()) {
        manager.add(expandAllAction);
    }

    manager.add(createContributionItem(ScreenshotHandler.COMMAND_ID));
}

From source file:ca.uvic.chisel.javasketch.ui.internal.search.TraceSearchResultPage.java

License:Open Source License

@Override
public void createControl(Composite parent) {
    page = new Composite(parent, SWT.NULL);
    page.setLayout(new GridLayout());
    fViewer = new TreeViewer(page, SWT.NONE);
    fViewer.getTree().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    TableLayout tl = new TableLayout();
    fViewer.getTree().setLayout(tl);/*w ww . j a  v a2s  .c o m*/
    // create columns for the viewer
    TreeViewerColumn c = new TreeViewerColumn(fViewer, SWT.NONE);
    c.getColumn().setText("Search Result");
    c.setLabelProvider(new TraceSearchResultLabelProvider());
    GC gc = new GC(fViewer.getTree());
    tl.addColumnData(new ColumnPixelData(Dialog.convertWidthInCharsToPixels(gc.getFontMetrics(), 60)));
    gc.dispose();

    c = new TreeViewerColumn(fViewer, SWT.NONE);
    c.getColumn().setText("Kind");
    c.setLabelProvider(new TraceSearchResultLabelProvider());
    tl.addColumnData(new ColumnPixelData(50));

    c = new TreeViewerColumn(fViewer, SWT.NONE);
    c.getColumn().setText("Trace");
    c.setLabelProvider(new TraceSearchResultLabelProvider());

    tl.addColumnData(new ColumnPixelData(50));
    resultsListener = new TraceSearchResultListener();

    fViewer.getTree().setHeaderVisible(true);

    fViewer.setContentProvider(new TraceSearchResultContentProvider());
    //create a context menu for the viewer so that results can be 
    //linked to
    MenuManager manager = new MenuManager("TraceSearchResultsPage", "#TraceSearchResults");
    Menu menu = manager.createContextMenu(fViewer.getTree());
    manager.setRemoveAllWhenShown(true);
    manager.addMenuListener(new IMenuListener() {

        @Override
        public void menuAboutToShow(IMenuManager manager) {
            fillContextMenu(manager);
            IStructuredSelection ss = (IStructuredSelection) getSite().getSelectionProvider().getSelection();
            if (!ss.isEmpty()) {
                Object o = ss.getFirstElement();
                if (o instanceof IActivation || o instanceof IMessage) {
                    IAction action = new CommandAction(RevealActivationHandler.COMMAND_ID, null);
                    action.setText("Reveal");
                    manager.add(action);
                }
            }
        }
    });
    getSite().registerContextMenu("#TraceSearchResults", manager, fViewer);
    fViewer.getTree().setMenu(menu);
    SelectionForward forward = new SelectionForward();
    fViewer.addSelectionChangedListener(forward);
    getSite().setSelectionProvider(forward);

}

From source file:ca.uvic.chisel.javasketch.ui.internal.TraceActionDelegate.java

License:Open Source License

private void updateAction(IAction action) {
    if (action == null)
        return;/*from ww w  .  j a  va 2s . c  om*/
    IProcess process = DebugUITools.getCurrentProcess();
    ITraceClient client = SketchPlugin.getDefault().getAssociatedClient(process);
    if (client == null || client.isTerminated()) {
        //set the icon to "play"
        action.setImageDescriptor(
                SketchPlugin.imageDescriptorFromPlugin(SketchPlugin.PLUGIN_ID, "images/etool16/play_icon.png"));
        action.setText("Resume Trace");
        action.setToolTipText("Resumes a paused trace");
        action.setChecked(false);
        action.setEnabled(false);
    } else {
        if (client.isPaused()) {
            //set the icon to "play"
            action.setImageDescriptor(SketchPlugin.imageDescriptorFromPlugin(SketchPlugin.PLUGIN_ID,
                    "images/etool16/play_icon.png"));
            action.setText("Resume Trace");
            action.setToolTipText("Resumes a paused trace");
        } else {
            //set the icon to "play"
            action.setImageDescriptor(SketchPlugin.imageDescriptorFromPlugin(SketchPlugin.PLUGIN_ID,
                    "images/etool16/pause_icon.png"));
            action.setText("Pause Trace");
            action.setToolTipText("Pauses a running trace");
        }
        action.setEnabled(true);
    }
}

From source file:ch.elexis.core.ui.laboratory.views.LaborView.java

License:Open Source License

@Override
public void createPartControl(final Composite parent) {
    setTitleImage(Images.IMG_VIEW_LABORATORY.getImage());

    tabFolder = new CTabFolder(parent, SWT.TOP);
    tabFolder.setLayout(new FillLayout());

    final CTabItem resultsTabItem = new CTabItem(tabFolder, SWT.NULL);
    resultsTabItem.setText("Resultate");
    resultsComposite = new LaborResultsComposite(tabFolder, SWT.NONE);
    resultsTabItem.setControl(resultsComposite);

    final CTabItem ordersTabItem = new CTabItem(tabFolder, SWT.NULL);
    ordersTabItem.setText("Verordnungen");
    ordersComposite = new LaborOrdersComposite(tabFolder, SWT.NONE);
    ordersTabItem.setControl(ordersComposite);

    tabFolder.setSelection(0);/*from  ww  w .j a  va2s .  c  o m*/
    tabFolder.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            resultsComposite.reload();
            ordersComposite.reload();
        }
    });
    makeActions();
    menu = new ViewMenus(getViewSite());
    menu.createMenu(newAction, backAction, fwdAction, printAction, importAction, xmlAction);
    // Orders
    final LaborOrderPulldownMenuCreator menuCreator = new LaborOrderPulldownMenuCreator(parent.getShell());
    if (menuCreator.getSelected() != null) {
        IAction dropDownAction = menuCreator.getAction();

        IActionBars actionBars = getViewSite().getActionBars();
        IToolBarManager toolbar = actionBars.getToolBarManager();

        toolbar.add(dropDownAction);

        // Set data
        dropDownAction.setText(menuCreator.getSelected().getText());
        dropDownAction.setToolTipText(menuCreator.getSelected().getToolTipText());
        dropDownAction.setImageDescriptor(menuCreator.getSelected().getImageDescriptor());
    }
    // Importers
    IToolBarManager tm = getViewSite().getActionBars().getToolBarManager();
    List<IAction> importers = Extensions.getClasses(
            Extensions.getExtensions(ExtensionPointConstantsUi.LABORDATENIMPORT), "ToolbarAction", //$NON-NLS-1$ //$NON-NLS-2$
            false);
    for (IAction ac : importers) {
        tm.add(ac);
    }
    if (importers.size() > 0) {
        tm.add(new Separator());
    }
    tm.add(refreshAction);
    tm.add(newColumnAction);
    tm.add(newAction);
    tm.add(backAction);
    tm.add(fwdAction);
    tm.add(expandAllAction);
    tm.add(collapseAllAction);
    tm.add(printAction);

    // register event listeners
    ElexisEventDispatcher.getInstance().addListeners(eeli_labitem, eeli_laborder, eeli_labresult, eeli_pat);
    Patient act = (Patient) ElexisEventDispatcher.getSelected(Patient.class);
    if ((act != null && act != resultsComposite.getPatient())) {
        resultsComposite.selectPatient(act);
    }
}

From source file:ch.elexis.views.LaborView.java

License:Open Source License

@Override
public void createPartControl(final Composite parent) {
    setTitleImage(Desk.getImage(ICON));/*from  w  w  w.j  a  v a 2s .c o  m*/
    parent.setLayout(new GridLayout());
    form = tk.createForm(parent);
    form.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
    Composite body = form.getBody();
    body.setLayout(new GridLayout());

    table = new Table(body, SWT.FULL_SELECTION | SWT.LEFT | SWT.V_SCROLL | SWT.H_SCROLL);
    table.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
    table.setHeaderVisible(true);
    table.setLinesVisible(true);

    table.addListener(SWT.PaintItem, new Listener() {

        private void paintCell(final String text, final Event event, final Color foregnd, final Color backgnd) {
            Point size = event.gc.textExtent(text);
            int offset1 = Math.max(0, (event.width - size.x) / 2);
            int offset2 = Math.max(0, (event.height - size.y) / 2);
            GC gc = event.gc;
            gc.setForeground(backgnd);
            gc.fillRectangle(event.x, event.y, event.width, event.height);
            gc.setForeground(foregnd);
            event.gc.drawText(text, event.x + offset1, event.y + offset2, true);
        }

        public void handleEvent(final Event event) {
            TableItem item = (TableItem) event.item;
            String text = item.getText(event.index);
            LabItem it = (LabItem) item.getData(KEY_ITEM);
            if (it != null) {
                LabResult[] lrs = (LabResult[]) item.getData(KEY_VALUES);
                if (lrs != null) {
                    int screenIdx = event.index - COL_OFFSET;
                    if ((screenIdx >= 0) && (screenIdx < lrs.length)) {
                        LabResult lr = lrs[screenIdx];
                        if (lr != null) {
                            if (lr.isFlag(LabResult.PATHOLOGIC)) {
                                paintCell(text, event, COL_PATHOLOGIC, COL_BACKGND);
                            }
                            if (lr.getComment().length() > 0) {
                                paintCell(text, event, COL_REMARK, COL_BACKGND);
                            }
                        }
                    }
                }
            }
        }

    });

    cursor = new TableCursor(table, SWT.NONE);
    editor = new ControlEditor(cursor);
    editor.grabHorizontal = true;
    editor.grabVertical = true;

    /*
     * Tastatursteuerung fr die Tabelle: Druck auf Eingabetaste lsst die Zelle editieren,
     * sofern sie auf einem editierbaren Feld ist. Wenn sie nicht auf einem editierbaren Feld
     * ist, wird der stattdessen Cursor eine Zeile nach unten bewegt. Druck auf irgendeine Zahl-
     * oder Buchstabentaste lsst die Zelle editieren, wenn sie editierbar ist. Editierbar ist
     * eine Zelle dann, wenn sie sich a) in einer Spalte mit einem Datum im Kopf befindet, und
     * b) sich in einer Zeile mit einem LaborItem am Anfang befindet.
     */
    cursor.addSelectionListener(new SelectionAdapter() {
        // Tabellenauswahl soll dem Cursor folgen
        @Override
        public void widgetSelected(final SelectionEvent e) {
            table.setSelection(new TableItem[] { cursor.getRow() });
        }

        // Eingabetaste
        @Override
        public void widgetDefaultSelected(final SelectionEvent e) {

            TableItem row = cursor.getRow();
            LabItem li = (LabItem) row.getData(KEY_ITEM);
            if (li == null) {
                cursorDown();
                return;
            }
            int column = cursor.getColumn();
            if (columns[column].getText().matches(PATTERN_DECIMAL)) {
                doEdit(row.getText(column));
            }

        }
    });
    // Sonstige Taste
    cursor.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(final KeyEvent e) {
            if (e.character == SWT.DEL) {
                return;
            }
            TableItem row = cursor.getRow();
            e.doit = false;
            if (row.getData(KEY_ITEM) == null) {
                return;
            }
            if (e.character > 0x30) {
                StringBuilder sb = new StringBuilder();
                sb.append(e.character);
                int column = cursor.getColumn();
                if (columns[column].getText().matches(PATTERN_DECIMAL)) {
                    doEdit(sb.toString());
                }
            }
        }
    });
    cursor.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseDoubleClick(final MouseEvent e) {
            LabResult lr = actResult();
            if (lr != null) {
                LabItem li = lr.getItem();
                if (li.getTyp().equals(LabItem.typ.TEXT) || (lr.getComment().length() > 0)) {
                    DisplayTextDialog dlg = new DisplayTextDialog(getViewSite().getShell(),
                            Messages.getString("LaborView.textResultTitle"), li.getName(), lr.getComment()); //$NON-NLS-1$
                    Font font = null;
                    // HL7 Befunde enthalten oft mit Leerzeichen formatierte Bemerkungen,
                    // die nur mit nicht-proportionalen Fonts dargestellt werden knnen
                    // Wir versuchen also, die Anzeige mit Courier New, ohne zu wissen ob die
                    // auf Mac und Linux auch drauf sind.
                    // Falls der Font nicht geladen werden kann, wird der System-Default Font
                    // verwendet
                    // Hier die Fonts, welche getestet worden sind:
                    // Windows: Courier New (getestet=
                    // Mac: nicht getestet
                    // Linux: nicht getestet
                    try {
                        font = new Font(null, "Courier New", 9, SWT.NORMAL); //$NON-NLS-1$
                    } catch (Exception ex) {
                        // Do nothing -> Use System Default font
                    } finally {
                        dlg.setFont(font);
                    }
                    dlg.setWhitespaceNormalized(false);
                    dlg.open();
                } else if (li.getTyp().equals(LabItem.typ.DOCUMENT)) {
                    Patient patient = ElexisEventDispatcher.getSelectedPatient();
                    if (patient != null) {
                        Query<LabResult> labResultQuery = new Query<LabResult>(LabResult.class);
                        labResultQuery.add(LabResult.PATIENT_ID, Query.EQUALS, patient.getId());
                        labResultQuery.add(LabResult.DATE, Query.EQUALS, lr.getDate());
                        labResultQuery.add(LabResult.ITEM_ID, Query.EQUALS, li.getId());
                        List<LabResult> labResultList = labResultQuery.execute();
                        if (labResultList != null && labResultList.size() > 0) {
                            new DisplayLabDokumenteDialog(getViewSite().getShell(),
                                    Messages.getString("LaborView.Documents"), labResultList).open();//$NON-NLS-1$
                        }
                    }
                }
            }
            super.mouseDoubleClick(e);
        }

    });

    makeActions();
    menu = new ViewMenus(getViewSite());
    menu.createMenu(newAction, backAction, fwdAction, printAction, importAction, xmlAction);
    // Orders
    final LaborOrderPulldownMenuCreator menuCreator = new LaborOrderPulldownMenuCreator(parent.getShell());
    if (menuCreator.getSelected() != null) {
        IAction dropDownAction = menuCreator.getAction();

        IActionBars actionBars = getViewSite().getActionBars();
        IToolBarManager toolbar = actionBars.getToolBarManager();

        toolbar.add(dropDownAction);

        // Set data
        dropDownAction.setText(menuCreator.getSelected().getText());
        dropDownAction.setToolTipText(menuCreator.getSelected().getToolTipText());
        dropDownAction.setImageDescriptor(menuCreator.getSelected().getImageDescriptor());
    }
    // Importers
    IToolBarManager tm = getViewSite().getActionBars().getToolBarManager();
    List<IAction> importers = Extensions.getClasses(Extensions.getExtensions("ch.elexis.LaborDatenImport"), //$NON-NLS-1$
            "ToolbarAction", //$NON-NLS-1$
            false);
    for (IAction ac : importers) {
        tm.add(ac);
    }
    if (importers.size() > 0) {
        tm.add(new Separator());
    }
    tm.add(refreshAction);
    tm.add(newAction);
    tm.add(backAction);
    tm.add(fwdAction);
    tm.add(printAction);
    // menu.createToolbar(newAction,backAction,fwdAction,printAction);
    final MenuManager mgr = new MenuManager("path"); //$NON-NLS-1$
    Menu menu = mgr.createContextMenu(cursor);
    mgr.setRemoveAllWhenShown(true);
    mgr.addMenuListener(new IMenuListener() {
        public void menuAboutToShow(final IMenuManager manager) {
            LabResult lr = getSelectedResult();
            if (lr != null) {
                LabItem li = lr.getItem();
                if (!li.getTyp().equals(LabItem.typ.DOCUMENT)) {
                    mgr.add(setStateAction);
                    setStateAction.setChecked(lr.isFlag(LabResult.PATHOLOGIC));
                }
            }

        }
    });
    cursor.setMenu(menu);
    // menu.createControlContextMenu(cursor, setStateAction);
    rebuild();
    GlobalEventDispatcher.addActivationListener(this, this);
}

From source file:com.amalto.workbench.compare.Utilities.java

License:Open Source License

public static void initAction(IAction a, ResourceBundle bundle, String prefix) {

    String labelKey = "label"; //$NON-NLS-1$
    String tooltipKey = "tooltip"; //$NON-NLS-1$
    String imageKey = "image"; //$NON-NLS-1$
    String descriptionKey = "description"; //$NON-NLS-1$

    if (prefix != null && prefix.length() > 0) {
        labelKey = prefix + labelKey;//from w  w  w. j  a va  2 s  .  c om
        tooltipKey = prefix + tooltipKey;
        imageKey = prefix + imageKey;
        descriptionKey = prefix + descriptionKey;
    }

    a.setText(getString(bundle, labelKey, labelKey));
    a.setToolTipText(getString(bundle, tooltipKey, null));
    a.setDescription(getString(bundle, descriptionKey, null));

    String relPath = getString(bundle, imageKey, null);
    if (relPath != null && relPath.trim().length() > 0) {

        String dPath;
        String ePath;

        if (relPath.indexOf("/") >= 0) { //$NON-NLS-1$
            String path = relPath.substring(1);
            dPath = 'd' + path;
            ePath = 'e' + path;
        } else {
            dPath = "dlcl16/" + relPath; //$NON-NLS-1$
            ePath = "elcl16/" + relPath; //$NON-NLS-1$
        }

        // ImageDescriptor id= CompareUIPlugin.getImageDescriptor(dPath); // we set the disabled image first (see PR
        // 1GDDE87)
        // if (id != null)
        // a.setDisabledImageDescriptor(id);
        // id= CompareUIPlugin.getImageDescriptor(ePath);
        // if (id != null) {
        // a.setImageDescriptor(id);
        // a.setHoverImageDescriptor(id);
        // }
    }
}

From source file:com.android.ide.eclipse.adt.internal.editors.layout.gle2.DynamicContextMenu.java

License:Open Source License

private IAction createPlainAction(final RuleAction action, final List<INode> nodes, final String defaultId) {
    IAction a = new Action(action.getTitle(), IAction.AS_PUSH_BUTTON) {
        @Override/*  w w  w .  ja v a2 s . c o m*/
        public void run() {
            String label = createActionLabel(action, nodes);
            mEditorDelegate.getEditor().wrapUndoEditXmlModel(label, new Runnable() {
                @Override
                public void run() {
                    action.getCallback().action(action, nodes, null, Boolean.TRUE);
                    applyPendingChanges();
                }
            });
        }
    };

    String id = action.getId();
    if (defaultId != null && id.equals(defaultId)) {
        a.setAccelerator(DEFAULT_ACTION_KEY);
        String text = a.getText();
        text = text + '\t' + DEFAULT_ACTION_SHORTCUT;
        a.setText(text);

    } else if (ATTR_ID.equals(id)) {
        // Keep in sync with {@link LayoutCanvas#handleKeyPressed}
        if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_DARWIN) {
            a.setAccelerator('R' | SWT.MOD1 | SWT.MOD3);
            // Option+Command
            a.setText(a.getText().trim() + "\t\u2325\u2318R"); //$NON-NLS-1$
        } else if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_LINUX) {
            a.setAccelerator('R' | SWT.MOD2 | SWT.MOD3);
            a.setText(a.getText() + "\tShift+Alt+R"); //$NON-NLS-1$
        } else {
            a.setAccelerator('R' | SWT.MOD2 | SWT.MOD3);
            a.setText(a.getText() + "\tAlt+Shift+R"); //$NON-NLS-1$
        }
    }
    a.setId(id);
    return a;
}

From source file:com.aptana.editor.js.views.JSIndexViewActionProvider.java

License:Open Source License

/**
 * @param view//w  w w.  ja  v a2  s.c  o m
 * @param typeNames
 * @return
 */
protected IAction createAction(final IndexView view, final List<String> typeNames) {
    IAction action = new Action() {
        @Override
        public void run() {
            TreeViewer treeViewer = view.getTreeViewer();

            if (treeViewer != null) {
                Object input = treeViewer.getInput();

                if (input instanceof IProject) {
                    IProject project = (IProject) input;

                    Index index = getIndexManager().getIndex(project.getLocationURI());
                    JSIndexQueryHelper queryHelper = new JSIndexQueryHelper();
                    Collection<TypeElement> types = queryHelper.getTypes(index, typeNames.get(0), true);
                    List<ClassElement> classes = JSTypeUtil.typesToClasses(types);

                    if (!CollectionsUtil.isEmpty(classes)) {
                        ClassElement c = classes.get(0);

                        treeViewer.setSelection(new StructuredSelection(c), true);
                    }
                }
            }
        }
    };

    action.setText(Messages.JSIndexViewActionProvider_JumpToType);

    return action;
}

From source file:com.aptana.ide.server.ui.views.GenericServersView.java

License:Open Source License

/**
 * Creates and registers the context menu
 *///from   w  w  w  .  ja  va  2s.c om
private void createPopupMenu() {
    deleteAction = ActionFactory.DELETE.create(getViewSite().getWorkbenchWindow());
    MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
    menuMgr.setRemoveAllWhenShown(true);
    getViewSite().getActionBars().setGlobalActionHandler(ActionFactory.DELETE.getId(), new Action() {

        public void run() {
            doDelete();
        }
    });
    menuMgr.addMenuListener(new IMenuListener() {
        public void menuAboutToShow(IMenuManager manager) {
            IContributionItem[] items = getViewSite().getActionBars().getToolBarManager().getItems();
            for (int i = 0; i < items.length; i++) {

                if (items[i] instanceof ActionContributionItem) {
                    ActionContributionItem aci = (ActionContributionItem) items[i];
                    IAction action = aci.getAction();
                    if (action == openLog) {
                        // adds the Open Log action to the context menu as a push button instead of 
                        // drop-down
                        boolean enabled = action.isEnabled();
                        action = new OpenLogAction(serverViewer, Action.AS_PUSH_BUTTON);
                        action.setEnabled(enabled);
                    }
                    if (action.isEnabled() && action.getStyle() != Action.AS_DROP_DOWN_MENU) {
                        if (action.getText() == null || action.getText().length() == 0) {
                            action.setText(action.getToolTipText());
                        }
                        manager.add(action);
                    }
                } else {
                    if (items[i] instanceof Separator) {
                        manager.add(new Separator());
                    }
                }
            }
            manager.add(new Separator());
            IStructuredSelection selection = (IStructuredSelection) serverViewer.getSelection();
            final IServer server = (IServer) selection.getFirstElement();
            if (server != null) {
                deleteAction.setText(StringUtils.format(Messages.ServersView_DELETE, getShortenName(server)));
                // deleteAction.setEnabled(server.getServerState() == IServer.STATE_STOPPED);
                deleteAction.setEnabled(server.canDelete().isOK());
                manager.add(deleteAction);

                Action action = new Action() {
                    public void run() {
                        doEdit(server);
                    }
                };
                action.setText(StringUtils.format(Messages.ServersView_EDIT, getShortenName(server)));
                IStatus canModify = server.canModify();
                IStatus canModifyInStoppedStateOnly = server.canModifyInStoppedStateOnly();
                action.setEnabled(((canModifyInStoppedStateOnly == null
                        || canModifyInStoppedStateOnly.getCode() == IStatus.OK)
                                ? server.getServerState() == IServer.STATE_STOPPED
                                : true)
                        && (canModify == null || canModify.getCode() == IStatus.OK));
                manager.add(action);
            }
            // deleteAction.setEnabled(!selection.isEmpty());
            manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); // Allow
        }

        private String getShortenName(final IServer server) {
            String name = server.getName();
            int length = name.length();
            if (length > MAX_SHOWN_SERVER_NAME) {
                int delta = (length - 15) / 2;
                int pivot = length / 2;
                int start = pivot - delta;
                int end = pivot + delta;
                String s1 = name.substring(0, start);
                String s2 = name.substring(end, length);
                String s = s1 + ELLIPSIS + s2;
                return s;
            }
            return name;
        }
    });
    Menu menu = menuMgr.createContextMenu(serverViewer.getControl());
    serverViewer.getControl().setMenu(menu);
    getSite().registerContextMenu(menuMgr, serverViewer);
}

From source file:com.archimatetool.editor.diagram.AbstractDiagramEditor.java

License:Open Source License

/**
 * Add some extra Actions - *after* the graphical viewer has been created
 *///from   w  w w .  j a  v a 2 s. c  o m
@SuppressWarnings("unchecked")
protected void createActions(GraphicalViewer viewer) {
    ActionRegistry registry = getActionRegistry();
    IAction action;

    // Zoom Manager tweaking
    ZoomManager zoomManager = (ZoomManager) getAdapter(ZoomManager.class);
    double[] zoomLevels = { .25, .5, .75, 1, 1.5, 2, 3, 4, 6, 8 };
    zoomManager.setZoomLevels(zoomLevels);
    List<String> zoomContributionLevels = new ArrayList<String>();
    zoomContributionLevels.add(ZoomManager.FIT_ALL);
    zoomContributionLevels.add(ZoomManager.FIT_WIDTH);
    zoomContributionLevels.add(ZoomManager.FIT_HEIGHT);
    zoomManager.setZoomLevelContributions(zoomContributionLevels);

    // Zoom Actions
    IAction zoomIn = new ZoomInAction(zoomManager);
    IAction zoomOut = new ZoomOutAction(zoomManager);
    registry.registerAction(zoomIn);
    registry.registerAction(zoomOut);

    // Add these zoom actions to the key binding service
    IHandlerService service = (IHandlerService) getEditorSite().getService(IHandlerService.class);
    service.activateHandler(zoomIn.getActionDefinitionId(), new ActionHandler(zoomIn));
    service.activateHandler(zoomOut.getActionDefinitionId(), new ActionHandler(zoomOut));

    // Add our own Select All Action so we can select connections as well
    action = new SelectAllAction(this);
    registry.registerAction(action);

    // Add our own Print Action
    action = new PrintDiagramAction(this);
    registry.registerAction(action);

    // Direct Edit Rename
    action = new DirectEditAction(this);
    action.setId(ActionFactory.RENAME.getId()); // Set this for Global Handler
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Change the Delete Action label
    action = registry.getAction(ActionFactory.DELETE.getId());
    action.setText(Messages.AbstractDiagramEditor_2);
    action.setToolTipText(action.getText());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Paste
    PasteAction pasteAction = new PasteAction(this, viewer);
    registry.registerAction(pasteAction);
    getSelectionActions().add(pasteAction.getId());

    // Cut
    action = new CutAction(this, pasteAction);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Copy
    action = new CopyAction(this, pasteAction);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Use Grid Action
    action = new ToggleGridEnabledAction();
    registry.registerAction(action);

    // Show Grid Action
    action = new ToggleGridVisibleAction();
    registry.registerAction(action);

    // Snap to Alignment Guides
    action = new ToggleSnapToAlignmentGuidesAction();
    registry.registerAction(action);

    // Ruler
    //IAction showRulers = new ToggleRulerVisibilityAction(getGraphicalViewer());
    //registry.registerAction(showRulers);

    action = new MatchWidthAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());

    action = new MatchHeightAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());

    action = new AlignmentAction((IWorkbenchPart) this, PositionConstants.LEFT);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());

    action = new AlignmentAction((IWorkbenchPart) this, PositionConstants.RIGHT);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());

    action = new AlignmentAction((IWorkbenchPart) this, PositionConstants.TOP);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());

    action = new AlignmentAction((IWorkbenchPart) this, PositionConstants.BOTTOM);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());

    action = new AlignmentAction((IWorkbenchPart) this, PositionConstants.CENTER);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());

    action = new AlignmentAction((IWorkbenchPart) this, PositionConstants.MIDDLE);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());

    // Default Size
    action = new DefaultEditPartSizeAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Reset Aspect Ratio
    action = new ResetAspectRatioAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Properties
    action = new PropertiesAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());

    // Fill Colour
    action = new FillColorAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Connection Line Width
    action = new ConnectionLineWidthAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Connection Line Color
    action = new LineColorAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Font
    action = new FontAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Font Colour
    action = new FontColorAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Export As Image
    action = new ExportAsImageAction(viewer);
    registry.registerAction(action);

    // Export As Image to Clipboard
    action = new ExportAsImageToClipboardAction(viewer);
    registry.registerAction(action);

    // Connection Router types
    action = new ConnectionRouterAction.BendPointConnectionRouterAction(this);
    registry.registerAction(action);
    action = new ConnectionRouterAction.ShortestPathConnectionRouterAction(this);
    registry.registerAction(action);
    action = new ConnectionRouterAction.ManhattanConnectionRouterAction(this);
    registry.registerAction(action);

    // Send Backward
    action = new SendBackwardAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Bring Forward
    action = new BringForwardAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Send to Back
    action = new SendToBackAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Bring To Front
    action = new BringToFrontAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Text Alignment Actions
    for (TextAlignmentAction a : TextAlignmentAction.createActions(this)) {
        registry.registerAction(a);
        getSelectionActions().add(a.getId());
        getUpdateCommandStackActions().add(a);
    }

    // Text Position Actions
    for (TextPositionAction a : TextPositionAction.createActions(this)) {
        registry.registerAction(a);
        getSelectionActions().add(a.getId());
        getUpdateCommandStackActions().add(a);
    }

    // Lock Object
    action = new LockObjectAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Border Color
    action = new BorderColorAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
    getUpdateCommandStackActions().add((UpdateAction) action);

    // Full Screen
    if (!PlatformUtils.supportsMacFullScreen()) {
        action = new FullScreenAction(this);
        registry.registerAction(action);
    }

    // Select Element in Tree
    action = new SelectElementInTreeAction(this);
    registry.registerAction(action);
    getSelectionActions().add(action.getId());
}