Example usage for org.eclipse.jface.viewers StructuredSelection size

List of usage examples for org.eclipse.jface.viewers StructuredSelection size

Introduction

In this page you can find the example usage for org.eclipse.jface.viewers StructuredSelection size.

Prototype

@Override
    public int size() 

Source Link

Usage

From source file:info.novatec.inspectit.rcp.preferences.page.CmrRepositoryPreferencePage.java

/**
 * Updates the state of the remove and license info buttons depending on the current table
 * selection.//from   w w w  .jav  a 2s .co  m
 */
private void updateButtonsState() {
    StructuredSelection structuredSelection = (StructuredSelection) tableViewer.getSelection();
    if (structuredSelection.isEmpty()) {
        removeButton.setEnabled(false);
        manageLabelsButton.setEnabled(false);
    } else {
        removeButton.setEnabled(true);
        if (structuredSelection.size() == 1 && ((CmrRepositoryDefinition) structuredSelection.getFirstElement())
                .getOnlineStatus() == OnlineStatus.ONLINE) {
            manageLabelsButton.setEnabled(true);
        } else {
            manageLabelsButton.setEnabled(false);
        }
    }
}

From source file:info.vancauwenberge.designer.enhtrace.action.OpenTraceAction.java

License:Mozilla Public License

@Override
public void run(IAction action) {
    System.out.println("OpenTraceAction.run() action=" + action);
    System.out.println("OpenTraceAction.run() action=" + action.getId());
    System.out.println("OpenTraceAction.run() action=" + action.getText());
    System.out.println("OpenTraceAction.run() selection=" + selection.getClass().getName());
    System.out.println("OpenTraceAction.run() selection=" + selection.getClass().getGenericInterfaces());
    if (selection instanceof com.novell.idm.model.Server) {
        com.novell.idm.model.Server server = (com.novell.idm.model.Server) selection;
        System.out.println("selectedObject:" + server.getDirectoryDN());
        openEditor(server);//  w  ww  .  j a  v a 2 s  . com
    } else if (selection instanceof StructuredSelection) {

        StructuredSelection structuredSelection = (StructuredSelection) selection;
        Object selectedObject = structuredSelection.getFirstElement();
        System.out.println("selectedObject:" + selectedObject.getClass().getName());
        System.out.println("selectedObject:" + structuredSelection.size());
        if (selectedObject instanceof com.novell.idm.model.Server) {
            com.novell.idm.model.Server server = (com.novell.idm.model.Server) selectedObject;
            System.out.println("selectedObject:" + server.getDirectoryDN());
            openEditor(server);
            //LiveTraceEditorInput input = Activator.registerDSTraceListener();
        }
    }

}

From source file:io.sarl.eclipse.wizards.elements.AbstractSuperTypeSelectionDialog.java

License:Apache License

@Override
protected void handleSelected(StructuredSelection selection) {
    super.handleSelected(selection);

    if (selection.size() == 0 && getSuperTypeCount(this.typeWizardPage) > this.oldContent.size()) {
        // overrides updateStatus() from handleSelected() if
        // list of super interfaces was modified
        // the <code>super.handleSelected(selection)</code> has to be
        // called, because superclass implementation of this class updates
        // state of the table.

        updateStatus(Status.OK_STATUS);/*w  w  w.  ja  v a 2  s  .co  m*/

        getButton(ADD_ID).setEnabled(false);
    } else {
        // if selection isn't empty, the add button should be enabled in
        // exactly the same scenarios as the OK button
        getButton(ADD_ID).setEnabled(getButton(OK).isEnabled());
    }
}

From source file:net.enilink.komma.edit.ui.dialogs.FilteredList.java

License:Open Source License

