1 /*******************************************************************************
2 * Copyright (c) 2012, 2013 Association for Decentralized Information Management in
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.g3d.property;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Field;
16 import java.lang.reflect.InvocationTargetException;
17 import java.lang.reflect.Method;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.LinkedHashMap;
24 import java.util.List;
27 import java.util.function.Consumer;
29 import org.eclipse.jface.layout.GridDataFactory;
30 import org.eclipse.jface.viewers.AbstractTableViewer;
31 import org.eclipse.jface.viewers.CellEditor;
32 import org.eclipse.jface.viewers.CellEditor.LayoutData;
33 import org.eclipse.jface.viewers.CellLabelProvider;
34 import org.eclipse.jface.viewers.CellNavigationStrategy;
35 import org.eclipse.jface.viewers.ColumnViewer;
36 import org.eclipse.jface.viewers.ColumnViewerEditor;
37 import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent;
38 import org.eclipse.jface.viewers.ColumnViewerEditorActivationListener;
39 import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy;
40 import org.eclipse.jface.viewers.ColumnViewerEditorDeactivationEvent;
41 import org.eclipse.jface.viewers.EditingSupport;
42 import org.eclipse.jface.viewers.FocusCellOwnerDrawHighlighter;
43 import org.eclipse.jface.viewers.ISelection;
44 import org.eclipse.jface.viewers.ISelectionChangedListener;
45 import org.eclipse.jface.viewers.ISelectionProvider;
46 import org.eclipse.jface.viewers.IStructuredContentProvider;
47 import org.eclipse.jface.viewers.SelectionChangedEvent;
48 import org.eclipse.jface.viewers.StructuredSelection;
49 import org.eclipse.jface.viewers.TableViewer;
50 import org.eclipse.jface.viewers.TableViewerColumn;
51 import org.eclipse.jface.viewers.TableViewerFocusCellManager;
52 import org.eclipse.jface.viewers.TextCellEditor;
53 import org.eclipse.jface.viewers.Viewer;
54 import org.eclipse.jface.viewers.ViewerCell;
55 import org.eclipse.jface.viewers.ViewerColumn;
56 import org.eclipse.jface.viewers.ViewerRow;
57 import org.eclipse.swt.SWT;
58 import org.eclipse.swt.custom.TableEditor;
59 import org.eclipse.swt.events.TraverseEvent;
60 import org.eclipse.swt.widgets.Composite;
61 import org.eclipse.swt.widgets.Control;
62 import org.eclipse.swt.widgets.Display;
63 import org.eclipse.swt.widgets.Event;
64 import org.eclipse.swt.widgets.Item;
65 import org.eclipse.swt.widgets.TableColumn;
66 import org.eclipse.swt.widgets.TableItem;
67 import org.eclipse.ui.IWorkbenchSite;
68 import org.simantics.db.management.ISessionContext;
69 import org.simantics.g3d.property.annotations.CompoundGetPropertyValue;
70 import org.simantics.g3d.property.annotations.CompoundSetPropertyValue;
71 import org.simantics.g3d.property.annotations.GetPropertyValue;
72 import org.simantics.g3d.property.annotations.PropertyTabBlacklist;
73 import org.simantics.g3d.property.annotations.SetPropertyValue;
74 import org.simantics.g3d.scenegraph.IG3DNode;
75 import org.simantics.g3d.scenegraph.NodeMap;
76 import org.simantics.g3d.scenegraph.NodeMapProvider;
77 import org.simantics.g3d.scenegraph.base.INode;
78 import org.simantics.g3d.scenegraph.base.NodeListener;
79 import org.simantics.g3d.scenegraph.base.ParentNode;
80 import org.simantics.g3d.scenegraph.structural.IStructuralNode;
81 import org.simantics.g3d.tools.AdaptationUtils;
82 import org.simantics.selectionview.IPropertyTab;
83 import org.simantics.selectionview.IPropertyTab2;
84 import org.simantics.utils.datastructures.Callback;
85 import org.simantics.utils.datastructures.MapList;
87 public class AnnotatedPropertyTabContributorFactory implements PropertyTabContributorFactory {
89 private static final boolean DEBUG = false;
91 @SuppressWarnings("unchecked")
93 public List<PropertyTabContributor> getContributors(Object input) {
94 Map<String,IPropertyItem> items = new LinkedHashMap<String, IPropertyItem>();
95 List<String> blacklist = new ArrayList<String>();
97 collectItems(input.getClass(), items);
98 collectBlacklist(input.getClass(), blacklist);
99 } catch (InstantiationException e) {
100 // TODO Auto-generated catch block
102 } catch (IllegalAccessException e) {
103 // TODO Auto-generated catch block
107 if (items.size() == 0)
108 return Collections.EMPTY_LIST;
110 MapList<String, IPropertyItem> tabMap = new MapList<String, IPropertyItem>();
111 List<String> tabs = new ArrayList<String>();
112 for (String id : items.keySet()) {
113 IPropertyItem item = items.get(id);
114 tabMap.add(item.getTabId(), item);
115 if (!tabs.contains(item.getTabId())) {
116 tabs.add(item.getTabId());
117 //System.out.println(item.tabId + " " + item.name + " " + item.id);
120 for (String s : blacklist) {
124 List<PropertyTabContributor> contributors = new ArrayList<PropertyTabContributor>(tabs.size());
125 for (String tabId : tabs) {
126 contributors.add(new AnnotatedPropertyTabContributor(tabId, tabMap.getValues(tabId)));
133 private static void collectItems(Class<?> clazz, Map<String, IPropertyItem> items) throws InstantiationException, IllegalAccessException {
134 Class<?> superclass = clazz.getSuperclass();
135 if(superclass != null)
136 collectItems(superclass, items);
138 for (Method m : clazz.getDeclaredMethods()) {
139 m.setAccessible(true);
140 for (Annotation annotation : m.getAnnotations()) {
141 if (annotation.annotationType().equals(GetPropertyValue.class)) {
142 GetPropertyValue get = (GetPropertyValue)annotation;
143 PropertyItem item = (PropertyItem)items.get(get.value());
145 item = new PropertyItem(get.value());
146 items.put(item.id, item);
150 item.manipulatorClass = get.manipulator().newInstance().get(m,null);
152 item.tabId = get.tabId();
154 item.name = get.name();
157 } else if (annotation.annotationType().equals(SetPropertyValue.class)) {
158 SetPropertyValue set = (SetPropertyValue)annotation;
159 PropertyItem item = (PropertyItem)items.get(set.value());
161 item = new PropertyItem(set.value());
162 items.put(item.id, item);
166 } else if (annotation.annotationType().equals(CompoundGetPropertyValue.class)) {
167 CompoundGetPropertyValue get = (CompoundGetPropertyValue)annotation;
168 CompoundPropertyItem item = (CompoundPropertyItem)items.get(get.value());
170 item = new CompoundPropertyItem(get.value());
171 items.put(item.id, item);
175 item.manipulatorFactory = get.manipulator().newInstance();
177 item.tabId = get.tabId();
179 item.name = get.name();
180 } else if (annotation.annotationType().equals(CompoundSetPropertyValue.class)) {
181 CompoundSetPropertyValue set = (CompoundSetPropertyValue)annotation;
182 CompoundPropertyItem item = (CompoundPropertyItem)items.get(set.value());
184 item = new CompoundPropertyItem(set.value());
185 items.put(item.id, item);
196 private static void collectBlacklist(Class<?> clazz, List<String> blacklist) throws InstantiationException, IllegalAccessException {
197 Class<?> superclass = clazz.getSuperclass();
198 if(superclass != null)
199 collectBlacklist(superclass, blacklist);
201 PropertyTabBlacklist ann = clazz.getAnnotation(PropertyTabBlacklist.class);
204 String s = ann.value();
209 for (String item : s.split(";")) {
216 private static Map<PropertyItem, PropertyManipulator> createManipulators(CompoundPropertyItem item, Object obj) {
219 Map<String,Object> map = (Map<String, Object>)item.getter.invoke(obj);
220 Map<PropertyItem, PropertyManipulator> result = new HashMap<AnnotatedPropertyTabContributorFactory.PropertyItem, PropertyManipulator>();
221 for (String key : map.keySet()) {
222 MethodWithMapValueProvider provider = new MethodWithMapValueProvider(item.getter, item.setter, key);
223 Class<? extends PropertyManipulator> clazz = item.manipulatorFactory.get(null,map.get(key));
224 PropertyManipulator manipulator = clazz.getConstructor(ValueProvider.class,Object.class).newInstance(provider,obj);
225 PropertyItem i = new PropertyItem(item.id+"."+key);
226 i.getter = item.getter;
227 i.setter = item.setter;
229 i.tabId = item.tabId;
230 result.put(i,manipulator);
233 } catch (Exception e) {
235 return Collections.EMPTY_MAP;
240 private static PropertyManipulator createManipulator(PropertyItem item, Object obj) {
242 MethodValueProvider provider = new MethodValueProvider(item.getter, item.setter);
243 PropertyManipulator manipulator = item.manipulatorClass.getConstructor(ValueProvider.class,Object.class).newInstance(provider,obj);
245 } catch (Exception e) {
251 private static interface IPropertyItem {
252 public String getTabId();
255 private static class PropertyItem implements IPropertyItem{
258 private String tabId;
259 private Method getter;
260 private Method setter;
261 private Class<? extends PropertyManipulator> manipulatorClass;
264 public PropertyItem(String id) {
266 throw new NullPointerException();
271 public int hashCode() {
272 return id.hashCode();
276 public String getTabId() {
281 private static class CompoundPropertyItem implements IPropertyItem{
284 private String tabId;
285 private Method getter;
286 private Method setter;
287 private PropertyManipulatorFactory manipulatorFactory;
290 public CompoundPropertyItem(String id) {
292 throw new NullPointerException();
297 public int hashCode() {
298 return id.hashCode();
302 public String getTabId() {
307 private static class AnnotatedPropertyTabContributor implements PropertyTabContributor {
309 List<IPropertyItem> items;
311 public AnnotatedPropertyTabContributor(String id, List<IPropertyItem> items) {
313 throw new NullPointerException();
319 public IPropertyTab create(Composite parent, IWorkbenchSite site,
320 ISessionContext context, Object input) {
321 AnnotatedPropertyTab tab = new AnnotatedPropertyTab(id, items);
322 tab.createControl(parent, context);
327 public String getId() {
333 private static class AnnotatedPropertyTab implements IPropertyTab2, NodeListener {
335 List<IPropertyItem> contibutedItems;
336 List<PropertyItem> resolvedItems = new ArrayList<PropertyItem>();
337 private Map<PropertyItem,PropertyManipulator> manipulators = new HashMap<PropertyItem, PropertyManipulator>();
339 private TableViewer viewer;
341 private IG3DNode node;
342 private NodeMap<?,?> nodeMap;
344 private List<TableViewerColumn> valueColumns = new ArrayList<TableViewerColumn>();
346 public AnnotatedPropertyTab(String id, List<IPropertyItem> items) {
348 this.contibutedItems = items;
354 public void createControl(Composite parent, ISessionContext context) {
355 //parent.setLayout(new FillLayout());
356 viewer = new TableViewer(parent, SWT.FULL_SELECTION | SWT.SINGLE);
358 GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(viewer.getTable());
360 //viewer.setLabelProvider(new AnnotatedTableLabelProvider(object))
362 viewer.setContentProvider(new PropertyItemContentsProvider());
364 TableViewerColumn name = new TableViewerColumn(viewer, SWT.LEFT);
365 //TableViewerColumn value = new TableViewerColumn(viewer, SWT.LEFT);
366 name.setLabelProvider(new PropertyItemNameProvider());
367 //value.setLabelProvider(new PropertyValueLabelProvider(null));
368 name.getColumn().setText("Property");
369 //value.getColumn().setText("Value");
370 name.getColumn().setWidth(200);
371 //value.getColumn().setWidth(200);
372 name.getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
375 public void selectionChanged(SelectionChangedEvent event) {
376 PropertyItem item = AdaptationUtils.adaptToSingle(event.getSelection(),PropertyItem.class);
378 PropertyManipulator manipulator = manipulators.get(item);//createManipulator(item, null);
379 for (int i = 0; i < valueColumns.size(); i++) {
380 TableViewerColumn c = valueColumns.get(i);
381 if (i < manipulator.getValueCount()) {
382 c.getColumn().setText(manipulator.getDescription(i));
384 c.getColumn().setText("");
393 for (IPropertyItem item : contibutedItems) {
394 if (item instanceof PropertyItem) {
395 PropertyManipulator manipulator = createManipulator((PropertyItem)item, null);
396 if (manipulator == null)
398 if (valueCount < manipulator.getValueCount())
399 valueCount = manipulator.getValueCount();
400 } else if (item instanceof CompoundPropertyItem) {
405 for (int i = 0; i < valueCount; i++) {
406 TableViewerColumn value = new TableViewerColumn(viewer, SWT.LEFT);
407 //value.getColumn().setText("Value " + (i+1));
408 value.getColumn().setText("");
409 value.getColumn().setWidth(200);
410 valueColumns.add(value);
411 //value.setEditingSupport(new )
413 viewer.getTable().setHeaderVisible(true);
414 viewer.getTable().setLinesVisible(true);
415 viewer.addSelectionChangedListener(new ISelectionChangedListener() {
418 public void selectionChanged(SelectionChangedEvent event) {
419 PropertyItem item = AdaptationUtils.adaptToSingle(event.getSelection(), PropertyItem.class);
421 if (!manipulators.get(selectedItem).getEditMode())
422 manipulators.get(selectedItem).setEditMode(true);
425 for (IPropertyItem i : delayedUpdate) {
426 if (!i.equals(selectedItem)) {
427 manipulators.get(i).setEditMode(false);
428 viewer.update(i,null);
431 if (delayedUpdate.contains(selectedItem)) {
432 delayedUpdate.clear();
433 delayedUpdate.add(selectedItem);
435 delayedUpdate.clear();
440 CellNavigationStrategy nStrategy = new CellNavigationStrategy() {
441 private ViewerCell internalFindSelectedCell(
442 ColumnViewer viewer, ViewerCell currentSelectedCell,
444 switch (event.keyCode) {
446 if (currentSelectedCell != null) {
447 return getNeighbor(currentSelectedCell,
448 ViewerCell.ABOVE, false);
452 if (currentSelectedCell != null) {
453 return getNeighbor(currentSelectedCell,
454 ViewerCell.BELOW, false);
458 if (currentSelectedCell != null) {
459 return getNeighbor(currentSelectedCell,
460 ViewerCell.LEFT, true);
463 case SWT.ARROW_RIGHT:
464 if (currentSelectedCell != null) {
465 return getNeighbor(currentSelectedCell,
466 ViewerCell.RIGHT, true);
473 public ViewerCell findSelectedCell(ColumnViewer viewer,
474 ViewerCell currentSelectedCell, Event event) {
475 ViewerCell cell = internalFindSelectedCell(viewer,
476 currentSelectedCell, event);
478 TableColumn t = AnnotatedPropertyTab.this.viewer.getTable().getColumn(
479 cell.getColumnIndex());
480 AnnotatedPropertyTab.this.viewer.getTable().showColumn(t);
486 TableViewerFocusCellManager focusCellManager = new TableViewerFocusCellManager(
487 viewer, new FocusCellOwnerDrawHighlighter(viewer));
489 Field f = focusCellManager.getClass().getSuperclass()
490 .getDeclaredField("navigationStrategy");
491 f.setAccessible(true);
492 f.set(focusCellManager, nStrategy);
493 } catch (SecurityException e) {
495 } catch (NoSuchFieldException e) {
497 } catch (IllegalArgumentException e) {
499 } catch (IllegalAccessException e) {
502 ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(
504 protected boolean isEditorActivationEvent(
505 ColumnViewerEditorActivationEvent event) {
506 return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
507 || event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
508 || (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED && event.keyCode == SWT.CR)
509 || event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
512 TableViewerEditor.create(viewer, focusCellManager, actSupport,
513 ColumnViewerEditor.TABBING_HORIZONTAL
514 | ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
515 | ColumnViewerEditor.TABBING_VERTICAL
516 | ColumnViewerEditor.KEYBOARD_ACTIVATION);
517 viewer.getColumnViewerEditor().addEditorActivationListener(
518 new ColumnViewerEditorActivationListener() {
519 public void afterEditorActivated(
520 ColumnViewerEditorActivationEvent event) {
523 public void afterEditorDeactivated(
524 ColumnViewerEditorDeactivationEvent event) {
527 public void beforeEditorActivated(
528 ColumnViewerEditorActivationEvent event) {
529 ViewerCell cell = (ViewerCell) event.getSource();
530 viewer.getTable().showColumn(
531 viewer.getTable().getColumn(cell.getColumnIndex()));
534 public void beforeEditorDeactivated(
535 ColumnViewerEditorDeactivationEvent event) {
543 private IPropertyItem selectedItem = null;
544 private Set<IPropertyItem> delayedUpdate = new HashSet<IPropertyItem>();
548 public void setInput(ISessionContext context, ISelection selection,
550 Collection<IG3DNode> nodes = AdaptationUtils.adaptToCollection(selection, IG3DNode.class);
551 if (nodes.size() != 1) {
553 node.removeListener(this);
558 IG3DNode n = nodes.iterator().next();
560 if (!node.equals(n)) {
561 node.removeListener(this);
571 private void setInput(IG3DNode node) {
573 this.node.addListener(this);
581 if (n instanceof NodeMapProvider<?,?>) {
582 nodeMap = ((NodeMapProvider<?,?>) n).getNodeMap();
586 n = (IG3DNode)n.getParent();
588 boolean readOnly = (node instanceof IStructuralNode && ((IStructuralNode)node).isPartOfInstantiatedModel() && !((IStructuralNode)node).isInstantiatedModelRoot());
589 // create label providers
590 PropertyValueLabelProvider2 p = new PropertyValueLabelProvider2(this);
592 for (TableViewerColumn c : valueColumns) {
593 c.setLabelProvider(p);
595 PropertyEditingSupport support = new PropertyEditingSupport(this, viewer, index++, nodeMap);
596 c.setEditingSupport(support);
599 resolvedItems.clear();
600 manipulators.clear();
601 for (IPropertyItem item : contibutedItems) {
602 if (item instanceof PropertyItem) {
603 resolvedItems.add((PropertyItem)item);
604 manipulators.put((PropertyItem)item, createManipulator((PropertyItem)item, node));
607 CompoundPropertyItem compound = (CompoundPropertyItem)item;
608 Map<PropertyItem, PropertyManipulator> manipulators = createManipulators(compound, node);
609 for (PropertyItem i : manipulators.keySet()) {
610 resolvedItems.add(i);
611 this.manipulators.put(i, manipulators.get(i));
616 viewer.getTable().setEnabled(!readOnly);
617 viewer.setInput(resolvedItems);
621 public void requestFocus() {
622 viewer.getTable().forceFocus();
626 public void dispose() {
628 node.removeListener(this);
635 public Control getControl() {
636 return viewer.getTable();
640 public ISelectionProvider getSelectionProvider() {
645 public boolean isDisposed() {
646 return viewer.getTable().isDisposed();
650 public <T extends INode> void nodeAdded(ParentNode<T> node,
651 INode child, String rel) {
656 public <T extends INode> void nodeRemoved(ParentNode<T> node,
657 INode child, String rel) {
662 public void propertyChanged(INode node, final String id) {
663 // for (final PropertyItem item : items) {
664 // if (item.id.equals(id)) {
665 // Display.getDefault().asyncExec(new Runnable() {
668 // public void run() {
669 // viewer.update(item, null);
675 if (Thread.currentThread() == Display.getDefault().getThread()) {
676 if (viewer.getTable().isDisposed())
678 if (DEBUG)System.out.println("Viewer refresh " + id);
679 for (PropertyItem item : resolvedItems)
680 if (!item.equals(selectedItem))
681 viewer.refresh(item);
682 if (selectedItem != null)
683 delayedUpdate.add(selectedItem);
684 } else if (!editing){
685 // running delayed refresh when a cell editor is active would cancel cell editing.
686 Display.getDefault().asyncExec(new Runnable() {
689 if (viewer.getTable().isDisposed()) {
690 if (AnnotatedPropertyTab.this.node != null)
691 AnnotatedPropertyTab.this.node.removeListener(AnnotatedPropertyTab.this);
694 if (DEBUG) System.out.println("Viewer threaded refresh " + id);
695 for (PropertyItem item : resolvedItems)
696 if (!item.equals(selectedItem))
697 viewer.refresh(item);
698 if (selectedItem != null)
699 delayedUpdate.add(selectedItem);
704 for (PropertyItem item : resolvedItems) {
705 delayedUpdate.add(item);
714 public void updatePartName(Consumer<String> updateCallback) {
716 updateCallback.accept(node.toString());
720 public PropertyManipulator getManipulator(PropertyItem item) {
721 return manipulators.get(item);
724 private boolean editing = false;
726 public void setEditing(boolean editing) {
727 this.editing = editing;
733 private static class PropertyEditingSupport extends EditingSupport {
734 AnnotatedPropertyTab tab;
736 NodeMap<?,?> nodeMap;
740 public PropertyEditingSupport(AnnotatedPropertyTab tab, TableViewer viewer, int index, NodeMap<?,?> nodeMap) {
744 this.viewer = viewer;
745 this.nodeMap = nodeMap;
749 protected boolean canEdit(Object element) {
750 PropertyItem item = (PropertyItem)element;
751 if (tab.getManipulator(item).getValueCount() <= index)
753 if (item.setter == null)
755 if (getValue(element) == null)
761 protected CellEditor getCellEditor(Object element) {
763 if (tab.getManipulator((PropertyItem)element).getValueCount() <= index)
766 editor = new TextCellEditor(viewer.getTable(),SWT.NONE) {
768 public void activate() {
769 tab.setEditing(true);
773 public void deactivate() {
775 tab.setEditing(false);
778 if (DEBUG)System.err.println("CELL EDITOR: " + element);
783 protected Object getValue(Object element) {
784 PropertyItem item = (PropertyItem)element;
785 PropertyManipulator manipulator = tab.getManipulator(item);//createManipulator(item, obj);
786 if (manipulator.getValueCount() <= index)
788 Object value = manipulator.getValue(index);
793 protected void setValue(Object element, Object value) {
795 PropertyItem item = (PropertyItem)element;
796 PropertyManipulator manipulator = tab.getManipulator(item);//createManipulator(item, obj);
797 if (manipulator.getValueCount() <= index)
798 throw new IllegalAccessError("Editing value in index " + index + " is not allowed.");
799 if (DEBUG)System.err.println("CELL SET VALUE: " + element + " " + value);
800 manipulator.setValue((String)value,index);
801 viewer.refresh(item);
802 nodeMap.commit("Set " + item.id + " value to " + value);
810 private static class PropertyItemNameProvider extends CellLabelProvider {
814 public void update(ViewerCell cell) {
815 PropertyItem item = (PropertyItem)cell.getElement();
817 if (item.name.length() > 0)
818 cell.setText(item.name);
820 cell.setText(item.id);
826 private static class PropertyValueLabelProvider2 extends CellLabelProvider {
827 AnnotatedPropertyTab tab;
828 //private Object object;
830 public PropertyValueLabelProvider2(AnnotatedPropertyTab tab) {
835 public void update(ViewerCell cell) {
836 PropertyItem item = (PropertyItem)cell.getElement();
837 int index = cell.getColumnIndex() -1;
838 PropertyManipulator manipulator = tab.getManipulator(item);//createManipulator(item, object);
839 if (manipulator.getValueCount() <= index)
841 cell.setText(manipulator.getValue(index));
845 private static class PropertyItemContentsProvider implements IStructuredContentProvider {
846 @SuppressWarnings("unchecked")
848 public Object[] getElements(Object inputElement) {
849 List<PropertyItem> items = (List<PropertyItem>)inputElement;
850 return items.toArray();
854 public void dispose() {
859 public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
866 private static ViewerCell getNeighbor(ViewerCell currentCell,
867 int directionMask, boolean sameLevel) {
869 if ((directionMask & ViewerCell.ABOVE) == ViewerCell.ABOVE) {
870 row = currentCell.getViewerRow().getNeighbor(ViewerRow.ABOVE,
872 } else if ((directionMask & ViewerCell.BELOW) == ViewerCell.BELOW) {
873 row = currentCell.getViewerRow().getNeighbor(ViewerRow.BELOW,
876 row = currentCell.getViewerRow();
880 columnIndex = getVisualIndex(row, currentCell.getColumnIndex());
882 if ((directionMask & ViewerCell.LEFT) == ViewerCell.LEFT) {
884 } else if ((directionMask & ViewerCell.RIGHT) == ViewerCell.RIGHT) {
887 columnIndex += modifier;
888 if (columnIndex >= 0 && columnIndex < row.getColumnCount()) {
889 ViewerCell cell = getCellAtVisualIndex(row, columnIndex);
892 && columnIndex < row.getColumnCount() - 1
893 && columnIndex > 0) {
894 if (isVisible(cell)) {
897 columnIndex += modifier;
898 cell = getCellAtVisualIndex(row, columnIndex);
912 public static class TableViewerEditor extends ColumnViewerEditor {
914 * This viewer's table editor.
916 private TableEditor tableEditor;
917 private TableViewerFocusCellManager focusCellManager;
922 * the viewer the editor is attached to
923 * @param focusCellManager
924 * the cell focus manager if one used or <code>null</code>
925 * @param editorActivationStrategy
926 * the strategy used to decide about the editor activation
930 TableViewerEditor(TableViewer viewer,
931 TableViewerFocusCellManager focusCellManager,
932 ColumnViewerEditorActivationStrategy editorActivationStrategy,
934 super(viewer, editorActivationStrategy, feature);
935 this.feature = feature;
936 tableEditor = new TableEditor(viewer.getTable());
937 this.focusCellManager = focusCellManager;
941 * Create a customized editor with focusable cells
944 * the viewer the editor is created for
945 * @param focusCellManager
946 * the cell focus manager if one needed else
948 * @param editorActivationStrategy
949 * activation strategy to control if an editor activated
951 * bit mask controlling the editor
953 * <li>{@link ColumnViewerEditor#DEFAULT}</li>
954 * <li>{@link ColumnViewerEditor#TABBING_CYCLE_IN_ROW}</li>
955 * <li>{@link ColumnViewerEditor#TABBING_HORIZONTAL}</li>
957 * {@link ColumnViewerEditor#TABBING_MOVE_TO_ROW_NEIGHBOR}</li>
958 * <li>{@link ColumnViewerEditor#TABBING_VERTICAL}</li>
960 * @see #create(TableViewer, ColumnViewerEditorActivationStrategy, int)
962 public static void create(TableViewer viewer,
963 TableViewerFocusCellManager focusCellManager,
964 ColumnViewerEditorActivationStrategy editorActivationStrategy,
966 TableViewerEditor editor = new TableViewerEditor(viewer,
967 focusCellManager, editorActivationStrategy, feature);
968 viewer.setColumnViewerEditor(editor);
969 if (focusCellManager != null) {
971 Method m = focusCellManager.getClass().getSuperclass()
972 .getDeclaredMethod("init", null);
973 m.setAccessible(true);
974 m.invoke(focusCellManager, null);
975 } catch (SecurityException e) {
977 } catch (IllegalArgumentException e) {
979 } catch (IllegalAccessException e) {
981 } catch (NoSuchMethodException e) {
983 } catch (InvocationTargetException e) {
986 // focusCellManager.init();
991 * Create a customized editor whose activation process is customized
994 * the viewer the editor is created for
995 * @param editorActivationStrategy
996 * activation strategy to control if an editor activated
998 * bit mask controlling the editor
1000 * <li>{@link ColumnViewerEditor#DEFAULT}</li>
1001 * <li>{@link ColumnViewerEditor#TABBING_CYCLE_IN_ROW}</li>
1002 * <li>{@link ColumnViewerEditor#TABBING_HORIZONTAL}</li>
1004 * {@link ColumnViewerEditor#TABBING_MOVE_TO_ROW_NEIGHBOR}</li>
1005 * <li>{@link ColumnViewerEditor#TABBING_VERTICAL}</li>
1008 public static void create(TableViewer viewer,
1009 ColumnViewerEditorActivationStrategy editorActivationStrategy,
1011 create(viewer, null, editorActivationStrategy, feature);
1014 protected void setEditor(Control w, Item item, int columnNumber) {
1015 tableEditor.setEditor(w, (TableItem) item, columnNumber);
1018 protected void setLayoutData(LayoutData layoutData) {
1019 tableEditor.grabHorizontal = layoutData.grabHorizontal;
1020 tableEditor.horizontalAlignment = layoutData.horizontalAlignment;
1021 tableEditor.minimumWidth = layoutData.minimumWidth;
1024 public ViewerCell getFocusCell() {
1025 if (focusCellManager != null) {
1026 return focusCellManager.getFocusCell();
1028 return super.getFocusCell();
1031 protected void updateFocusCell(ViewerCell focusCell,
1032 ColumnViewerEditorActivationEvent event) {
1033 // Update the focus cell when we activated the editor with these 2
1035 if (event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC
1036 || event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL) {
1037 if (focusCellManager != null) {
1039 if (DEBUG)System.err.println("FOCUS CELL: " + focusCell);
1041 Method m = AbstractTableViewer.class.getDeclaredMethod(
1042 "getSelectionFromWidget", null);
1043 m.setAccessible(true);
1044 List l = (List) m.invoke(getViewer(), null);
1045 if (focusCellManager != null) {
1046 m = focusCellManager
1049 .getDeclaredMethod("setFocusCell",
1050 new Class[] { ViewerCell.class });
1051 m.setAccessible(true);
1052 m.invoke(focusCellManager,
1053 new Object[] { focusCell });
1055 if (!l.contains(focusCell.getElement())) {
1056 getViewer().setSelection(
1057 new StructuredSelection(focusCell
1060 } catch (SecurityException e) {
1061 e.printStackTrace();
1062 } catch (IllegalArgumentException e) {
1063 e.printStackTrace();
1064 } catch (IllegalAccessException e) {
1065 e.printStackTrace();
1066 } catch (NoSuchMethodException e) {
1067 e.printStackTrace();
1068 } catch (InvocationTargetException e) {
1069 e.printStackTrace();
1075 protected void processTraverseEvent(int columnIndex, ViewerRow row,
1076 TraverseEvent event) {
1077 ViewerCell cell2edit = null;
1078 if (event.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
1080 if ((event.stateMask & SWT.CTRL) == SWT.CTRL
1081 && (feature & TABBING_VERTICAL) == TABBING_VERTICAL) {
1082 cell2edit = searchCellAboveBelow(row, getViewer(),
1084 } else if ((feature & TABBING_HORIZONTAL) == TABBING_HORIZONTAL) {
1085 cell2edit = searchPreviousCell(row,
1086 row.getCell(columnIndex), row.getCell(columnIndex),
1089 } else if (event.detail == SWT.TRAVERSE_TAB_NEXT) {
1091 if ((event.stateMask & SWT.CTRL) == SWT.CTRL
1092 && (feature & TABBING_VERTICAL) == TABBING_VERTICAL) {
1093 cell2edit = searchCellAboveBelow(row, getViewer(),
1094 columnIndex, false);
1095 } else if ((feature & TABBING_HORIZONTAL) == TABBING_HORIZONTAL) {
1096 cell2edit = searchNextCell(row, row.getCell(columnIndex),
1097 row.getCell(columnIndex), getViewer());
1100 if (DEBUG) System.err.println("NEXT CELL: " + cell2edit);
1101 if (cell2edit != null) {
1102 getViewer().getControl().setRedraw(false);
1103 ColumnViewerEditorActivationEvent acEvent = new ColumnViewerEditorActivationEvent(
1106 Method m = ColumnViewer.class
1108 "triggerEditorActivationEvent",
1109 new Class[] { ColumnViewerEditorActivationEvent.class });
1110 m.setAccessible(true);
1111 m.invoke(getViewer(), new Object[] { acEvent });
1112 } catch (SecurityException e) {
1113 e.printStackTrace();
1114 } catch (NoSuchMethodException e) {
1115 e.printStackTrace();
1116 } catch (IllegalArgumentException e) {
1117 e.printStackTrace();
1118 } catch (IllegalAccessException e) {
1119 e.printStackTrace();
1120 } catch (InvocationTargetException e) {
1121 e.printStackTrace();
1123 getViewer().getControl().setRedraw(true);
1127 private ViewerCell searchCellAboveBelow(ViewerRow row,
1128 ColumnViewer viewer, int columnIndex, boolean above) {
1129 ViewerCell rv = null;
1130 ViewerRow newRow = null;
1132 newRow = row.getNeighbor(ViewerRow.ABOVE, false);
1134 newRow = row.getNeighbor(ViewerRow.BELOW, false);
1137 if (newRow != null) {
1138 Method m = ColumnViewer.class.getDeclaredMethod(
1139 "getViewerColumn", new Class[] { int.class });
1140 m.setAccessible(true);
1141 ViewerColumn column = (ViewerColumn) m.invoke(viewer,
1142 new Object[] { new Integer(columnIndex) });
1143 m = ViewerColumn.class.getDeclaredMethod(
1144 "getEditingSupport", null);
1145 m.setAccessible(true);
1146 EditingSupport es = (EditingSupport) m.invoke(column, null);
1147 if (column != null && es != null) {
1148 m = EditingSupport.class.getDeclaredMethod("canEdit",
1149 new Class[] { Object.class });
1150 m.setAccessible(true);
1151 Boolean b = (Boolean) m.invoke(es,
1152 new Object[] { newRow.getItem().getData() });
1153 if (b.booleanValue()) {
1154 rv = newRow.getCell(columnIndex);
1157 rv = searchCellAboveBelow(newRow, viewer, columnIndex,
1161 } catch (Exception e) {
1162 e.printStackTrace();
1167 private ViewerCell searchPreviousCell(ViewerRow row,
1168 ViewerCell currentCell, ViewerCell originalCell,
1169 ColumnViewer viewer) {
1170 ViewerCell rv = null;
1171 ViewerCell previousCell;
1172 if (currentCell != null) {
1173 previousCell = getNeighbor(currentCell, ViewerCell.LEFT, true);
1175 if (row.getColumnCount() != 0) {
1176 previousCell = row.getCell(getCreationIndex(row,
1177 row.getColumnCount() - 1));
1179 previousCell = row.getCell(0);
1183 if (originalCell.equals(previousCell)) {
1186 if (previousCell != null) {
1187 if (isCellEditable(viewer, previousCell)) {
1190 rv = searchPreviousCell(row, previousCell, originalCell,
1194 if ((feature & TABBING_CYCLE_IN_ROW) == TABBING_CYCLE_IN_ROW) {
1195 rv = searchPreviousCell(row, null, originalCell, viewer);
1196 } else if ((feature & TABBING_MOVE_TO_ROW_NEIGHBOR) == TABBING_MOVE_TO_ROW_NEIGHBOR) {
1197 ViewerRow rowAbove = row
1198 .getNeighbor(ViewerRow.ABOVE, false);
1199 if (rowAbove != null) {
1200 rv = searchPreviousCell(rowAbove, null, originalCell,
1208 private ViewerCell searchNextCell(ViewerRow row,
1209 ViewerCell currentCell, ViewerCell originalCell,
1210 ColumnViewer viewer) {
1211 ViewerCell rv = null;
1212 ViewerCell nextCell;
1213 if (currentCell != null) {
1214 nextCell = getNeighbor(currentCell, ViewerCell.RIGHT, true);
1216 nextCell = row.getCell(getCreationIndex(row, 0));
1219 if (originalCell.equals(nextCell)) {
1222 if (nextCell != null) {
1223 if (isCellEditable(viewer, nextCell)) {
1226 rv = searchNextCell(row, nextCell, originalCell, viewer);
1229 if ((feature & TABBING_CYCLE_IN_ROW) == TABBING_CYCLE_IN_ROW) {
1230 rv = searchNextCell(row, null, originalCell, viewer);
1231 } else if ((feature & TABBING_MOVE_TO_ROW_NEIGHBOR) == TABBING_MOVE_TO_ROW_NEIGHBOR) {
1232 ViewerRow rowBelow = row
1233 .getNeighbor(ViewerRow.BELOW, false);
1234 if (rowBelow != null) {
1235 rv = searchNextCell(rowBelow, null, originalCell,
1243 private boolean isCellEditable(ColumnViewer viewer, ViewerCell cell) {
1245 Method m = ColumnViewer.class.getDeclaredMethod(
1246 "getViewerColumn", new Class[] { int.class });
1247 m.setAccessible(true);
1248 ViewerColumn column = (ViewerColumn) m.invoke(viewer,
1249 new Object[] { new Integer(cell.getColumnIndex()) });
1250 m = ViewerColumn.class.getDeclaredMethod("getEditingSupport",
1252 m.setAccessible(true);
1253 EditingSupport es = (EditingSupport) m.invoke(column, null);
1254 if (column != null && es != null) {
1255 m = EditingSupport.class.getDeclaredMethod("canEdit",
1256 new Class[] { Object.class });
1257 m.setAccessible(true);
1259 Boolean b = (Boolean) m.invoke(es,
1260 new Object[] { cell.getElement() });
1261 return b.booleanValue();
1263 } catch (Exception e) {
1264 e.printStackTrace();
1270 // Reimplementation of ViewerCell-Methods
1271 private static int getVisualIndex(ViewerRow row, int creationIndex) {
1272 TableItem item = (TableItem) row.getItem();
1273 int[] order = item.getParent().getColumnOrder();
1274 for (int i = 0; i < order.length; i++) {
1275 if (order[i] == creationIndex) {
1279 return creationIndex;
1282 private static int getCreationIndex(ViewerRow row, int visualIndex) {
1283 TableItem item = (TableItem) row.getItem();
1284 if (item != null && !item.isDisposed() /*
1285 * && hasColumns() &&
1289 return item.getParent().getColumnOrder()[visualIndex];
1294 private static ViewerCell getCellAtVisualIndex(ViewerRow row,
1296 return getCell(row, getCreationIndex(row, visualIndex));
1299 private static boolean isVisible(ViewerCell cell) {
1300 return getWidth(cell) > 0;
1303 private static int getWidth(ViewerCell cell) {
1304 TableItem item = (TableItem) cell.getViewerRow().getItem();
1305 return item.getParent().getColumn(cell.getColumnIndex()).getWidth();
1308 private static ViewerCell getCell(ViewerRow row, int index) {
1309 return row.getCell(index);