public Control createControl(Composite parent) {
    composite = new Composite(parent, SWT.NONE);
    composite.addDisposeListener(new DisposeListener() {
        @Override/* w w w. j  a  va 2s.  co m*/
        public void widgetDisposed(DisposeEvent e) {
            filterJob.cancel();
            refreshCacheJob.cancel();
            refreshProgressMessageJob.cancel();
        }
    });

    filterHistoryJob = new FilterHistoryJob();
    filterJob = new FilterJob();
    contentProvider = new ContentProvider();
    refreshCacheJob = new RefreshCacheJob();
    refreshProgressMessageJob = new RefreshProgressMessageJob();
    itemsListSeparator = new ItemsListSeparator(DialogMessages.FilteredItemsSelectionDialog_separatorLabel);
    selectionMode = NONE;

    GridLayout gridLayout = new GridLayout(1, false);
    gridLayout.marginHeight = 0;
    gridLayout.marginWidth = 0;
    composite.setLayout(gridLayout);
    createPatternAndMenu(composite);
    createLabels(composite);

    list = new TableViewer(composite,
            (multi ? SWT.MULTI : SWT.SINGLE) | SWT.BORDER | SWT.V_SCROLL | SWT.VIRTUAL);
    list.setContentProvider(contentProvider);
    list.setLabelProvider(getItemsListLabelProvider());
    list.setInput(new Object[0]);
    list.setItemCount(contentProvider.getElements(null).length);
    GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
    list.getTable().setLayoutData(gd);

    createPopupMenu();

    pattern.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            applyFilter();
        }
    });

    pattern.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            if (e.keyCode == SWT.ARROW_DOWN) {
                if (list.getTable().getItemCount() > 0) {
                    list.getTable().setFocus();
                }
            }
        }
    });

    list.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            StructuredSelection selection = (StructuredSelection) event.getSelection();
            handleSelected(selection);
        }
    });

    list.getTable().addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {

            if (e.keyCode == SWT.DEL) {

                List<?> selectedElements = ((StructuredSelection) list.getSelection()).toList();

                boolean isSelectedHistory = true;

                for (Object item : selectedElements) {
                    if (item instanceof ItemsListSeparator || !isHistoryElement(item)) {
                        isSelectedHistory = false;
                        break;
                    }
                }
                if (isSelectedHistory)
                    removeSelectedItems(selectedElements);

            }

            if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.SHIFT) != 0 && (e.stateMask & SWT.CTRL) != 0) {
                StructuredSelection selection = (StructuredSelection) list.getSelection();

                if (selection.size() == 1) {
                    Object element = selection.getFirstElement();
                    if (element.equals(list.getElementAt(0))) {
                        pattern.setFocus();
                    }
                    if (list.getElementAt(
                            list.getTable().getSelectionIndex() - 1) instanceof ItemsListSeparator)
                        list.getTable().setSelection(list.getTable().getSelectionIndex() - 1);
                    list.getTable().notifyListeners(SWT.Selection, new Event());

                }
            }

            if (e.keyCode == SWT.ARROW_DOWN && (e.stateMask & SWT.SHIFT) != 0
                    && (e.stateMask & SWT.CTRL) != 0) {

                if (list.getElementAt(list.getTable().getSelectionIndex() + 1) instanceof ItemsListSeparator)
                    list.getTable().setSelection(list.getTable().getSelectionIndex() + 1);
                list.getTable().notifyListeners(SWT.Selection, new Event());
            }

        }
    });

    details = new DetailsContentViewer(composite, SWT.BORDER | SWT.FLAT);
    details.setVisible(toggleStatusLineAction.isChecked());
    details.setContentProvider(new NullContentProvider());
    details.setLabelProvider(getDetailsLabelProvider());

    if (initialPatternText != null) {
        pattern.setText(initialPatternText);
    }

    switch (selectionMode) {
    case CARET_BEGINNING:
        pattern.setSelection(0, 0);
        break;
    case FULL_SELECTION:
        pattern.setSelection(0, initialPatternText.length());
        break;
    }

    // apply filter even if pattern is empty (display history)
    applyFilter();
    pattern.setFocus();

    return composite;
}

From source file:net.enilink.komma.edit.ui.dialogs.FilteredList.java

License:Open Source License

/**
 * Refreshes the details field according to the current selection in the
 * items list.//from   w w w.  jav  a2 s.  com
 */
private void refreshDetails() {
    StructuredSelection selection = getSelectedItems();

    switch (selection.size()) {
    case 0:
        details.setInput(null);
        break;
    case 1:
        details.setInput(selection.getFirstElement());
        break;
    default:
        details.setInput(NLS.bind(DialogMessages.FilteredItemsSelectionDialog_nItemsSelected,
                new Integer(selection.size())));
        break;
    }

}

From source file:net.enilink.komma.edit.ui.dialogs.FilteredList.java

License:Open Source License

/**
 * Handle selection in the items list by updating labels of selected and
 * unselected items and refresh the details field using the selection.
 * /*from   w  ww.  j av a  2s  .  com*/
 * @param selection
 *            the new selection
 */
protected void handleSelected(StructuredSelection selection) {
    IStatus status = new Status(IStatus.OK, PlatformUI.PLUGIN_ID, IStatus.OK, EMPTY_STRING, null);

    if (selection.size() == 0) {
        status = new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, IStatus.ERROR, EMPTY_STRING, null);

        if (lastSelection != null && getListSelectionLabelDecorator() != null) {
            list.update(lastSelection, null);
        }

        lastSelection = null;

    } else {
        status = new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, IStatus.ERROR, EMPTY_STRING, null);

        List<?> items = selection.toList();

        Object item = null;
        IStatus tempStatus = null;

        for (Object o : items) {
            if (o instanceof ItemsListSeparator) {
                continue;
            }

            item = o;
            tempStatus = validateItem(item);

            if (tempStatus.isOK()) {
                status = new Status(IStatus.OK, PlatformUI.PLUGIN_ID, IStatus.OK, EMPTY_STRING, null);
            } else {
                status = tempStatus;
                // if any selected element is not valid status is set to
                // ERROR
                break;
            }
        }

        if (lastSelection != null && getListSelectionLabelDecorator() != null) {
            list.update(lastSelection, null);
        }

        if (getListSelectionLabelDecorator() != null) {
            list.update(items.toArray(), null);
        }

        lastSelection = items.toArray();
    }

    refreshDetails();
    updateStatus(status);
}

From source file:net.karlmartens.ui.widget.GridChooser.java

License:Apache License

private static int minSelectionOrder(TableViewer viewer) {
    final StructuredSelection selection = (StructuredSelection) viewer.getSelection();
    if (selection.isEmpty())
        return -1;

    final GridChooserItem[] items = new GridChooserItem[selection.size()];
    System.arraycopy(selection.toArray(), 0, items, 0, selection.size());

    int index = items[0].getSelectionOrder();
    for (int i = 1; i < items.length; i++) {
        final int candidate = items[i].getSelectionOrder();
        if (index > candidate) {
            index = candidate;/*from  ww w .  j a v  a 2 s .  c  om*/
        }
    }
    return index;
}

From source file:net.karlmartens.ui.widget.GridChooser.java

License:Apache License

private static int maxSelectionOrder(TableViewer viewer) {
    final StructuredSelection selection = (StructuredSelection) viewer.getSelection();
    if (selection.isEmpty())
        return -1;

    final GridChooserItem[] items = new GridChooserItem[selection.size()];
    System.arraycopy(selection.toArray(), 0, items, 0, selection.size());

    int index = items[0].getSelectionOrder();
    for (int i = 1; i < items.length; i++) {
        final int candidate = items[i].getSelectionOrder();
        if (index < candidate) {
            index = candidate;/*  w w  w .  j av  a 2 s  .c om*/
        }
    }
    return index;
}

From source file:net.sf.jmoney.reconciliation.reconcilePage.StatementSection.java

License:Open Source License

@SuppressWarnings("unchecked")
public StatementSection(Composite parent, FormToolkit toolkit, ReconcileEditor page,
        RowSelectionTracker<EntryRowControl> rowTracker) {
    super(parent, toolkit, Section.TITLE_BAR);
    getSection().setText("Entries Shown on Statement");
    fPage = page;//w  w  w  . j a  v a2  s  .c  o  m
    this.toolkit = toolkit;

    container = toolkit.createComposite(getSection());

    reconciledTableContents = new IEntriesContent() {
        public Collection<Entry> getEntries() {
            Vector<Entry> requiredEntries = new Vector<Entry>();

            // If no statement is set, return an empty collection.
            // The table will not be visible in this situation, but
            // this method will be called and so we must allow for
            // this situation.
            if (fPage.getStatement() == null) {
                return requiredEntries;
            }

            /* The caller always sorts, so there is no point in us returning
             * sorted results.  It may be at some point we decide it is more
             * efficient to get the database to sort for us, but that would
             * only help the first time the results are fetched, it would not
             * help on a re-sort.  It also only helps if the database indexes
             * on the date.      
            CurrencyAccount account = fPage.getAccount();
              Collection<Entry> accountEntries = 
                 account
                  .getSortedEntries(TransactionInfo.getDateAccessor(), false);
            */
            Collection<Entry> accountEntries = fPage.getAccount().getEntries();

            for (Entry entry : accountEntries) {
                BankStatement statement = entry
                        .getPropertyValue(ReconciliationEntryInfo.getStatementAccessor());
                if (fPage.getStatement().equals(statement)) {
                    requiredEntries.add(entry);
                }
            }

            return requiredEntries;
        }

        public boolean isEntryInTable(Entry entry) {
            // If no statement is set, nothing is in the table.
            // The table will not be visible in this situation, but
            // this method will be called and so we must allow for
            // this situation.
            if (fPage.getStatement() == null) {
                return false;
            }

            // This entry is to be shown if both the account and
            // the statement match.
            BankStatement statement = entry.getPropertyValue(ReconciliationEntryInfo.getStatementAccessor());
            return fPage.getAccount().equals(entry.getAccount()) && fPage.getStatement().equals(statement);
        }

        public boolean filterEntry(EntryData data) {
            // No filter here, so entries always match
            return true;
        }

        public long getStartBalance() {
            return openingBalance;
        }

        public Entry createNewEntry(Transaction newTransaction) {
            Entry entryInTransaction = newTransaction.createEntry();
            Entry otherEntry = newTransaction.createEntry();

            setNewEntryProperties(entryInTransaction);

            // TODO: See if this code has any effect, and
            // should this be here at all?
            /*
             * We set the currency by default to be the currency of the
             * top-level entry.
             * 
             * The currency of an entry is not applicable if the entry is an
             * entry in a currency account or an income and expense account
             * that is restricted to a single currency.
             * However, we set it anyway so the value is there if the entry
             * is set to an account which allows entries in multiple currencies.
             * 
             * It may be that the currency of the top-level entry is not
             * known. This is not possible if entries in a currency account
             * are being listed, but may be possible if this entries list
             * control is used for more general purposes. In this case, the
             * currency is not set and so the user must enter it.
             */
            if (entryInTransaction.getCommodityInternal() instanceof Currency) {
                otherEntry.setIncomeExpenseCurrency((Currency) entryInTransaction.getCommodityInternal());
            }

            return entryInTransaction;
        }

        private void setNewEntryProperties(Entry newEntry) {
            // It is assumed that the entry is in a data manager that is a direct
            // child of the data manager that contains the account.
            TransactionManager tm = (TransactionManager) newEntry.getDataManager();
            newEntry.setAccount(tm.getCopyInTransaction(fPage.getAccount()));

            newEntry.setPropertyValue(ReconciliationEntryInfo.getStatementAccessor(), fPage.getStatement());
        }
    };

    // We manage the layout of 'container' ourselves because we want either
    // the 'containerOfTableAndButtons' to be visible or the 'no statement'
    // message to be visible.  There is no suitable layout for
    // this.  Therefore clear out the layout manager.
    container.setLayout(null);

    // Create the control that will be visible if no session is open
    noStatementMessage = new Label(container, SWT.WRAP);
    noStatementMessage.setText(ReconciliationPlugin.getResourceString("EntriesSection.noStatementMessage"));
    noStatementMessage.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_DARK_RED));

    // Load the 'unreconcile' indicator
    URL installURL = ReconciliationPlugin.getDefault().getBundle().getEntry("/icons/unreconcile.gif");
    final Image unreconcileImage = ImageDescriptor.createFromURL(installURL).createImage();
    parent.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent e) {
            unreconcileImage.dispose();
        }
    });

    CellBlock<EntryData, EntryRowControl> unreconcileButton = new CellBlock<EntryData, EntryRowControl>(20, 0) {

        @Override
        public IPropertyControl<EntryData> createCellControl(Composite parent, final RowControl rowControl,
                final EntryRowControl coordinator) {
            ButtonCellControl cellControl = new ButtonCellControl(parent, coordinator, unreconcileImage,
                    "Remove Entry from this Statement") {
                @Override
                protected void run(EntryRowControl rowControl) {
                    unreconcileEntry(rowControl);
                }
            };

            // Allow entries to be dropped in the statement table in the account to be moved from the unreconciled list
            final DropTarget dropTarget = new DropTarget(cellControl.getControl(), DND.DROP_MOVE);

            // Data is provided using a local reference only (can only drag and drop
            // within the Java VM)
            Transfer[] types = new Transfer[] { LocalSelectionTransfer.getTransfer() };
            dropTarget.setTransfer(types);

            dropTarget.addDropListener(new DropTargetAdapter() {

                @Override
                public void dragEnter(DropTargetEvent event) {
                    /*
                     * We want to check what is being dragged, in case it is not an
                     * EntryData object.  Unfortunately this is not available on all platforms,
                     * only on Windows.  The following call to the nativeToJava method will
                     * return the ISelection object on Windows but null on other platforms.
                     * If we get null back, we assume the drop is valid.
                     */
                    ISelection selection = (ISelection) LocalSelectionTransfer.getTransfer()
                            .nativeToJava(event.currentDataType);
                    if (selection == null) {
                        // The selection cannot be determined on this platform - accept the drop
                        return;
                    }

                    if (selection instanceof StructuredSelection) {
                        StructuredSelection structured = (StructuredSelection) selection;
                        if (structured.size() == 1 && structured.getFirstElement() instanceof Entry) {
                            // We do want to accept the drop
                            return;
                        }
                    }

                    // we don't want to accept drop
                    event.detail = DND.DROP_NONE;
                }

                @Override
                public void dragLeave(DropTargetEvent event) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void dragOperationChanged(DropTargetEvent event) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void dragOver(DropTargetEvent event) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void drop(DropTargetEvent event) {
                    if (LocalSelectionTransfer.getTransfer().isSupportedType(event.currentDataType)) {
                        ISelection selection = LocalSelectionTransfer.getTransfer().getSelection();
                        Entry sourceEntry = (Entry) ((StructuredSelection) selection).getFirstElement();
                        EntryRowControl dropRow = coordinator;

                        /*
                         * Merge data from dragged transaction into the target transaction
                         * and delete the dragged transaction.
                         */
                        boolean success = mergeTransaction(sourceEntry, dropRow);
                        if (!success) {
                            event.detail = DND.DROP_NONE;
                        } else {
                            dropRow.commitChanges("Merge Entries");
                        }
                    }
                }

                @Override
                public void dropAccept(DropTargetEvent event) {
                    // TODO Auto-generated method stub
                }
            });

            fReconciledEntriesControl.getControl().addDisposeListener(new DisposeListener() {
                public void widgetDisposed(DisposeEvent e) {
                    dropTarget.dispose();
                }
            });

            return cellControl;
        }

        @Override
        public void createHeaderControls(Composite parent, EntryData entryData) {
            /*
             * All CellBlock implementations must create a control because
             * the header and rows must match. Maybe these objects could
             * just point to the header controls, in which case this would
             * not be necessary.
             * 
             * Note also we use Label, not an empty Composite, because we
             * don't want a preferred height that is higher than the labels.
             */
            new Label(parent, SWT.NONE);
        }
    };

    IndividualBlock<EntryData, RowControl> transactionDateColumn = PropertyBlock
            .createTransactionColumn(TransactionInfo.getDateAccessor());
    CellBlock<EntryData, BaseEntryRowControl> debitColumnManager = DebitAndCreditColumns
            .createDebitColumn(fPage.getAccount().getCurrency());
    CellBlock<EntryData, BaseEntryRowControl> creditColumnManager = DebitAndCreditColumns
            .createCreditColumn(fPage.getAccount().getCurrency());
    CellBlock<EntryData, BaseEntryRowControl> balanceColumnManager = new BalanceColumn(
            fPage.getAccount().getCurrency());

    /*
     * Setup the layout structure of the header and rows.
     */
    Block<EntryData, EntryRowControl> rootBlock = new HorizontalBlock<EntryData, EntryRowControl>(
            unreconcileButton, transactionDateColumn,
            PropertyBlock.createEntryColumn(EntryInfo.getValutaAccessor()),
            PropertyBlock.createEntryColumn(EntryInfo.getCheckAccessor()),
            PropertyBlock.createEntryColumn(EntryInfo.getMemoAccessor()),
            new OtherEntriesButton(new HorizontalBlock<Entry, ISplitEntryContainer>(
                    new SingleOtherEntryPropertyBlock(EntryInfo.getAccountAccessor()),
                    new SingleOtherEntryPropertyBlock(EntryInfo.getMemoAccessor(),
                            NLS.bind(Messages.StatementSection_EntryDescription, null)),
                    new SingleOtherEntryPropertyBlock(EntryInfo.getAmountAccessor()))),
            debitColumnManager, creditColumnManager, balanceColumnManager);

    // Create the table control.
    IRowProvider rowProvider = new ReusableRowProvider(rootBlock);
    fReconciledEntriesControl = new EntriesTable<EntryData>(container, rootBlock, reconciledTableContents,
            rowProvider, fPage.getAccount().getSession(), transactionDateColumn, rowTracker) {
        @Override
        protected EntryData createEntryRowInput(Entry entry) {
            return new EntryData(entry, session.getDataManager());
        }

        @Override
        protected EntryData createNewEntryRowInput() {
            return new EntryData(null, session.getDataManager());
        }
    };

    // TODO: do not duplicate this.
    if (fPage.getStatement() == null) {
        noStatementMessage.setSize(container.getSize());
        //fReconciledEntriesControl.getControl().setSize(0, 0);
        fReconciledEntriesControl.setSize(0, 0);
    } else {
        noStatementMessage.setSize(0, 0);
        //fReconciledEntriesControl.getControl().setSize(containerOfEntriesControl1.getSize());
        fReconciledEntriesControl.setSize(container.getSize());
        fReconciledEntriesControl.layout(true); // ??????
    }

    // There is no layout set on the navigation view.
    // Therefore we must listen for changes to the size of
    // the navigation view and adjust the size of the visible
    // control to match.
    container.addControlListener(new ControlAdapter() {
        @Override
        public void controlResized(ControlEvent e) {
            if (fPage.getStatement() == null) {
                noStatementMessage.setSize(container.getSize());
                fReconciledEntriesControl.setSize(0, 0);
            } else {
                noStatementMessage.setSize(0, 0);
                fReconciledEntriesControl.setSize(container.getSize());
                fReconciledEntriesControl.layout(true); // ??????
            }
        }
    });

    getSection().setClient(container);
    toolkit.paintBordersFor(container);
    refresh();
}

From source file:net.sf.smbt.touchosc.ui.touchoscgui.diagram.sheet.TouchoscguiPropertySectionOLD.java

License:LGPL

public void setInput(IWorkbenchPart part, ISelection selection) {
    if (selection.isEmpty() || false == selection instanceof StructuredSelection) {
        setInput2(part, selection);/*from ww w .jav a2 s .c o m*/
        return;
    }
    final StructuredSelection structuredSelection = ((StructuredSelection) selection);
    ArrayList transformedSelection = new ArrayList(structuredSelection.size());
    for (Iterator it = structuredSelection.iterator(); it.hasNext();) {
        Object r = transformSelection(it.next());
        if (r != null) {
            transformedSelection.add(r);
        }
    }
    setInput2(part, new StructuredSelection(transformedSelection));
}