1 /*******************************************************************************
2 * Copyright (c) 2007, 2012 Association for Decentralized Information Management
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.browsing.ui.swt;
14 import java.util.ArrayList;
15 import java.util.Arrays;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.Deque;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.Iterator;
22 import java.util.LinkedList;
23 import java.util.List;
26 import java.util.WeakHashMap;
27 import java.util.concurrent.CopyOnWriteArrayList;
28 import java.util.concurrent.ExecutorService;
29 import java.util.concurrent.Future;
30 import java.util.concurrent.ScheduledExecutorService;
31 import java.util.concurrent.TimeUnit;
32 import java.util.concurrent.atomic.AtomicBoolean;
33 import java.util.concurrent.atomic.AtomicReference;
34 import java.util.function.BiFunction;
35 import java.util.function.Consumer;
37 import org.eclipse.core.runtime.Assert;
38 import org.eclipse.core.runtime.AssertionFailedException;
39 import org.eclipse.core.runtime.IProgressMonitor;
40 import org.eclipse.core.runtime.IStatus;
41 import org.eclipse.core.runtime.MultiStatus;
42 import org.eclipse.core.runtime.Status;
43 import org.eclipse.core.runtime.jobs.Job;
44 import org.eclipse.jface.action.IStatusLineManager;
45 import org.eclipse.jface.resource.ColorDescriptor;
46 import org.eclipse.jface.resource.DeviceResourceException;
47 import org.eclipse.jface.resource.DeviceResourceManager;
48 import org.eclipse.jface.resource.FontDescriptor;
49 import org.eclipse.jface.resource.ImageDescriptor;
50 import org.eclipse.jface.resource.JFaceResources;
51 import org.eclipse.jface.resource.LocalResourceManager;
52 import org.eclipse.jface.resource.ResourceManager;
53 import org.eclipse.jface.util.OpenStrategy;
54 import org.eclipse.jface.viewers.IPostSelectionProvider;
55 import org.eclipse.jface.viewers.ISelection;
56 import org.eclipse.jface.viewers.ISelectionChangedListener;
57 import org.eclipse.jface.viewers.ISelectionProvider;
58 import org.eclipse.jface.viewers.IStructuredSelection;
59 import org.eclipse.jface.viewers.SelectionChangedEvent;
60 import org.eclipse.jface.viewers.StructuredSelection;
61 import org.eclipse.jface.viewers.TreeSelection;
62 import org.eclipse.swt.SWT;
63 import org.eclipse.swt.SWTException;
64 import org.eclipse.swt.custom.CCombo;
65 import org.eclipse.swt.custom.TreeEditor;
66 import org.eclipse.swt.events.FocusEvent;
67 import org.eclipse.swt.events.FocusListener;
68 import org.eclipse.swt.events.KeyEvent;
69 import org.eclipse.swt.events.KeyListener;
70 import org.eclipse.swt.events.MouseEvent;
71 import org.eclipse.swt.events.MouseListener;
72 import org.eclipse.swt.events.SelectionListener;
73 import org.eclipse.swt.graphics.Color;
74 import org.eclipse.swt.graphics.Font;
75 import org.eclipse.swt.graphics.GC;
76 import org.eclipse.swt.graphics.Image;
77 import org.eclipse.swt.graphics.Point;
78 import org.eclipse.swt.graphics.RGB;
79 import org.eclipse.swt.graphics.Rectangle;
80 import org.eclipse.swt.widgets.Composite;
81 import org.eclipse.swt.widgets.Control;
82 import org.eclipse.swt.widgets.Display;
83 import org.eclipse.swt.widgets.Event;
84 import org.eclipse.swt.widgets.Listener;
85 import org.eclipse.swt.widgets.ScrollBar;
86 import org.eclipse.swt.widgets.Shell;
87 import org.eclipse.swt.widgets.Text;
88 import org.eclipse.swt.widgets.Tree;
89 import org.eclipse.swt.widgets.TreeColumn;
90 import org.eclipse.swt.widgets.TreeItem;
91 import org.eclipse.ui.IWorkbenchPart;
92 import org.eclipse.ui.IWorkbenchSite;
93 import org.eclipse.ui.PlatformUI;
94 import org.eclipse.ui.contexts.IContextActivation;
95 import org.eclipse.ui.contexts.IContextService;
96 import org.eclipse.ui.services.IServiceLocator;
97 import org.eclipse.ui.swt.IFocusService;
98 import org.simantics.browsing.ui.BuiltinKeys;
99 import org.simantics.browsing.ui.CheckedState;
100 import org.simantics.browsing.ui.Column;
101 import org.simantics.browsing.ui.Column.Align;
102 import org.simantics.browsing.ui.DataSource;
103 import org.simantics.browsing.ui.ExplorerState;
104 import org.simantics.browsing.ui.GraphExplorer;
105 import org.simantics.browsing.ui.NodeContext;
106 import org.simantics.browsing.ui.NodeContext.CacheKey;
107 import org.simantics.browsing.ui.NodeContext.PrimitiveQueryKey;
108 import org.simantics.browsing.ui.NodeContext.QueryKey;
109 import org.simantics.browsing.ui.NodeContextPath;
110 import org.simantics.browsing.ui.NodeQueryManager;
111 import org.simantics.browsing.ui.NodeQueryProcessor;
112 import org.simantics.browsing.ui.PrimitiveQueryProcessor;
113 import org.simantics.browsing.ui.SelectionDataResolver;
114 import org.simantics.browsing.ui.SelectionFilter;
115 import org.simantics.browsing.ui.StatePersistor;
116 import org.simantics.browsing.ui.common.AdaptableHintContext;
117 import org.simantics.browsing.ui.common.ColumnKeys;
118 import org.simantics.browsing.ui.common.ErrorLogger;
119 import org.simantics.browsing.ui.common.NodeContextBuilder;
120 import org.simantics.browsing.ui.common.NodeContextUtil;
121 import org.simantics.browsing.ui.common.internal.GECache;
122 import org.simantics.browsing.ui.common.internal.GENodeQueryManager;
123 import org.simantics.browsing.ui.common.internal.IGECache;
124 import org.simantics.browsing.ui.common.internal.IGraphExplorerContext;
125 import org.simantics.browsing.ui.common.internal.UIElementReference;
126 import org.simantics.browsing.ui.common.processors.DefaultCheckedStateProcessor;
127 import org.simantics.browsing.ui.common.processors.DefaultComparableChildrenProcessor;
128 import org.simantics.browsing.ui.common.processors.DefaultFinalChildrenProcessor;
129 import org.simantics.browsing.ui.common.processors.DefaultImageDecoratorProcessor;
130 import org.simantics.browsing.ui.common.processors.DefaultImagerFactoriesProcessor;
131 import org.simantics.browsing.ui.common.processors.DefaultImagerProcessor;
132 import org.simantics.browsing.ui.common.processors.DefaultLabelDecoratorProcessor;
133 import org.simantics.browsing.ui.common.processors.DefaultLabelerFactoriesProcessor;
134 import org.simantics.browsing.ui.common.processors.DefaultLabelerProcessor;
135 import org.simantics.browsing.ui.common.processors.DefaultPrunedChildrenProcessor;
136 import org.simantics.browsing.ui.common.processors.DefaultSelectedImageDecoratorFactoriesProcessor;
137 import org.simantics.browsing.ui.common.processors.DefaultSelectedLabelDecoratorFactoriesProcessor;
138 import org.simantics.browsing.ui.common.processors.DefaultSelectedLabelerProcessor;
139 import org.simantics.browsing.ui.common.processors.DefaultSelectedViewpointFactoryProcessor;
140 import org.simantics.browsing.ui.common.processors.DefaultSelectedViewpointProcessor;
141 import org.simantics.browsing.ui.common.processors.DefaultViewpointContributionProcessor;
142 import org.simantics.browsing.ui.common.processors.DefaultViewpointContributionsProcessor;
143 import org.simantics.browsing.ui.common.processors.DefaultViewpointProcessor;
144 import org.simantics.browsing.ui.common.processors.IsExpandedProcessor;
145 import org.simantics.browsing.ui.common.processors.NoSelectionRequestProcessor;
146 import org.simantics.browsing.ui.common.processors.ProcessorLifecycle;
147 import org.simantics.browsing.ui.common.state.ExplorerStates;
148 import org.simantics.browsing.ui.content.ImageDecorator;
149 import org.simantics.browsing.ui.content.Imager;
150 import org.simantics.browsing.ui.content.LabelDecorator;
151 import org.simantics.browsing.ui.content.Labeler;
152 import org.simantics.browsing.ui.content.Labeler.CustomModifier;
153 import org.simantics.browsing.ui.content.Labeler.DeniedModifier;
154 import org.simantics.browsing.ui.content.Labeler.DialogModifier;
155 import org.simantics.browsing.ui.content.Labeler.EnumerationModifier;
156 import org.simantics.browsing.ui.content.Labeler.FilteringModifier;
157 import org.simantics.browsing.ui.content.Labeler.LabelerListener;
158 import org.simantics.browsing.ui.content.Labeler.Modifier;
159 import org.simantics.browsing.ui.content.PrunedChildrenResult;
160 import org.simantics.browsing.ui.model.nodetypes.EntityNodeType;
161 import org.simantics.browsing.ui.model.nodetypes.NodeType;
162 import org.simantics.browsing.ui.swt.internal.Threads;
163 import org.simantics.db.layer0.SelectionHints;
164 import org.simantics.utils.ObjectUtils;
165 import org.simantics.utils.datastructures.BijectionMap;
166 import org.simantics.utils.datastructures.disposable.AbstractDisposable;
167 import org.simantics.utils.datastructures.hints.IHintContext;
168 import org.simantics.utils.threads.IThreadWorkQueue;
169 import org.simantics.utils.threads.SWTThread;
170 import org.simantics.utils.threads.ThreadUtils;
171 import org.simantics.utils.ui.ISelectionUtils;
172 import org.simantics.utils.ui.SWTUtils;
173 import org.simantics.utils.ui.jface.BasePostSelectionProvider;
174 import org.simantics.utils.ui.widgets.VetoingEventHandler;
175 import org.simantics.utils.ui.workbench.WorkbenchUtils;
177 import gnu.trove.map.hash.THashMap;
178 import gnu.trove.procedure.TObjectProcedure;
179 import gnu.trove.set.hash.THashSet;
182 * @see #getMaxChildren()
183 * @see #setMaxChildren(int)
184 * @see #getMaxChildren(NodeQueryManager, NodeContext)
186 class GraphExplorerImpl extends GraphExplorerImplBase implements Listener, GraphExplorer /*, IPostSelectionProvider*/ {
188 private static class GraphExplorerPostSelectionProvider implements IPostSelectionProvider {
190 private GraphExplorerImpl ge;
192 GraphExplorerPostSelectionProvider(GraphExplorerImpl ge) {
201 public void setSelection(final ISelection selection) {
202 if(ge == null) return;
203 ge.setSelection(selection, false);
208 public void removeSelectionChangedListener(ISelectionChangedListener listener) {
209 if(ge == null) return;
210 if(ge.isDisposed()) {
211 if (DEBUG_SELECTION_LISTENERS)
212 System.out.println("GraphExplorerImpl is disposed in removeSelectionChangedListener: " + listener);
215 //assertNotDisposed();
216 //System.out.println("Remove selection changed listener: " + listener);
217 ge.selectionProvider.removeSelectionChangedListener(listener);
221 public void addPostSelectionChangedListener(ISelectionChangedListener listener) {
222 if(ge == null) return;
223 if (!ge.thread.currentThreadAccess())
224 throw new AssertionError(getClass().getSimpleName() + ".addPostSelectionChangedListener called from non SWT-thread: " + Thread.currentThread());
225 if(ge.isDisposed()) {
226 System.out.println("Client BUG: GraphExplorerImpl is disposed in addPostSelectionChangedListener: " + listener);
229 //System.out.println("Add POST selection changed listener: " + listener);
230 ge.selectionProvider.addPostSelectionChangedListener(listener);
234 public void removePostSelectionChangedListener(ISelectionChangedListener listener) {
235 if(ge == null) return;
236 if(ge.isDisposed()) {
237 if (DEBUG_SELECTION_LISTENERS)
238 System.out.println("GraphExplorerImpl is disposed in removePostSelectionChangedListener: " + listener);
241 // assertNotDisposed();
242 //System.out.println("Remove POST selection changed listener: " + listener);
243 ge.selectionProvider.removePostSelectionChangedListener(listener);
248 public void addSelectionChangedListener(ISelectionChangedListener listener) {
249 if(ge == null) return;
250 if (!ge.thread.currentThreadAccess())
251 throw new AssertionError(getClass().getSimpleName() + ".addSelectionChangedListener called from non SWT-thread: " + Thread.currentThread());
252 //System.out.println("Add selection changed listener: " + listener);
253 if (ge.tree.isDisposed() || ge.selectionProvider == null) {
254 System.out.println("Client BUG: GraphExplorerImpl is disposed in addSelectionChangedListener: " + listener);
258 ge.selectionProvider.addSelectionChangedListener(listener);
263 public ISelection getSelection() {
264 if(ge == null) return StructuredSelection.EMPTY;
265 if (!ge.thread.currentThreadAccess())
266 throw new AssertionError(getClass().getSimpleName() + ".getSelection called from non SWT-thread: " + Thread.currentThread());
267 if (ge.tree.isDisposed() || ge.selectionProvider == null)
268 return StructuredSelection.EMPTY;
269 return ge.selectionProvider.getSelection();
275 * If this explorer is running with an Eclipse workbench open, this
276 * Workbench UI context will be activated whenever inline editing is started
277 * through {@link #startEditing(TreeItem, int)} and deactivated when inline
280 * This context information can be used to for UI handler activity testing.
282 private static final String INLINE_EDITING_UI_CONTEXT = "org.simantics.browsing.ui.inlineEditing";
284 private static final String KEY_DRAG_COLUMN = "dragColumn";
286 private static final boolean DEBUG_SELECTION_LISTENERS = false;
288 private static final int DEFAULT_CONSECUTIVE_LABEL_REFRESH_DELAY = 200;
290 public static final int DEFAULT_MAX_CHILDREN = 1000;
292 private final IThreadWorkQueue thread;
295 * Local method for checking from whether resources are loaded in
298 private final LocalResourceManager localResourceManager;
301 * Local device resource manager that is safe to use in
302 * {@link ImageLoaderJob} for creating images in a non-UI thread.
304 private final ResourceManager resourceManager;
307 * Package visibility.
308 * TODO: Get rid of these.
312 @SuppressWarnings({ "rawtypes" })
313 final HashMap<CacheKey<?>, NodeQueryProcessor> processors = new HashMap<>();
314 @SuppressWarnings({ "rawtypes" })
315 final HashMap<Object, PrimitiveQueryProcessor> primitiveProcessors = new HashMap<>();
316 @SuppressWarnings({ "rawtypes" })
317 final HashMap<Class, DataSource> dataSources = new HashMap<>();
319 class GraphExplorerContext extends AbstractDisposable implements IGraphExplorerContext {
320 // This is for query debugging only.
323 GECache cache = new GECache();
324 AtomicBoolean propagating = new AtomicBoolean(false);
325 Object propagateList = new Object();
326 Object propagate = new Object();
327 List<Runnable> scheduleList = new ArrayList<Runnable>();
328 final Deque<Integer> activity = new LinkedList<Integer>();
332 * Stores the currently running query update runnable. If
333 * <code>null</code> there's nothing scheduled yet in which case
334 * scheduling can commence. Otherwise the update should be skipped.
336 AtomicReference<Runnable> currentQueryUpdater = new AtomicReference<>();
339 * Keeps track of nodes that have already been auto-expanded. After
340 * being inserted into this set, nodes will not be forced to stay in an
341 * expanded state after that. This makes it possible for the user to
342 * close auto-expanded nodes.
344 Map<NodeContext, Boolean> autoExpanded = new WeakHashMap<>();
348 protected void doDispose() {
350 autoExpanded.clear();
354 public IGECache getCache() {
359 public int queryIndent() {
364 public int queryIndent(int offset) {
365 queryIndent += offset;
370 @SuppressWarnings("unchecked")
371 public <T> NodeQueryProcessor<T> getProcessor(Object o) {
372 return processors.get(o);
376 @SuppressWarnings("unchecked")
377 public <T> PrimitiveQueryProcessor<T> getPrimitiveProcessor(Object o) {
378 return primitiveProcessors.get(o);
381 @SuppressWarnings("unchecked")
383 public <T> DataSource<T> getDataSource(Class<T> clazz) {
384 return dataSources.get(clazz);
388 public void update(UIElementReference ref) {
389 //System.out.println("GE.update " + ref);
390 TreeItemReference tiref = (TreeItemReference) ref;
391 TreeItem item = tiref.getItem();
392 // NOTE: must be called regardless of the the item value.
393 // A null item is currently used to indicate a tree root update.
394 GraphExplorerImpl.this.update(item);
398 public Object getPropagateLock() {
403 public Object getPropagateListLock() {
404 return propagateList;
408 public boolean isPropagating() {
409 return propagating.get();
413 public void setPropagating(boolean b) {
414 this.propagating.set(b);
418 public List<Runnable> getScheduleList() {
423 public void setScheduleList(List<Runnable> list) {
424 this.scheduleList = list;
428 public Deque<Integer> getActivity() {
433 public void setActivityInt(int i) {
434 this.activityInt = i;
438 public int getActivityInt() {
443 public void scheduleQueryUpdate(Runnable r) {
444 if (GraphExplorerImpl.this.isDisposed() || queryUpdateScheduler.isShutdown())
446 //System.out.println("Scheduling query update for runnable " + r);
447 if (currentQueryUpdater.compareAndSet(null, r)) {
448 //System.out.println("Scheduling query update for runnable " + r);
449 queryUpdateScheduler.execute(QUERY_UPDATE_SCHEDULER);
453 Runnable QUERY_UPDATE_SCHEDULER = new Runnable() {
456 Runnable r = currentQueryUpdater.getAndSet(null);
458 //System.out.println("Running query update runnable " + r);
465 GraphExplorerContext explorerContext = new GraphExplorerContext();
467 HashSet<TreeItem> pendingItems = new HashSet<>();
468 boolean updating = false;
469 boolean pendingRoot = false;
471 @SuppressWarnings("deprecation")
472 ModificationContext modificationContext = null;
474 NodeContext rootContext;
476 StatePersistor persistor = null;
478 boolean editable = true;
481 * This is a reverse mapping from {@link NodeContext} tree objects back to
482 * their owner TreeItems.
485 * Access this map only in the SWT thread to keep it thread-safe.
488 BijectionMap<NodeContext, TreeItem> contextToItem = new BijectionMap<>();
491 * Columns of the UI viewer. Use {@link #setColumns(Column[])} to
494 Column[] columns = new Column[0];
495 Map<String, Integer> columnKeyToIndex = new HashMap<>();
496 boolean refreshingColumnSizes = false;
497 boolean columnsAreVisible = true;
500 * An array reused for invoking {@link TreeItem#setImage(Image[])} instead
501 * of constantly allocating new arrays for setting each TreeItems images.
502 * This works because {@link TreeItem#setImage(Image[])} does not take hold
503 * of the array itself, only the contents of the array.
505 * @see #setImage(NodeContext, TreeItem, Imager, Collection, int)
507 Image[] columnImageArray = { null };
510 * Used for collecting Image or ImageDescriptor instances for a single
511 * TreeItem when initially setting images for a TreeItem.
513 * @see #setImage(NodeContext, TreeItem, Imager, Collection, int)
515 Object[] columnDescOrImageArray = { null };
517 final ExecutorService queryUpdateScheduler = Threads.getExecutor();
518 final ScheduledExecutorService uiUpdateScheduler = ThreadUtils.getNonBlockingWorkExecutor();
520 /** Set to true when the Tree widget is disposed. */
521 private boolean disposed = false;
522 private final CopyOnWriteArrayList<FocusListener> focusListeners = new CopyOnWriteArrayList<>();
523 private final CopyOnWriteArrayList<MouseListener> mouseListeners = new CopyOnWriteArrayList<>();
524 private final CopyOnWriteArrayList<KeyListener> keyListeners = new CopyOnWriteArrayList<>();
526 /** Selection provider */
527 private GraphExplorerPostSelectionProvider postSelectionProvider = new GraphExplorerPostSelectionProvider(this);
528 protected BasePostSelectionProvider selectionProvider = new BasePostSelectionProvider();
529 protected SelectionDataResolver selectionDataResolver;
530 protected SelectionFilter selectionFilter;
531 protected BiFunction<GraphExplorer, Object[], Object[]> selectionTransformation = new BiFunction<GraphExplorer, Object[], Object[]>() {
534 public Object[] apply(GraphExplorer explorer, Object[] objects) {
535 Object[] result = new Object[objects.length];
536 for (int i = 0; i < objects.length; i++) {
537 IHintContext context = new AdaptableHintContext(SelectionHints.KEY_MAIN);
538 context.setHint(SelectionHints.KEY_MAIN, objects[i]);
545 protected FontDescriptor originalFont;
546 protected ColorDescriptor originalForeground;
547 protected ColorDescriptor originalBackground;
550 * The set of currently selected TreeItem instances. This set is needed
551 * because we need to know in {@link #setData(Event)} whether the updated
552 * item was a part of the current selection in which case the selection must
555 private final Map<TreeItem, NodeContext> selectedItems = new HashMap<>();
558 * TODO: specify what this is for
560 private final Set<NodeContext> selectionRefreshContexts = new HashSet<>();
563 * If this field is non-null, it means that if {@link #setData(Event)}
564 * encounters a NodeContext equal to this one, it must make the TreeItem
565 * assigned to that NodeContext the topmost item of the tree using
566 * {@link Tree#setTopItem(TreeItem)}. After this the field value is
570 * This is related to {@link #initializeState()}, i.e. explorer state
573 // private NodeContext[] topNodePath = NodeContext.NONE;
574 // private int[] topNodePath = {};
575 // private int currentTopNodePathIndex = -1;
578 * See {@link #setAutoExpandLevel(int)}
580 private int autoExpandLevel = 0;
583 * <code>null</code> if not explicitly set through
584 * {@link #setServiceLocator(IServiceLocator)}.
586 private IServiceLocator serviceLocator;
589 * The global workbench context service, if the workbench is available.
590 * Retrieved in the constructor.
592 private IContextService contextService = null;
595 * The global workbench IFocusService, if the workbench is available.
596 * Retrieved in the constructor.
598 private IFocusService focusService = null;
601 * A Workbench UI context activation that is activated when starting inline
602 * editing through {@link #startEditing(TreeItem, int)}.
604 * @see #activateEditingContext()
605 * @see #deactivateEditingContext()
607 private IContextActivation editingContext = null;
609 static class ImageTask {
612 Object[] descsOrImages;
613 public ImageTask(NodeContext node, TreeItem item, Object[] descsOrImages) {
616 this.descsOrImages = descsOrImages;
621 * The job that is used for off-loading image loading tasks (see
622 * {@link ImageTask} to a worker thread from the main UI thread.
624 * @see #setPendingImages(IProgressMonitor)
626 ImageLoaderJob imageLoaderJob;
629 * The set of currently gathered up image loading tasks for
630 * {@link #imageLoaderJob} to execute.
632 * @see #setPendingImages(IProgressMonitor)
634 Map<TreeItem, ImageTask> imageTasks = new THashMap<>();
637 * A state flag indicating whether the vertical scroll bar was visible for
638 * {@link #tree} the last time it was checked. Since there is no listener
639 * that can provide this information, we check it in {@link #setData(Event)}
640 * every time any data for a TreeItem is updated. If the visibility changes,
641 * we will force re-layouting of the tree's parent composite.
643 * @see #setData(Event)
645 private boolean verticalBarVisible = false;
647 static class TransientStateImpl implements TransientExplorerState {
649 private Integer activeColumn = null;
652 public synchronized Integer getActiveColumn() {
656 public synchronized void setActiveColumn(Integer column) {
657 activeColumn = column;
662 private TransientStateImpl transientState = new TransientStateImpl();
664 boolean scheduleUpdater() {
666 if (tree.isDisposed())
669 if (pendingRoot == true || !pendingItems.isEmpty()) {
670 assert(!tree.isDisposed());
672 int activity = explorerContext.activityInt;
674 if (activity < 100) {
675 // System.out.println("Scheduling update immediately.");
676 } else if (activity < 1000) {
677 // System.out.println("Scheduling update after 500ms.");
680 // System.out.println("Scheduling update after 3000ms.");
686 //System.out.println("Scheduling UI update after " + delay + " ms.");
687 uiUpdateScheduler.schedule(new Runnable() {
691 if (tree.isDisposed())
694 if (updateCounter > 0) {
696 uiUpdateScheduler.schedule(this, 50, TimeUnit.MILLISECONDS);
698 tree.getDisplay().asyncExec(new UpdateRunner(GraphExplorerImpl.this));
702 }, delay, TimeUnit.MILLISECONDS);
711 int updateCounter = 0;
713 void update(TreeItem item) {
715 synchronized(pendingItems) {
717 // System.out.println("update " + item);
721 if(item == null) pendingRoot = true;
722 else pendingItems.add(item);
724 if(updating == true) return;
732 private int maxChildren = DEFAULT_MAX_CHILDREN;
735 public int getMaxChildren() {
740 public int getMaxChildren(NodeQueryManager manager, NodeContext context) {
741 Integer result = manager.query(context, BuiltinKeys.SHOW_MAX_CHILDREN);
742 //System.out.println("getMaxChildren(" + manager + ", " + context + "): " + result);
743 if (result != null) {
745 throw new AssertionError("BuiltinKeys.SHOW_MAX_CHILDREN query must never return < 0, got " + result);
752 public void setMaxChildren(int maxChildren) {
753 this.maxChildren = maxChildren;
757 public void setModificationContext(@SuppressWarnings("deprecation") ModificationContext modificationContext) {
758 this.modificationContext = modificationContext;
762 * @param parent the parent SWT composite
764 public GraphExplorerImpl(Composite parent) {
765 this(parent, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
769 * Stores the node context and the modifier that is currently being
770 * modified. These are used internally to prevent duplicate edits from being
771 * initiated which should always be a sensible thing to do.
773 private Set<NodeContext> currentlyModifiedNodes = new THashSet<>();
775 private final TreeEditor editor;
776 private Color invalidModificationColor = null;
779 * @param item the TreeItem to start editing
780 * @param columnIndex the index of the column to edit, starts counting from
782 * @return <code>true</code> if the editing was initiated successfully or
783 * <code>false</code> if editing could not be started due to lack of
784 * {@link Modifier} for the labeler in question.
786 private String startEditing(final TreeItem item, final int columnIndex, String columnKey) {
788 return "Rename not supported for selection";
790 GENodeQueryManager manager = new GENodeQueryManager(this.explorerContext, null, null, TreeItemReference.create(item.getParentItem()));
791 final NodeContext context = (NodeContext) item.getData();
792 Labeler labeler = manager.query(context, BuiltinKeys.SELECTED_LABELER);
794 return "Rename not supported for selection";
796 if(columnKey == null) columnKey = columns[columnIndex].getKey();
798 // columnKey might be prefixed with '#' to indicate
799 // textual editing is preferred. Try to get modifier
800 // for that first and only if it fails, try without
802 Modifier modifier = labeler.getModifier(modificationContext, columnKey);
803 if (modifier == null) {
804 if(columnKey.startsWith("#"))
805 modifier = labeler.getModifier(modificationContext, columnKey.substring(1));
806 if (modifier == null)
807 return "Rename not supported for selection";
809 if (modifier instanceof DeniedModifier) {
810 DeniedModifier dm = (DeniedModifier)modifier;
811 return dm.getMessage();
814 // Prevent editing of a single node context multiple times.
815 if (currentlyModifiedNodes.contains(context)) {
816 //System.out.println("discarding duplicate edit for context " + context);
817 return "Rename not supported for selection";
820 // Clean up any previous editor control
821 Control oldEditor = editor.getEditor();
822 if (oldEditor != null)
825 if (modifier instanceof DialogModifier) {
826 performDialogEditing(item, columnIndex, context, (DialogModifier) modifier);
827 } else if (modifier instanceof CustomModifier) {
828 startCustomEditing(item, columnIndex, context, (CustomModifier) modifier);
829 } else if (modifier instanceof EnumerationModifier) {
830 startEnumerationEditing(item, columnIndex, context, (EnumerationModifier) modifier);
832 startTextEditing(item, columnIndex, context, modifier);
844 void performDialogEditing(final TreeItem item, final int columnIndex, final NodeContext context,
845 final DialogModifier modifier) {
846 final AtomicBoolean disposed = new AtomicBoolean(false);
847 Consumer<String> callback = result -> {
850 String error = modifier.isValid(result);
852 modifier.modify(result);
853 // Item may be disposed if the tree gets reset after a previous editing.
854 if (!item.isDisposed()) {
855 item.setText(columnIndex, result);
856 queueSelectionRefresh(context);
861 currentlyModifiedNodes.add(context);
863 String status = modifier.query(tree, item, columnIndex, context, callback);
865 ErrorLogger.defaultLog( new Status(IStatus.INFO, Activator.PLUGIN_ID, status) );
867 currentlyModifiedNodes.remove(context);
872 private void reconfigureTreeEditor(TreeItem item, int columnIndex, Control control, int widthHint, int heightHint, int insetX, int insetY) {
873 Point size = control.computeSize(widthHint, heightHint);
874 editor.horizontalAlignment = SWT.LEFT;
875 Rectangle itemRect = item.getBounds(columnIndex),
876 rect = tree.getClientArea();
877 editor.minimumWidth = Math.max(size.x, itemRect.width) + insetX * 2;
878 int left = itemRect.x,
879 right = rect.x + rect.width;
880 editor.minimumWidth = Math.min(editor.minimumWidth, right - left);
881 editor.minimumHeight = size.y + insetY * 2;
885 void reconfigureTreeEditorForText(TreeItem item, int columnIndex, Control control, String text, int heightHint, int insetX, int insetY) {
886 GC gc = new GC(control);
887 Point size = gc.textExtent(text);
889 reconfigureTreeEditor(item, columnIndex, control, size.x, SWT.DEFAULT, insetX, insetY);
898 void startCustomEditing(final TreeItem item, final int columnIndex, final NodeContext context,
899 final CustomModifier modifier) {
900 final Object obj = modifier.createControl(tree, item, columnIndex, context);
901 if (!(obj instanceof Control))
902 throw new UnsupportedOperationException("SWT control required, got " + obj + " from CustomModifier.createControl(Object)");
903 final Control control = (Control) obj;
905 // final int insetX = 0;
906 // final int insetY = 0;
907 // control.addListener(SWT.Resize, new Listener() {
909 // public void handleEvent(Event e) {
910 // Rectangle rect = control.getBounds();
911 // control.setBounds(rect.x + insetX, rect.y + insetY, rect.width - insetX * 2, rect.height - insetY * 2);
914 control.addListener(SWT.Dispose, new Listener() {
916 public void handleEvent(Event event) {
917 currentlyModifiedNodes.remove(context);
918 queueSelectionRefresh(context);
919 deactivateEditingContext();
923 if (!(control instanceof Shell)) {
924 editor.setEditor(control, item, columnIndex);
930 GraphExplorerImpl.this.reconfigureTreeEditor(item, columnIndex, control, SWT.DEFAULT, SWT.DEFAULT, 0, 0);
932 activateEditingContext(control);
934 // Removed in disposeListener above
935 currentlyModifiedNodes.add(context);
936 //System.out.println("START CUSTOM EDITING: " + item);
945 void startEnumerationEditing(final TreeItem item, final int columnIndex, final NodeContext context, final EnumerationModifier modifier) {
946 String initialText = modifier.getValue();
947 if (initialText == null)
948 throw new AssertionError("Labeler.Modifier.getValue() returned null");
950 List<String> values = modifier.getValues();
951 String selectedValue = modifier.getValue();
952 int selectedIndex = values.indexOf(selectedValue);
953 if (selectedIndex == -1)
954 throw new AssertionFailedException(modifier + " EnumerationModifier.getValue returned '" + selectedValue + "' which is not among the possible values returned by EnumerationModifier.getValues(): " + values);
956 final CCombo combo = new CCombo(tree, SWT.FLAT | SWT.BORDER | SWT.READ_ONLY | SWT.DROP_DOWN);
957 combo.setVisibleItemCount(10);
958 //combo.setEditable(false);
960 for (String value : values) {
963 combo.select(selectedIndex);
965 Listener comboListener = new Listener() {
966 boolean arrowTraverseUsed = false;
968 public void handleEvent(final Event e) {
969 //System.out.println("FOO: " + e);
972 if (e.character == SWT.CR) {
973 // Commit edit directly on ENTER press.
974 String text = combo.getText();
975 modifier.modify(text);
976 // Item may be disposed if the tree gets reset after a previous editing.
977 if (!item.isDisposed()) {
978 item.setText(columnIndex, text);
979 queueSelectionRefresh(context);
983 } else if (e.keyCode == SWT.ESC) {
984 // Cancel editing immediately
991 if (arrowTraverseUsed) {
992 arrowTraverseUsed = false;
996 String text = combo.getText();
997 modifier.modify(text);
999 // Item may be disposed if the tree gets reset after a previous editing.
1000 if (!item.isDisposed()) {
1001 item.setText(columnIndex, text);
1002 queueSelectionRefresh(context);
1007 case SWT.FocusOut: {
1008 String text = combo.getText();
1009 modifier.modify(text);
1011 // Item may be disposed if the tree gets reset after a previous editing.
1012 if (!item.isDisposed()) {
1013 item.setText(columnIndex, text);
1014 queueSelectionRefresh(context);
1019 case SWT.Traverse: {
1021 case SWT.TRAVERSE_RETURN:
1022 String text = combo.getText();
1023 modifier.modify(text);
1024 if (!item.isDisposed()) {
1025 item.setText(columnIndex, text);
1026 queueSelectionRefresh(context);
1028 arrowTraverseUsed = false;
1030 case SWT.TRAVERSE_ESCAPE:
1034 case SWT.TRAVERSE_ARROW_NEXT:
1035 case SWT.TRAVERSE_ARROW_PREVIOUS:
1036 arrowTraverseUsed = true;
1039 //System.out.println("unhandled traversal: " + e.detail);
1045 currentlyModifiedNodes.remove(context);
1046 deactivateEditingContext();
1051 combo.addListener(SWT.MouseWheel, VetoingEventHandler.INSTANCE);
1052 combo.addListener(SWT.KeyDown, comboListener);
1053 combo.addListener(SWT.FocusOut, comboListener);
1054 combo.addListener(SWT.Traverse, comboListener);
1055 combo.addListener(SWT.Selection, comboListener);
1056 combo.addListener(SWT.Dispose, comboListener);
1058 editor.setEditor(combo, item, columnIndex);
1061 combo.setListVisible(true);
1063 GraphExplorerImpl.this.reconfigureTreeEditorForText(item, columnIndex, combo, combo.getText(), SWT.DEFAULT, 0, 0);
1065 activateEditingContext(combo);
1067 // Removed in comboListener
1068 currentlyModifiedNodes.add(context);
1070 //System.out.println("START ENUMERATION EDITING: " + item);
1075 * @param columnIndex
1079 void startTextEditing(final TreeItem item, final int columnIndex, final NodeContext context, final Modifier modifier) {
1080 String initialText = modifier.getValue();
1081 if (initialText == null)
1082 throw new AssertionError("Labeler.Modifier.getValue() returned null, modifier=" + modifier);
1084 final Composite composite = new Composite(tree, SWT.NONE);
1085 //composite.setBackground(composite.getDisplay().getSystemColor(SWT.COLOR_RED));
1086 final Text text = new Text(composite, SWT.BORDER);
1087 final int insetX = 0;
1088 final int insetY = 0;
1089 composite.addListener(SWT.Resize, new Listener() {
1091 public void handleEvent(Event e) {
1092 Rectangle rect = composite.getClientArea();
1093 text.setBounds(rect.x + insetX, rect.y + insetY, rect.width - insetX * 2, rect.height
1097 final FilteringModifier filter = modifier instanceof FilteringModifier ? (FilteringModifier) modifier : null;
1098 Listener textListener = new Listener() {
1100 boolean modified = false;
1103 public void handleEvent(final Event e) {
1109 //System.out.println("FOCUS OUT " + item);
1110 newText = text.getText();
1111 error = modifier.isValid(newText);
1112 if (error == null) {
1113 modifier.modify(newText);
1115 // Item may be disposed if the tree gets reset after a previous editing.
1116 if (!item.isDisposed()) {
1117 item.setText(columnIndex, newText);
1118 queueSelectionRefresh(context);
1121 // System.out.println("validation error: " + error);
1124 composite.dispose();
1127 newText = text.getText();
1128 error = modifier.isValid(newText);
1129 if (error != null) {
1130 text.setBackground(invalidModificationColor);
1132 //System.out.println("validation error: " + error);
1134 text.setBackground(null);
1141 // Safety check since it seems that this may happen with
1143 if (item.isDisposed())
1146 // Filter input if necessary
1147 e.text = filter != null ? filter.filter(e.text) : e.text;
1149 newText = text.getText();
1150 String leftText = newText.substring(0, e.start);
1151 String rightText = newText.substring(e.end, newText.length());
1152 GraphExplorerImpl.this.reconfigureTreeEditorForText(
1153 item, columnIndex, text, leftText + e.text + rightText,
1154 SWT.DEFAULT, insetX, insetY);
1158 case SWT.TRAVERSE_RETURN:
1160 newText = text.getText();
1161 error = modifier.isValid(newText);
1162 if (error == null) {
1163 modifier.modify(newText);
1164 if (!item.isDisposed()) {
1165 item.setText(columnIndex, newText);
1166 queueSelectionRefresh(context);
1171 case SWT.TRAVERSE_ESCAPE:
1172 composite.dispose();
1176 //System.out.println("unhandled traversal: " + e.detail);
1182 currentlyModifiedNodes.remove(context);
1183 deactivateEditingContext();
1189 // Set the initial text before registering a listener. We do not want immediate modification!
1190 text.setText(initialText);
1191 text.addListener(SWT.FocusOut, textListener);
1192 text.addListener(SWT.Traverse, textListener);
1193 text.addListener(SWT.Verify, textListener);
1194 text.addListener(SWT.Modify, textListener);
1195 text.addListener(SWT.Dispose, textListener);
1196 editor.setEditor(composite, item, columnIndex);
1200 // Initialize TreeEditor properly.
1201 GraphExplorerImpl.this.reconfigureTreeEditorForText(
1202 item, columnIndex, text, initialText,
1203 SWT.DEFAULT, insetX, insetY);
1205 // Removed in textListener
1206 currentlyModifiedNodes.add(context);
1208 activateEditingContext(text);
1210 //System.out.println("START TEXT EDITING: " + item);
1213 protected void errorStatus(String error) {
1214 IStatusLineManager status = getStatusLineManager();
1215 if (status != null) {
1216 status.setErrorMessage(error);
1220 protected IStatusLineManager getStatusLineManager() {
1221 if (serviceLocator instanceof IWorkbenchPart) {
1222 return WorkbenchUtils.getStatusLine((IWorkbenchPart) serviceLocator);
1223 } else if (serviceLocator instanceof IWorkbenchSite) {
1224 return WorkbenchUtils.getStatusLine((IWorkbenchSite) serviceLocator);
1229 protected void activateEditingContext(Control control) {
1230 if (contextService != null) {
1231 editingContext = contextService.activateContext(INLINE_EDITING_UI_CONTEXT);
1233 if (control != null && focusService != null) {
1234 focusService.addFocusTracker(control, INLINE_EDITING_UI_CONTEXT);
1235 // No need to remove the control, it will be
1236 // removed automatically when it is disposed.
1240 protected void deactivateEditingContext() {
1241 IContextActivation a = editingContext;
1243 editingContext = null;
1244 contextService.deactivateContext(a);
1251 void queueSelectionRefresh(NodeContext forContext) {
1252 selectionRefreshContexts.add(forContext);
1256 public String startEditing(NodeContext context, String columnKey_) {
1257 assertNotDisposed();
1258 if (!thread.currentThreadAccess())
1259 throw new IllegalStateException("not in SWT display thread " + thread.getThread());
1261 String columnKey = columnKey_;
1262 if(columnKey.startsWith("#")) {
1263 columnKey = columnKey.substring(1);
1266 Integer columnIndex = columnKeyToIndex.get(columnKey);
1267 if (columnIndex == null)
1268 return "Rename not supported for selection";
1270 TreeItem item = contextToItem.getRight(context);
1272 return "Rename not supported for selection";
1274 return startEditing(item, columnIndex, columnKey_);
1279 public String startEditing(String columnKey) {
1281 ISelection selection = postSelectionProvider.getSelection();
1282 if(selection == null) return "Rename not supported for selection";
1283 NodeContext context = ISelectionUtils.filterSingleSelection(selection, NodeContext.class);
1284 if(context == null) return "Rename not supported for selection";
1286 return startEditing(context, columnKey);
1291 * @param site <code>null</code> if the explorer is detached from the workbench
1292 * @param parent the parent SWT composite
1293 * @param style the tree style to use, check the see tags for the available flags
1298 * @see SWT#FULL_SELECTION
1299 * @see SWT#NO_SCROLL
1303 public GraphExplorerImpl(Composite parent, int style) {
1305 setServiceLocator(null);
1307 this.localResourceManager = new LocalResourceManager(JFaceResources.getResources());
1308 this.resourceManager = new DeviceResourceManager(parent.getDisplay());
1310 this.imageLoaderJob = new ImageLoaderJob(this);
1311 this.imageLoaderJob.setPriority(Job.DECORATE);
1313 invalidModificationColor = (Color) localResourceManager.get( ColorDescriptor.createFrom( new RGB(255, 128, 128) ) );
1315 this.thread = SWTThread.getThreadAccess(parent);
1317 for(int i=0;i<10;i++) explorerContext.activity.push(0);
1319 tree = new Tree(parent, style);
1320 tree.addListener(SWT.SetData, this);
1321 tree.addListener(SWT.Expand, this);
1322 tree.addListener(SWT.Dispose, this);
1323 tree.addListener(SWT.Activate, this);
1325 tree.setData(KEY_GRAPH_EXPLORER, this);
1327 // These are both required for performing column resizing without flicker.
1328 // See SWT.Resize event handling in #handleEvent() for more explanations.
1329 parent.addListener(SWT.Resize, this);
1330 tree.addListener(SWT.Resize, this);
1332 originalFont = JFaceResources.getDefaultFontDescriptor();
1333 // originalBackground = JFaceResources.getColorRegistry().get(symbolicName);
1334 // originalForeground = tree.getForeground();
1336 tree.setFont((Font) localResourceManager.get(originalFont));
1338 columns = new Column[] { new Column(ColumnKeys.SINGLE) };
1339 columnKeyToIndex = Collections.singletonMap(ColumnKeys.SINGLE, 0);
1341 editor = new TreeEditor(tree);
1342 editor.horizontalAlignment = SWT.LEFT;
1343 editor.grabHorizontal = true;
1344 editor.minimumWidth = 50;
1346 setBasicListeners();
1347 setDefaultProcessors();
1349 this.toolTip = new GraphExplorerToolTip(explorerContext, tree);
1353 public IThreadWorkQueue getThread() {
1357 TreeItem previousSingleSelection = null;
1358 long focusGainedAt = Long.MIN_VALUE;
1360 protected GraphExplorerToolTip toolTip;
1362 protected void setBasicListeners() {
1363 // Keep track of the previous single selection to help
1364 // decide whether to start editing a tree node on mouse
1366 tree.addListener(SWT.Selection, event -> {
1367 TreeItem[] selection = tree.getSelection();
1368 if (selection.length == 1) {
1369 //for (TreeItem item : selection)
1370 // System.out.println("selection: " + item);
1371 previousSingleSelection = selection[0];
1373 previousSingleSelection = null;
1377 // Try to start editing of tree column when clicked for the second time.
1378 Listener mouseEditListener = new Listener() {
1380 Future<?> startEdit = null;
1383 public void handleEvent(Event event) {
1384 if (event.type == SWT.DragDetect) {
1385 // Needed to prevent editing from being started when in fact
1386 // the user starts dragging an item.
1387 //System.out.println("DRAG DETECT: " + event);
1391 //System.out.println("mouse down: " + event);
1392 if (event.button == 1) {
1393 // Always ignore the first mouse button press that focuses
1394 // the control. Do not let it start in-line editing since
1395 // that is very annoying to users and not how the UI's that
1396 // people are used to behave.
1397 long eventTime = ((long) event.time) & 0xFFFFFFFFL;
1398 if ((eventTime - focusGainedAt) < 250L) {
1399 //System.out.println("ignore mouse down " + focusGainedAt + ", " + eventTime + " = " + (eventTime-focusGainedAt));
1402 //System.out.println("testing whether to start editing");
1404 final Point point = new Point(event.x, event.y);
1405 final TreeItem item = tree.getItem(point);
1408 //System.out.println("mouse down @ " + point + ": " + item + ", previous item: " + previousSingleSelection);
1410 // Only start editing if the item was already selected.
1411 if (!item.equals(previousSingleSelection)) {
1416 if (tree.getColumnCount() > 1) {
1417 // TODO: reconsider this logic, might not be good in general.
1418 for (int i = 0; i < tree.getColumnCount(); i++) {
1419 if (item.getBounds(i).contains(point)) {
1420 tryScheduleEdit(event, item, point, 100, i);
1425 //System.out.println("clicks: " + event.count);
1426 if (item.getBounds().contains(point)) {
1427 if (event.count == 1) {
1428 tryScheduleEdit(event, item, point, 500, 0);
1437 void tryScheduleEdit(Event event, final TreeItem item, Point point, long delayMs, final int column) {
1438 //System.out.println("\tCONTAINS: " + item);
1442 //System.out.println("\tScheduling edit: " + item);
1443 startEdit = ThreadUtils.getNonBlockingWorkExecutor().schedule(new Runnable() {
1446 ThreadUtils.asyncExec(thread, new Runnable() {
1449 if (item.isDisposed())
1451 startEditing(item, column, null);
1455 }, delayMs, TimeUnit.MILLISECONDS);
1458 boolean cancelEdit() {
1459 Future<?> f = startEdit;
1461 // Try to cancel the start edit task if it's not running yet.
1464 boolean ret = f.cancel(false);
1465 //System.out.println("\tCancelled edit: " + ret);
1469 //System.out.println("\tNo edit in progress to cancel");
1473 tree.addListener(SWT.MouseDown, mouseEditListener);
1474 tree.addListener(SWT.DragDetect, mouseEditListener);
1475 tree.addListener(SWT.DragDetect, event -> {
1476 Point test = new Point(event.x, event.y);
1477 TreeItem item = tree.getItem(test);
1479 for(int i=0;i<tree.getColumnCount();i++) {
1480 Rectangle rect = item.getBounds(i);
1481 if(rect.contains(test)) {
1482 tree.setData(KEY_DRAG_COLUMN, i);
1487 tree.setData(KEY_DRAG_COLUMN, -1);
1489 tree.addListener(SWT.MouseMove, event -> {
1490 Point test = new Point(event.x, event.y);
1491 TreeItem item = tree.getItem(test);
1493 for(int i=0;i<tree.getColumnCount();i++) {
1494 Rectangle rect = item.getBounds(i);
1495 if(rect.contains(test)) {
1496 transientState.setActiveColumn(i);
1501 transientState.setActiveColumn(null);
1504 // Add focus/mouse/key listeners for supporting the respective
1505 // add/remove listener methods in IGraphExplorer.
1506 tree.addFocusListener(new FocusListener() {
1508 public void focusGained(FocusEvent e) {
1509 focusGainedAt = ((long) e.time) & 0xFFFFFFFFL;
1510 for (FocusListener listener : focusListeners)
1511 listener.focusGained(e);
1514 public void focusLost(FocusEvent e) {
1515 for (FocusListener listener : focusListeners)
1516 listener.focusLost(e);
1519 tree.addMouseListener(new MouseListener() {
1521 public void mouseDoubleClick(MouseEvent e) {
1522 for (MouseListener listener : mouseListeners) {
1523 listener.mouseDoubleClick(e);
1527 public void mouseDown(MouseEvent e) {
1528 for (MouseListener listener : mouseListeners) {
1529 listener.mouseDown(e);
1533 public void mouseUp(MouseEvent e) {
1534 for (MouseListener listener : mouseListeners) {
1535 listener.mouseUp(e);
1539 tree.addKeyListener(new KeyListener() {
1541 public void keyPressed(KeyEvent e) {
1542 for (KeyListener listener : keyListeners) {
1543 listener.keyPressed(e);
1547 public void keyReleased(KeyEvent e) {
1548 for (KeyListener listener : keyListeners) {
1549 listener.keyReleased(e);
1554 OpenStrategy os = new OpenStrategy(tree);
1555 os.addPostSelectionListener(SelectionListener.widgetSelectedAdapter(e -> {
1556 //System.out.println("OPENSTRATEGY: post selection changed: " + e);
1558 selectionProvider.firePostSelection(selectionProvider.getSelection());
1561 // This listener takes care of updating the set of currently selected
1562 // TreeItem instances. This set is needed because we need to know in
1563 // #setData(Event) whether the updated item was a part of the current
1564 // selection in which case the selection must be updated.
1565 selectionProvider.addSelectionChangedListener(new ISelectionChangedListener() {
1567 public void selectionChanged(SelectionChangedEvent event) {
1568 //System.out.println("selection changed: " + event.getSelection());
1569 Set<NodeContext> set = ISelectionUtils.filterSetSelection(event.getSelection(), NodeContext.class);
1570 selectedItems.clear();
1571 for (NodeContext nc : set) {
1572 TreeItem item = contextToItem.getRight(nc);
1574 selectedItems.put(item, nc);
1576 //System.out.println("newly selected items: " + selectedItems);
1581 private void resetSelection() {
1582 final ISelection selection = getWidgetSelection();
1583 // System.out.println("resetSelection()");
1584 // System.out.println(" provider selection: " + selectionProvider.getSelection());
1585 // System.out.println(" widget selection: " + selection);
1586 selectionProvider.setAndFireNonEqualSelection(selection);
1589 protected void setDefaultProcessors() {
1590 // Add a simple IMAGER query processor that always returns null.
1591 // With this processor no images will ever be shown.
1592 // setPrimitiveProcessor(new StaticImagerProcessor(null));
1594 setProcessor(new DefaultComparableChildrenProcessor());
1595 setProcessor(new DefaultLabelDecoratorsProcessor());
1596 setProcessor(new DefaultImageDecoratorsProcessor());
1597 setProcessor(new DefaultSelectedLabelerProcessor());
1598 setProcessor(new DefaultLabelerFactoriesProcessor());
1599 setProcessor(new DefaultSelectedImagerProcessor());
1600 setProcessor(new DefaultImagerFactoriesProcessor());
1601 setPrimitiveProcessor(new DefaultLabelerProcessor());
1602 setPrimitiveProcessor(new DefaultCheckedStateProcessor());
1603 setPrimitiveProcessor(new DefaultImagerProcessor());
1604 setPrimitiveProcessor(new DefaultLabelDecoratorProcessor());
1605 setPrimitiveProcessor(new DefaultImageDecoratorProcessor());
1606 setPrimitiveProcessor(new NoSelectionRequestProcessor());
1608 setProcessor(new DefaultFinalChildrenProcessor(this));
1610 setProcessor(new DefaultPrunedChildrenProcessor());
1611 setProcessor(new DefaultSelectedViewpointProcessor());
1612 setProcessor(new DefaultSelectedLabelDecoratorFactoriesProcessor());
1613 setProcessor(new DefaultSelectedImageDecoratorFactoriesProcessor());
1614 setProcessor(new DefaultViewpointContributionsProcessor());
1616 setPrimitiveProcessor(new DefaultViewpointProcessor());
1617 setPrimitiveProcessor(new DefaultViewpointContributionProcessor());
1618 setPrimitiveProcessor(new DefaultSelectedViewpointFactoryProcessor());
1619 setPrimitiveProcessor(new DefaultIsExpandedProcessor());
1620 setPrimitiveProcessor(new DefaultShowMaxChildrenProcessor());
1624 public <T> void setProcessor(NodeQueryProcessor<T> processor) {
1625 assertNotDisposed();
1626 if (processor == null)
1627 throw new IllegalArgumentException("null processor");
1629 processors.put(processor.getIdentifier(), processor);
1633 public <T> void setPrimitiveProcessor(PrimitiveQueryProcessor<T> processor) {
1634 assertNotDisposed();
1635 if (processor == null)
1636 throw new IllegalArgumentException("null processor");
1638 PrimitiveQueryProcessor<?> oldProcessor = primitiveProcessors.put(processor.getIdentifier(), processor);
1640 if (oldProcessor instanceof ProcessorLifecycle)
1641 ((ProcessorLifecycle) oldProcessor).detached(this);
1642 if (processor instanceof ProcessorLifecycle)
1643 ((ProcessorLifecycle) processor).attached(this);
1647 public <T> void setDataSource(DataSource<T> provider) {
1648 assertNotDisposed();
1649 if (provider == null)
1650 throw new IllegalArgumentException("null provider");
1651 dataSources.put(provider.getProvidedClass(), provider);
1654 @SuppressWarnings("unchecked")
1656 public <T> DataSource<T> removeDataSource(Class<T> forProvidedClass) {
1657 assertNotDisposed();
1658 if (forProvidedClass == null)
1659 throw new IllegalArgumentException("null class");
1660 return dataSources.remove(forProvidedClass);
1664 public void setPersistor(StatePersistor persistor) {
1665 this.persistor = persistor;
1669 public SelectionDataResolver getSelectionDataResolver() {
1670 return selectionDataResolver;
1674 public void setSelectionDataResolver(SelectionDataResolver r) {
1675 this.selectionDataResolver = r;
1679 public SelectionFilter getSelectionFilter() {
1680 return selectionFilter;
1684 public void setSelectionFilter(SelectionFilter f) {
1685 this.selectionFilter = f;
1686 // TODO: re-filter current selection?
1690 public void setSelectionTransformation(BiFunction<GraphExplorer, Object[], Object[]> f) {
1691 this.selectionTransformation = f;
1695 public <T> void addListener(T listener) {
1696 if(listener instanceof FocusListener) {
1697 focusListeners.add((FocusListener)listener);
1698 } else if(listener instanceof MouseListener) {
1699 mouseListeners.add((MouseListener)listener);
1700 } else if(listener instanceof KeyListener) {
1701 keyListeners.add((KeyListener)listener);
1706 public <T> void removeListener(T listener) {
1707 if(listener instanceof FocusListener) {
1708 focusListeners.remove(listener);
1709 } else if(listener instanceof MouseListener) {
1710 mouseListeners.remove(listener);
1711 } else if(listener instanceof KeyListener) {
1712 keyListeners.remove(listener);
1716 public void addSelectionListener(SelectionListener listener) {
1717 tree.addSelectionListener(listener);
1720 public void removeSelectionListener(SelectionListener listener) {
1721 tree.removeSelectionListener(listener);
1724 private Set<String> uiContexts;
1727 public void setUIContexts(Set<String> contexts) {
1728 this.uiContexts = contexts;
1732 public void setRoot(final Object root) {
1733 if(uiContexts != null && uiContexts.size() == 1)
1734 setRootContext0(NodeContextBuilder.buildWithData(BuiltinKeys.INPUT, root, BuiltinKeys.UI_CONTEXT, uiContexts.iterator().next()));
1736 setRootContext0(NodeContextBuilder.buildWithData(BuiltinKeys.INPUT, root));
1740 public void setRootContext(final NodeContext context) {
1741 setRootContext0(context);
1744 private void setRootContext0(final NodeContext context) {
1745 Assert.isNotNull(context, "root must not be null");
1746 if (isDisposed() || tree.isDisposed())
1748 Display display = tree.getDisplay();
1749 if (display.getThread() == Thread.currentThread()) {
1752 display.asyncExec(new Runnable() {
1761 private void initializeState() {
1762 if (persistor == null)
1764 ExplorerStates.scheduleRead(getRoot(), persistor)
1765 .thenAccept(state -> SWTUtils.asyncExec(tree, () -> restoreState(state)));
1768 private void restoreState(ExplorerState state) {
1769 // topNodeToSet will be processed by #setData when it encounters a
1770 // NodeContext that matches this one.
1771 // topNodePath = state.topNodePath;
1772 // topNodePathChildIndex = state.topNodePathChildIndex;
1773 // currentTopNodePathIndex = 0;
1775 Object processor = getPrimitiveProcessor(BuiltinKeys.IS_EXPANDED);
1776 if (processor instanceof DefaultIsExpandedProcessor) {
1777 DefaultIsExpandedProcessor isExpandedProcessor = (DefaultIsExpandedProcessor)processor;
1778 for(NodeContext expanded : state.expandedNodes) {
1779 isExpandedProcessor.replaceExpanded(expanded, true);
1784 private void saveState() {
1785 if (persistor == null)
1788 NodeContext[] topNodePath = NodeContext.NONE;
1789 int[] topNodePathChildIndex = {};
1790 Collection<NodeContext> expandedNodes = Collections.emptyList();
1791 Map<String, Integer> columnWidths = Collections.<String, Integer> emptyMap();
1793 // Resolve top node path
1794 TreeItem topItem = tree.getTopItem();
1795 if (topItem != null) {
1796 NodeContext topNode = (NodeContext) topItem.getData();
1797 if (topNode != null) {
1798 topNodePath = getNodeContextPathSegments(topNode);
1799 topNodePathChildIndex = new int[topNodePath.length];
1800 for (int i = 0; i < topNodePath.length; ++i) {
1801 // TODO: get child indexes
1802 topNodePathChildIndex[i] = 0;
1807 // Resolve expanded nodes
1808 Object processor = getPrimitiveProcessor(BuiltinKeys.IS_EXPANDED);
1809 if (processor instanceof IsExpandedProcessor) {
1810 IsExpandedProcessor isExpandedProcessor = (IsExpandedProcessor) processor;
1811 expandedNodes = isExpandedProcessor.getExpanded();
1815 TreeColumn[] columns = tree.getColumns();
1816 if (columns.length > 1) {
1817 columnWidths = new HashMap<String, Integer>();
1818 for (int i = 0; i < columns.length; ++i) {
1819 columnWidths.put(columns[i].getText(), columns[i].getWidth());
1823 persistor.serialize(
1824 ExplorerStates.explorerStateLocation(),
1826 new ExplorerState(topNodePath, topNodePathChildIndex, expandedNodes, columnWidths));
1830 * Invoke only from SWT thread to reset the root of the graph explorer tree.
1834 private void doSetRoot(NodeContext root) {
1835 if (tree.isDisposed())
1837 if (root.getConstant(BuiltinKeys.INPUT) == null) {
1838 ErrorLogger.defaultLogError("root node context does not contain BuiltinKeys.INPUT key. Node = " + root, new Exception("trace"));
1842 // Empty caches, release queries.
1843 GraphExplorerContext oldContext = explorerContext;
1844 GraphExplorerContext newContext = new GraphExplorerContext();
1845 GENodeQueryManager manager = new GENodeQueryManager(newContext, null, null, TreeItemReference.create(null));
1846 this.explorerContext = newContext;
1847 oldContext.safeDispose();
1848 toolTip.setGraphExplorerContext(explorerContext);
1850 // Need to empty these or otherwise they won't be emptied until the
1851 // explorer is disposed which would mean that many unwanted references
1852 // will be held by this map.
1853 clearPrimitiveProcessors();
1855 this.rootContext = root.getConstant(BuiltinKeys.IS_ROOT) != null ? root
1856 : NodeContextUtil.withConstant(root, BuiltinKeys.IS_ROOT, Boolean.TRUE);
1858 explorerContext.getCache().incRef(this.rootContext);
1862 NodeContext[] contexts = manager.query(rootContext, BuiltinKeys.FINAL_CHILDREN);
1864 tree.setItemCount(contexts.length);
1866 select(rootContext);
1867 refreshColumnSizes();
1871 public NodeContext getRoot() {
1876 public NodeContext getParentContext(NodeContext context) {
1878 throw new IllegalStateException("disposed");
1879 if (!thread.currentThreadAccess())
1880 throw new IllegalStateException("not in SWT display thread " + thread.getThread());
1882 TreeItem item = contextToItem.getRight(context);
1883 if(item == null) return null;
1884 TreeItem parentItem = item.getParentItem();
1885 if(parentItem == null) return null;
1886 return (NodeContext)parentItem.getData();
1889 Point previousTreeSize;
1890 Point previousTreeParentSize;
1891 boolean activatedBefore = false;
1894 public void handleEvent(Event event) {
1895 //System.out.println("EVENT: " + event);
1896 switch(event.type) {
1898 //System.out.println("EXPAND: " + event.item);
1899 if ((tree.getStyle() & SWT.VIRTUAL) != 0) {
1900 expandVirtual(event);
1902 System.out.println("TODO: non-virtual tree item expand");
1906 // Only invoked for SWT.VIRTUAL trees
1908 // Happened for Hannu once during program startup.
1909 // java.lang.AssertionError
1910 // at org.simantics.browsing.ui.common.internal.GENodeQueryManager.query(GENodeQueryManager.java:190)
1911 // at org.simantics.browsing.ui.swt.GraphExplorerImpl.setData(GraphExplorerImpl.java:2315)
1912 // at org.simantics.browsing.ui.swt.GraphExplorerImpl.handleEvent(GraphExplorerImpl.java:2039)
1913 // I do not know whether SWT guarantees that SetData events
1914 // don't come after Dispose event has been issued, but I
1915 // think its better to have this check here just incase.
1920 // This ensures that column sizes are refreshed at
1921 // least once when the GE is first shown.
1922 if (!activatedBefore) {
1923 refreshColumnSizes();
1924 activatedBefore = true;
1928 //new Exception().printStackTrace();
1935 if (event.widget == tree) {
1936 // This case is meant for listening to tree width increase.
1937 // The column resizing must be performed only after the tree
1938 // itself as been resized.
1939 Point size = tree.getSize();
1941 if (previousTreeSize != null) {
1942 dx = size.x - previousTreeSize.x;
1944 previousTreeSize = size;
1945 //System.out.println("RESIZE: " + dx + " - size=" + size);
1948 tree.setRedraw(false);
1949 refreshColumnSizes(size);
1950 tree.setRedraw(true);
1952 } else if (event.widget == tree.getParent()) {
1953 // This case is meant for listening to tree width decrease.
1954 // The columns must be resized before the tree widget itself
1955 // is resized to prevent scroll bar flicker. This can be achieved
1956 // by listening to the resize events of the tree parent widget.
1957 Composite parent = tree.getParent();
1958 Point size = parent.getSize();
1960 // We must subtract the parent's border and possible
1961 // scroll bar width from the new target width of the columns.
1962 size.x -= tree.getParent().getBorderWidth() * 2;
1963 ScrollBar vBar = parent.getVerticalBar();
1964 if (vBar != null && vBar.isVisible())
1965 size.x -= vBar.getSize().x;
1968 if (previousTreeParentSize != null) {
1969 dx = size.x - previousTreeParentSize.x;
1971 previousTreeParentSize = size;
1972 //System.out.println("RESIZE: " + dx + " - size=" + size);
1975 tree.setRedraw(false);
1976 refreshColumnSizes(size);
1977 tree.setRedraw(true);
1987 protected void refreshColumnSizes() {
1988 // Composite treeParent = tree.getParent();
1989 // Point size = treeParent.getSize();
1990 // size.x -= treeParent.getBorderWidth() * 2;
1991 Point size = tree.getSize();
1992 refreshColumnSizes(size);
1993 tree.getParent().layout();
1997 * This has been disabled since the logic of handling column widths has been
1998 * externalized to parties creating {@link GraphExplorerImpl} instances.
2000 protected void refreshColumnSizes(Point toSize) {
2002 refreshingColumnSizes = true;
2004 int columnCount = tree.getColumnCount();
2005 if (columnCount > 0) {
2006 Point size = toSize;
2007 int targetWidth = size.x - tree.getBorderWidth() * 2;
2010 // Take the vertical scroll bar existence into to account when
2011 // calculating the overflow column width.
2012 ScrollBar vBar = tree.getVerticalBar();
2013 //if (vBar != null && vBar.isVisible())
2015 targetWidth -= vBar.getSize().x;
2017 List<TreeColumn> resizing = new ArrayList<TreeColumn>();
2019 int resizingWidth = 0;
2020 int totalWeight = 0;
2021 for (int i = 0; i < columnCount - 1; ++i) {
2022 TreeColumn col = tree.getColumn(i);
2023 //System.out.println(" " + col.getText() + ": " + col.getWidth());
2024 int width = col.getWidth();
2026 Column c = (Column) col.getData();
2029 resizingWidth += width;
2030 totalWeight += c.getWeight();
2034 int requiredWidthAdjustment = targetWidth - usedWidth;
2035 if (requiredWidthAdjustment < 0)
2036 requiredWidthAdjustment = Math.min(requiredWidthAdjustment, -resizing.size());
2037 double diff = requiredWidthAdjustment;
2038 //System.out.println("REQUIRED WIDTH ADJUSTMENT: " + requiredWidthAdjustment);
2040 // Decide how much to give space to / take space from each grabbing column
2041 double wrel = 1.0 / resizing.size();
2043 double[] weightedShares = new double[resizing.size()];
2044 for (int i = 0; i < resizing.size(); ++i) {
2045 TreeColumn col = resizing.get(i);
2046 Column c = (Column) col.getData();
2047 if (totalWeight == 0) {
2048 weightedShares[i] = wrel;
2050 weightedShares[i] = (double) c.getWeight() / (double) totalWeight;
2053 //System.out.println("grabbing columns:" + resizing);
2054 //System.out.println("weighted space distribution: " + Arrays.toString(weightedShares));
2056 // Always shrink the columns if necessary, but don't enlarge before
2057 // there is sufficient space to at least give all resizable columns
2059 if (diff < 0 || (diff > 0 && diff > resizing.size())) {
2060 // Need to either shrink or enlarge the resizable columns if possible.
2061 for (int i = 0; i < resizing.size(); ++i) {
2062 TreeColumn col = resizing.get(i);
2063 Column c = (Column) col.getData();
2064 int cw = col.getWidth();
2065 //double wrel = (double) cw / (double) resizingWidth;
2066 //int delta = Math.min((int) Math.round(wrel * diff), requiredWidthAdjustment);
2067 double ddelta = weightedShares[i] * diff;
2070 delta = (int) Math.floor(ddelta);
2072 delta = Math.min((int) Math.floor(ddelta), requiredWidthAdjustment);
2074 //System.out.println("size delta(" + col.getText() + "): " + ddelta + " => " + delta);
2075 //System.out.println("argh(" + col.getText() + "): " + c.getWidth() + " vs. " + col.getWidth() + " vs. " + (cw+delta));
2076 int newWidth = Math.max(c.getWidth(), cw + delta);
2077 requiredWidthAdjustment -= (newWidth - cw);
2078 col.setWidth(newWidth);
2082 //System.out.println("FILLER WIDTH LEFT: " + requiredWidthAdjustment);
2084 TreeColumn last = tree.getColumn(columnCount - 1);
2085 // HACK: see #setColumns for why this is here.
2086 if (FILLER.equals(last.getText())) {
2087 last.setWidth(Math.max(0, requiredWidthAdjustment));
2091 refreshingColumnSizes = false;
2096 private void doDispose() {
2097 explorerContext.dispose();
2099 // No longer necessary, the used executors are shared.
2100 //scheduler.shutdown();
2101 //scheduler2.shutdown();
2104 detachPrimitiveProcessors();
2105 primitiveProcessors.clear();
2106 dataSources.clear();
2108 pendingItems.clear();
2112 contextToItem.clear();
2114 mouseListeners.clear();
2116 selectionProvider.clearListeners();
2117 selectionProvider = null;
2118 selectionDataResolver = null;
2119 selectionRefreshContexts.clear();
2120 selectedItems.clear();
2121 originalFont = null;
2123 localResourceManager.dispose();
2125 // Must shutdown image loader job before disposing its ResourceManager
2126 imageLoaderJob.dispose();
2127 imageLoaderJob.cancel();
2129 imageLoaderJob.join();
2130 } catch (InterruptedException e) {
2131 ErrorLogger.defaultLogError(e);
2133 resourceManager.dispose();
2135 postSelectionProvider.dispose();
2139 private void expandVirtual(final Event event) {
2140 TreeItem item = (TreeItem) event.item;
2141 assert (item != null);
2142 NodeContext context = (NodeContext) item.getData();
2143 assert (context != null);
2145 GENodeQueryManager manager = new GENodeQueryManager(this.explorerContext, null, null, TreeItemReference.create(item));
2146 NodeContext[] children = manager.query(context, BuiltinKeys.FINAL_CHILDREN);
2147 int maxChildren = getMaxChildren(manager, context);
2148 item.setItemCount(children.length < maxChildren ? children.length : maxChildren);
2151 private NodeContext getNodeContext(TreeItem item) {
2152 assert(item != null);
2154 NodeContext context = (NodeContext)item.getData();
2155 assert(context != null);
2160 private NodeContext getParentContext(TreeItem item) {
2161 TreeItem parentItem = item.getParentItem();
2162 if(parentItem != null) {
2163 return getNodeContext(parentItem);
2169 private static final String LISTENER_SET_INDICATOR = "LSI";
2170 private static final String PENDING = "PENDING";
2171 private int contextSelectionChangeModCount = 0;
2174 * Only invoked for SWT.VIRTUAL widgets.
2178 private void setData(final Event event) {
2179 assert (event != null);
2180 TreeItem item = (TreeItem) event.item;
2181 assert (item != null);
2183 // Based on experience it seems to be possible that
2184 // SetData events are sent for disposed TreeItems.
2185 if (item.isDisposed() || item.getData(PENDING) != null)
2188 //System.out.println("GE.SetData " + item);
2190 GENodeQueryManager manager = new GENodeQueryManager(this.explorerContext, null, null, TreeItemReference.create(item.getParentItem()));
2192 NodeContext parentContext = getParentContext(item);
2193 assert (parentContext != null);
2195 NodeContext[] parentChildren = manager.query(parentContext, BuiltinKeys.FINAL_CHILDREN);
2197 // Some children have disappeared since counting
2198 if (event.index < 0) {
2199 ErrorLogger.defaultLogError("GraphExplorer.setData: how can event.index be < 0: " + event.index + " ??", new Exception());
2202 if (event.index >= parentChildren.length)
2205 NodeContext context = parentChildren[event.index];
2206 assert (context != null);
2207 item.setData(context);
2209 // Manage NodeContext -> TreeItem mappings
2210 contextToItem.map(context, item);
2211 if (item.getData(LISTENER_SET_INDICATOR) == null) {
2212 // This "if" exists because setData will get called many
2213 // times for the same (NodeContext, TreeItem) pairs.
2214 // Each TreeItem only needs one listener, but this
2215 // is needed to tell whether it already has a listener
2217 item.setData(LISTENER_SET_INDICATOR, LISTENER_SET_INDICATOR);
2218 item.addListener(SWT.Dispose, itemDisposeListener);
2221 boolean isExpanded = manager.query(context, BuiltinKeys.IS_EXPANDED);
2223 PrunedChildrenResult children = manager.query(context, BuiltinKeys.PRUNED_CHILDREN);
2224 int maxChildren = getMaxChildren(manager, context);
2225 //item.setItemCount(children.getPrunedChildren().length < maxChildren ? children.getPrunedChildren().length : maxChildren);
2227 NodeContext[] pruned = children.getPrunedChildren();
2228 int count = Math.min(pruned.length, maxChildren);
2230 if (isExpanded || item.getItemCount() > 1) {
2231 item.setItemCount(count);
2232 TreeItem[] childItems = item.getItems();
2233 for(int i=0;i<count;i++)
2234 contextToItem.map(pruned[i], childItems[i]);
2236 if (children.getPrunedChildren().length == 0) {
2237 item.setItemCount(0);
2239 // item.setItemCount(1);
2240 item.setItemCount(count);
2241 TreeItem[] childItems = item.getItems();
2242 for(int i=0;i<count;i++)
2243 contextToItem.map(pruned[i], childItems[i]);
2244 // item.getItem(0).setData(PENDING, PENDING);
2245 // item.getItem(0).setItemCount(o);
2249 setTextAndImage(item, manager, context, event.index);
2251 // Check if the node should be auto-expanded?
2252 if ((autoExpandLevel == ALL_LEVELS || autoExpandLevel > 1) && !isExpanded) {
2253 //System.out.println("NOT EXPANDED(" +context + ", " + item + ")");
2254 int level = getTreeItemLevel(item);
2255 if ((autoExpandLevel == ALL_LEVELS || level <= autoExpandLevel)
2256 && !explorerContext.autoExpanded.containsKey(context))
2258 //System.out.println("AUTO-EXPANDING(" + context + ", " + item + ")");
2259 explorerContext.autoExpanded.put(context, Boolean.TRUE);
2260 setExpanded(context, true);
2264 item.setExpanded(isExpanded);
2266 if ((tree.getStyle() & SWT.CHECK) != 0) {
2267 CheckedState checked = manager.query(context, BuiltinKeys.IS_CHECKED);
2268 item.setChecked(CheckedState.CHECKED_STATES.contains(checked));
2269 item.setGrayed(CheckedState.GRAYED == checked);
2272 //System.out.println("GE.SetData completed " + item);
2274 // This test makes sure that selectionProvider holds the correct
2275 // selection with respect to the actual selection stored by the virtual
2277 // The data items shown below the items occupied by the selected and now removed data
2278 // will be squeezed to use the tree items previously used for the now
2279 // removed data. When this happens, the NodeContext items stored by the
2280 // tree items will be different from what the GraphExplorer's
2281 // ISelectionProvider thinks the selection currently is. To compensate,
2282 // 1. Recognize the situation
2283 // 2. ASAP set the selection provider selection to what is actually
2284 // offered by the tree widget.
2285 NodeContext selectedContext = selectedItems.get(item);
2286 // System.out.println("selectedContext(" + item + "): " + selectedContext);
2287 if (selectedContext != null && !selectedContext.equals(context)) {
2288 final int modCount = ++contextSelectionChangeModCount;
2289 // System.out.println("SELECTION MUST BE UPDATED (modCount=" + modCount + "): " + item);
2290 // System.out.println(" old context: " + selectedContext);
2291 // System.out.println(" new context: " + context);
2292 // System.out.println(" provider selection: " + selectionProvider.getSelection());
2293 // System.out.println(" widget selection: " + getWidgetSelection());
2294 ThreadUtils.asyncExec(thread, new Runnable() {
2299 int count = contextSelectionChangeModCount;
2300 // System.out.println("MODCOUNT: " + modCount + " vs. " + count);
2301 if (modCount != count)
2308 // This must be done to keep the visible tree selection properly
2309 // in sync with the selectionProvider JFace proxy of this class in
2310 // cases where an in-line editor was previously active for the node
2312 if (selectionRefreshContexts.remove(context)) {
2313 final ISelection currentSelection = selectionProvider.getSelection();
2314 // asyncExec is here to prevent ui glitches that
2315 // seem to occur if the selection setting is done
2316 // directly here in between setData invocations.
2317 ThreadUtils.asyncExec(thread, new Runnable() {
2322 // System.out.println("REFRESHING SELECTION: " + currentSelection);
2323 // System.out.println("BEFORE setSelection: " + Arrays.toString(tree.getSelection()));
2324 // System.out.println("BEFORE setSelection: " + selectionProvider.getSelection());
2325 setSelection(currentSelection, true);
2326 // System.out.println("AFTER setSelection: " + Arrays.toString(tree.getSelection()));
2327 // System.out.println("AFTER setSelection: " + selectionProvider.getSelection());
2332 // TODO: doesn't work if any part of the node path that should be
2333 // revealed is out of view.
2334 // Disabled until a better solution is devised.
2335 // Suggestion: include item indexes into the stored node context path
2336 // to make it possible for this method to know whether the current
2337 // node path segment is currently out of view based on event.index.
2338 // If out of view, this code needs to scroll the view programmatically
2340 // if (currentTopNodePathIndex >= 0 && topNodePath.length > 0) {
2341 // NodeContext topNode = topNodePath[currentTopNodePathIndex];
2342 // if (topNode.equals(context)) {
2343 // final TreeItem topItem = item;
2344 // ++currentTopNodePathIndex;
2345 // if (currentTopNodePathIndex >= topNodePath.length) {
2346 // // Mission accomplished. End search for top node here.
2347 // topNodePath = NodeContext.NONE;
2348 // currentTopNodePathIndex = -1;
2350 // ThreadUtils.asyncExec(thread, new Runnable() {
2352 // public void run() {
2353 // if (isDisposed())
2355 // tree.setTopItem(topItem);
2361 // Check if vertical scroll bar has become visible and refresh layout.
2362 ScrollBar verticalBar = tree.getVerticalBar();
2363 if(verticalBar != null) {
2364 boolean currentlyVerticalBarVisible = verticalBar.isVisible();
2365 if (verticalBarVisible != currentlyVerticalBarVisible) {
2366 verticalBarVisible = currentlyVerticalBarVisible;
2367 Composite parent = tree.getParent();
2375 * @return see {@link GraphExplorer#setAutoExpandLevel(int)} for how the
2376 * return value is calculated. Items without parents have level=2,
2377 * their children level=3, etc. Returns 0 for invalid items
2379 private int getTreeItemLevel(TreeItem item) {
2383 for (TreeItem parent = item; parent != null; parent = parent.getParentItem(), ++level);
2384 //System.out.println("\tgetTreeItemLevel(" + parent + ")");
2385 //System.out.println("level(" + item + "): " + level);
2393 private NodeContext[] getNodeContextPathSegments(NodeContext node) {
2394 TreeItem item = contextToItem.getRight(node);
2396 return NodeContext.NONE;
2397 int level = getTreeItemLevel(item);
2399 return NodeContext.NONE;
2400 // Exclude root from the saved node path.
2402 NodeContext[] segments = new NodeContext[level];
2403 for (TreeItem parent = item; parent != null; parent = parent.getParentItem(), --level) {
2404 NodeContext ctx = (NodeContext) item.getData();
2406 return NodeContext.NONE;
2407 segments[level-1] = ctx;
2416 @SuppressWarnings("unused")
2417 private NodeContextPath getNodeContextPath(NodeContext node) {
2418 NodeContext[] path = getNodeContextPathSegments(node);
2419 return new NodeContextPath(path);
2422 void setImage(NodeContext node, TreeItem item, Imager imager, Collection<ImageDecorator> decorators, int itemIndex) {
2423 Image[] images = columnImageArray;
2424 Arrays.fill(images, null);
2425 if (imager == null) {
2426 item.setImage(images);
2430 Object[] descOrImage = columnDescOrImageArray;
2431 Arrays.fill(descOrImage, null);
2432 boolean finishLoadingInJob = false;
2434 for (Column column : columns) {
2435 String key = column.getKey();
2436 ImageDescriptor desc = imager.getImage(key);
2438 // Attempt to decorate the label
2439 if (!decorators.isEmpty()) {
2440 for (ImageDecorator id : decorators) {
2441 ImageDescriptor ds = id.decorateImage(desc, key, itemIndex);
2447 // Try resolving only cached images here and now
2448 Object img = localResourceManager.find(desc);
2450 img = resourceManager.find(desc);
2452 images[index] = img != null ? (Image) img : null;
2453 descOrImage[index] = img == null ? desc : img;
2454 finishLoadingInJob |= img == null;
2459 // Finish loading the final image in the image loader job if necessary.
2460 if (finishLoadingInJob) {
2461 // Prevent UI from flashing unnecessarily by reusing the old image
2462 // in the item if it exists.
2463 for (int c = 0; c < columns.length; ++c) {
2464 Image img = item.getImage(c);
2468 item.setImage(images);
2470 // Schedule loading to another thread to refrain from blocking
2471 // the UI with database operations.
2472 queueImageTask(item, new ImageTask(
2475 Arrays.copyOf(descOrImage, descOrImage.length)));
2477 // Set any images that were resolved.
2478 item.setImage(images);
2482 private void queueImageTask(TreeItem item, ImageTask task) {
2483 synchronized (imageTasks) {
2484 imageTasks.put(item, task);
2486 imageLoaderJob.scheduleIfNecessary(100);
2490 * Invoked in a job worker thread.
2493 * @see ImageLoaderJob
2496 protected IStatus setPendingImages(IProgressMonitor monitor) {
2497 ImageTask[] tasks = null;
2498 synchronized (imageTasks) {
2499 tasks = imageTasks.values().toArray(new ImageTask[imageTasks.size()]);
2502 if (tasks.length == 0)
2503 return Status.OK_STATUS;
2505 MultiStatus status = null;
2507 // Load missing images
2508 for (ImageTask task : tasks) {
2509 Object[] descs = task.descsOrImages;
2510 for (int i = 0; i < descs.length; ++i) {
2511 Object obj = descs[i];
2512 if (obj instanceof ImageDescriptor) {
2513 ImageDescriptor desc = (ImageDescriptor) obj;
2515 descs[i] = resourceManager.get((ImageDescriptor) desc);
2516 } catch (DeviceResourceException e) {
2518 status = new MultiStatus(Activator.PLUGIN_ID, 0, "Problems loading images:", null);
2519 status.add(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Image descriptor loading failed: " + desc, e));
2525 // Perform final UI updates in the UI thread.
2526 final ImageTask[] _tasks = tasks;
2527 thread.asyncExec(new Runnable() {
2530 if (!tree.isDisposed()) {
2531 tree.setRedraw(false);
2533 tree.setRedraw(true);
2538 return status != null ? status : Status.OK_STATUS;
2542 * Invoked in the UI thread only.
2546 void setImages(ImageTask[] tasks) {
2547 for (ImageTask task : tasks)
2553 * Invoked in the UI thread only.
2557 void setImage(ImageTask task) {
2558 // Be sure not to process disposed items.
2559 if (task.item.isDisposed())
2561 // Discard this task if the TreeItem has switched owning NodeContext.
2562 if (!contextToItem.contains(task.node, task.item))
2565 Object[] descs = task.descsOrImages;
2566 Image[] images = columnImageArray;
2567 Arrays.fill(images, null);
2568 for (int i = 0; i < descs.length; ++i) {
2569 Object desc = descs[i];
2570 if (desc instanceof Image) {
2571 images[i] = (Image) desc;
2574 task.item.setImage(images);
2577 void setText(TreeItem item, Labeler labeler, Collection<LabelDecorator> decorators, int itemIndex) {
2578 if (labeler != null) {
2579 String[] texts = new String[columns.length];
2581 Map<String, String> labels = labeler.getLabels();
2582 Map<String, String> runtimeLabels = labeler.getRuntimeLabels();
2583 for (Column column : columns) {
2584 String key = column.getKey();
2586 if (runtimeLabels != null) s = runtimeLabels.get(key);
2587 if (s == null) s = labels.get(key);
2589 FontDescriptor font = originalFont;
2590 ColorDescriptor bg = originalBackground;
2591 ColorDescriptor fg = originalForeground;
2593 // Attempt to decorate the label
2594 if (!decorators.isEmpty()) {
2595 for (LabelDecorator ld : decorators) {
2596 String ds = ld.decorateLabel(s, key, itemIndex);
2600 FontDescriptor dfont = ld.decorateFont(font, key, itemIndex);
2604 ColorDescriptor dbg = ld.decorateBackground(bg, key, itemIndex);
2608 ColorDescriptor dfg = ld.decorateForeground(fg, key, itemIndex);
2614 if (font != originalFont) {
2615 //System.out.println("set font: " + index + ": " + font);
2616 item.setFont(index, (Font) localResourceManager.get(font));
2618 if (bg != originalBackground)
2619 item.setBackground(index, (Color) localResourceManager.get(bg));
2620 if (fg != originalForeground)
2621 item.setForeground(index, (Color) localResourceManager.get(fg));
2627 item.setText(texts);
2629 item.setText(Labeler.NO_LABEL);
2633 void setTextAndImage(TreeItem item, NodeQueryManager manager, NodeContext context, int itemIndex) {
2634 Labeler labeler = manager.query(context, BuiltinKeys.SELECTED_LABELER);
2635 if (labeler != null) {
2636 labeler.setListener(labelListener);
2638 Imager imager = manager.query(context, BuiltinKeys.SELECTED_IMAGER);
2639 Collection<LabelDecorator> labelDecorators = manager.query(context, BuiltinKeys.LABEL_DECORATORS);
2640 Collection<ImageDecorator> imageDecorators = manager.query(context, BuiltinKeys.IMAGE_DECORATORS);
2642 setText(item, labeler, labelDecorators, itemIndex);
2643 setImage(context, item, imager, imageDecorators, itemIndex);
2647 public void setFocus() {
2652 public <T> T query(NodeContext context, CacheKey<T> key) {
2653 return this.explorerContext.cache.get(context, key);
2657 public boolean isDisposed() {
2661 protected void assertNotDisposed() {
2663 throw new IllegalStateException("disposed");
2670 * @param forceControlUpdate
2673 public void setSelection(final ISelection selection, boolean forceControlUpdate) {
2674 assertNotDisposed();
2675 boolean equalsOld = selectionProvider.selectionEquals(selection);
2676 if (equalsOld && !forceControlUpdate) {
2677 // Just set the selection object instance, fire no events nor update
2678 // the viewer selection.
2679 selectionProvider.setSelection(selection);
2681 // Schedule viewer and selection update if necessary.
2682 if (tree.isDisposed())
2684 Display d = tree.getDisplay();
2685 if (d.getThread() == Thread.currentThread()) {
2686 updateSelectionToControl(selection);
2688 d.asyncExec(new Runnable() {
2691 if (tree.isDisposed())
2693 updateSelectionToControl(selection);
2701 /* Contains the best currently found tree item and its priority
2703 private static class SelectionResolutionStatus {
2704 int bestPriority = Integer.MAX_VALUE;
2712 private void updateSelectionToControl(ISelection selection) {
2713 if (selectionDataResolver == null)
2715 if (!(selection instanceof IStructuredSelection))
2718 // Initialize selection resolution status map
2719 IStructuredSelection iss = (IStructuredSelection) selection;
2720 final THashMap<Object,SelectionResolutionStatus> statusMap =
2721 new THashMap<Object,SelectionResolutionStatus>(iss.size());
2722 for(Iterator<?> it = iss.iterator(); it.hasNext();) {
2723 Object selectionElement = it.next();
2724 Object resolvedElement = selectionDataResolver.resolve(selectionElement);
2727 new SelectionResolutionStatus());
2730 // Iterate all tree items and try to match them to the selection
2731 iterateTreeItems(new TObjectProcedure<TreeItem>() {
2733 public boolean execute(TreeItem treeItem) {
2734 NodeContext nodeContext = (NodeContext)treeItem.getData();
2735 if(nodeContext == null)
2737 SelectionResolutionStatus status = statusMap.get(nodeContext);
2738 if(status != null) {
2739 status.bestPriority = 0; // best possible match
2740 status.bestItem = treeItem;
2744 Object input = nodeContext.getConstant(BuiltinKeys.INPUT);
2745 status = statusMap.get(input);
2746 if(status != null) {
2747 NodeType nodeType = nodeContext.getConstant(NodeType.TYPE);
2748 int curPriority = nodeType instanceof EntityNodeType
2749 ? 1 // Prefer EntityNodeType matches to other node types
2751 if(curPriority < status.bestPriority) {
2752 status.bestPriority = curPriority;
2753 status.bestItem = treeItem;
2761 ArrayList<TreeItem> items = new ArrayList<TreeItem>(statusMap.size());
2762 for(SelectionResolutionStatus status : statusMap.values())
2763 if(status.bestItem != null)
2764 items.add(status.bestItem);
2765 select(items.toArray(new TreeItem[items.size()]));
2771 public ISelection getWidgetSelection() {
2772 TreeItem[] items = tree.getSelection();
2773 if (items.length == 0)
2774 return StructuredSelection.EMPTY;
2776 List<NodeContext> nodes = new ArrayList<NodeContext>(items.length);
2778 // Caches for resolving node contexts the hard way if necessary.
2779 GENodeQueryManager manager = null;
2780 NodeContext lastParentContext = null;
2781 NodeContext[] lastChildren = null;
2783 for (int i = 0; i < items.length; i++) {
2784 TreeItem item = items[i];
2785 NodeContext ctx = (NodeContext) item.getData();
2786 // It may happen due to the virtual nature of the tree control
2787 // that it contains TreeItems which have not yet been ran through
2792 TreeItem parentItem = item.getParentItem();
2793 NodeContext parentContext = parentItem != null ? getNodeContext(parentItem) : rootContext;
2794 if (parentContext != null) {
2795 NodeContext[] children = lastChildren;
2796 if (parentContext != lastParentContext) {
2797 if (manager == null)
2798 manager = new GENodeQueryManager(this.explorerContext, null, null, null);
2799 lastChildren = children = manager.query(parentContext, BuiltinKeys.FINAL_CHILDREN);
2800 lastParentContext = parentContext;
2802 int index = parentItem != null ? parentItem.indexOf(item) : tree.indexOf(item);
2803 if (index >= 0 && index < children.length) {
2804 NodeContext child = children[index];
2805 if (child != null) {
2807 // Cache NodeContext in TreeItem for faster access
2808 item.setData(child);
2814 //System.out.println("widget selection " + items.length + " items / " + nodes.size() + " node contexts");
2815 ISelection selection = constructSelection(nodes.toArray(NodeContext.NONE));
2820 public TransientExplorerState getTransientState() {
2821 if (!thread.currentThreadAccess())
2822 throw new AssertionError(getClass().getSimpleName() + ".getActiveColumn called from non SWT-thread: " + Thread.currentThread());
2823 return transientState;
2830 private void select(TreeItem item) {
2831 tree.setSelection(item);
2832 tree.showSelection();
2833 selectionProvider.setAndFireNonEqualSelection(constructSelection((NodeContext) item.getData()));
2840 private void select(TreeItem[] items) {
2841 //System.out.println("Select: " + Arrays.toString(items));
2842 tree.setSelection(items);
2843 tree.showSelection();
2844 NodeContext[] data = new NodeContext[items.length];
2845 for (int i = 0; i < data.length; i++) {
2846 data[i] = (NodeContext) items[i].getData();
2848 selectionProvider.setAndFireNonEqualSelection(constructSelection(data));
2851 private void iterateTreeItems(TObjectProcedure<TreeItem> procedure) {
2852 for(TreeItem item : tree.getItems())
2853 if(!iterateTreeItems(item, procedure))
2857 private boolean iterateTreeItems(TreeItem item,
2858 TObjectProcedure<TreeItem> procedure) {
2859 if(!procedure.execute(item))
2861 if(item.getExpanded())
2862 for(TreeItem child : item.getItems())
2863 if(!iterateTreeItems(child, procedure))
2873 private boolean trySelect(TreeItem item, Object input) {
2874 NodeContext itemCtx = (NodeContext) item.getData();
2875 if (itemCtx != null) {
2876 if (input.equals(itemCtx.getConstant(BuiltinKeys.INPUT))) {
2881 if (item.getExpanded()) {
2882 for (TreeItem child : item.getItems()) {
2883 if (trySelect(child, input))
2890 private boolean equalsEnough(NodeContext c1, NodeContext c2) {
2892 Object input1 = c1.getConstant(BuiltinKeys.INPUT);
2893 Object input2 = c2.getConstant(BuiltinKeys.INPUT);
2894 if(!ObjectUtils.objectEquals(input1, input2))
2897 Object type1 = c1.getConstant(NodeType.TYPE);
2898 Object type2 = c2.getConstant(NodeType.TYPE);
2899 if(!ObjectUtils.objectEquals(type1, type2))
2906 private NodeContext tryFind(NodeContext context) {
2907 for (TreeItem item : tree.getItems()) {
2908 NodeContext found = tryFind(item, context);
2909 if(found != null) return found;
2914 private NodeContext tryFind(TreeItem item, NodeContext context) {
2915 NodeContext itemCtx = (NodeContext) item.getData();
2916 if (itemCtx != null) {
2917 if (equalsEnough(context, itemCtx)) {
2921 if (item.getExpanded()) {
2922 for (TreeItem child : item.getItems()) {
2923 NodeContext found = tryFind(child, context);
2924 if(found != null) return found;
2931 public boolean select(NodeContext context) {
2933 assertNotDisposed();
2935 if (context == null || context.equals(rootContext)) {
2937 selectionProvider.setAndFireNonEqualSelection(TreeSelection.EMPTY);
2941 // if (context.equals(rootContext)) {
2942 // tree.deselectAll();
2943 // selectionProvider.setAndFireNonEqualSelection(constructSelection(context));
2947 Object input = context.getConstant(BuiltinKeys.INPUT);
2949 for (TreeItem item : tree.getItems()) {
2950 if (trySelect(item, input))
2958 private NodeContext tryFind2(NodeContext context) {
2959 Set<NodeContext> ctxs = contextToItem.getLeftSet();
2960 for(NodeContext c : ctxs)
2961 if(equalsEnough(c, context))
2966 private boolean waitVisible(NodeContext parent, NodeContext context) {
2967 long start = System.nanoTime();
2969 TreeItem parentItem = contextToItem.getRight(parent);
2971 if(parentItem == null)
2975 NodeContext target = tryFind2(context);
2976 if(target != null) {
2977 TreeItem item = contextToItem.getRight(target);
2978 if (!(item.getParentItem().equals(parentItem)))
2980 tree.setTopItem(item);
2984 Display.getCurrent().readAndDispatch();
2985 long duration = System.nanoTime() - start;
2991 private boolean selectPathInternal(NodeContext[] contexts, int position) {
2992 //System.out.println("NodeContext path : " + contexts);
2994 NodeContext head = tryFind(contexts[position]);
2996 if(position == contexts.length-1) {
2997 return select(head);
3001 //setExpanded(head, true);
3003 if(!waitVisible(head, contexts[position+1]))
3006 setExpanded(head, true);
3008 return selectPathInternal(contexts, position+1);
3013 public boolean selectPath(Collection<NodeContext> contexts) {
3015 if(contexts == null) throw new IllegalArgumentException("Null list is not allowed");
3016 if(contexts.isEmpty()) throw new IllegalArgumentException("Empty list is not allowed");
3018 return selectPathInternal(contexts.toArray(new NodeContext[contexts.size()]), 0);
3023 public boolean isVisible(NodeContext context) {
3025 for (TreeItem item : tree.getItems()) {
3026 NodeContext found = tryFind(item, context);
3035 protected ISelection constructSelection(NodeContext... contexts) {
3036 if (contexts == null)
3037 throw new IllegalArgumentException("null contexts");
3038 if (contexts.length == 0)
3039 return StructuredSelection.EMPTY;
3040 if (selectionFilter == null)
3041 return new StructuredSelection(transformSelection(contexts));
3042 return new StructuredSelection( transformSelection(filter(selectionFilter, contexts)) );
3045 protected Object[] transformSelection(Object[] objects) {
3046 return selectionTransformation.apply(this, objects);
3049 protected static Object[] filter(SelectionFilter filter, NodeContext[] contexts) {
3050 int len = contexts.length;
3051 Object[] objects = new Object[len];
3052 for (int i = 0; i < len; ++i)
3053 objects[i] = filter.filter(contexts[i]);
3058 public void setExpanded(final NodeContext context, final boolean expanded) {
3059 assertNotDisposed();
3060 ThreadUtils.asyncExec(thread, new Runnable() {
3064 doSetExpanded(context, expanded);
3069 private void doSetExpanded(NodeContext context, boolean expanded) {
3070 //System.out.println("doSetExpanded(" + context + ", " + expanded + ")");
3071 TreeItem item = contextToItem.getRight(context);
3073 item.setExpanded(expanded);
3075 PrimitiveQueryProcessor<?> pqp = explorerContext.getPrimitiveProcessor(BuiltinKeys.IS_EXPANDED);
3076 if (pqp instanceof IsExpandedProcessor) {
3077 IsExpandedProcessor iep = (IsExpandedProcessor) pqp;
3078 iep.replaceExpanded(context, expanded);
3083 public void setColumnsVisible(boolean visible) {
3084 columnsAreVisible = visible;
3085 if(tree != null) tree.setHeaderVisible(columnsAreVisible);
3089 public void setColumns(final Column[] columns) {
3090 setColumns(columns, null);
3094 public void setColumns(final Column[] columns, Consumer<Map<Column, Object>> callback) {
3095 assertNotDisposed();
3096 checkUniqueColumnKeys(columns);
3098 Display d = tree.getDisplay();
3099 if (d.getThread() == Thread.currentThread())
3100 doSetColumns(columns, callback);
3103 if (tree.isDisposed())
3105 doSetColumns(columns, callback);
3109 private void checkUniqueColumnKeys(Column[] cols) {
3110 Set<String> usedColumnKeys = new HashSet<String>();
3111 List<Column> duplicateColumns = new ArrayList<Column>();
3112 for (Column c : cols) {
3113 if (!usedColumnKeys.add(c.getKey()))
3114 duplicateColumns.add(c);
3116 if (!duplicateColumns.isEmpty()) {
3117 throw new IllegalArgumentException("All columns do not have unique keys: " + cols + ", overlapping: " + duplicateColumns);
3122 * Only meant to be invoked from the SWT UI thread.
3126 private void doSetColumns(Column[] cols, Consumer<Map<Column, Object>> callback) {
3127 // Attempt to keep previous column widths.
3128 Map<String, Integer> prevWidths = new HashMap<>();
3129 for (TreeColumn column : tree.getColumns()) {
3130 Column c = (Column) column.getData();
3132 prevWidths.put(c.getKey(), column.getWidth());
3137 HashMap<String, Integer> keyToIndex = new HashMap<>();
3138 for (int i = 0; i < cols.length; ++i) {
3139 keyToIndex.put(cols[i].getKey(), i);
3142 this.columns = Arrays.copyOf(cols, cols.length);
3143 //this.columns[cols.length] = FILLER_COLUMN;
3144 this.columnKeyToIndex = keyToIndex;
3145 this.columnImageArray = new Image[cols.length];
3146 this.columnDescOrImageArray = new Object[cols.length];
3148 Map<Column, Object> map = new HashMap<>();
3150 tree.setHeaderVisible(columnsAreVisible);
3151 for (Column column : columns) {
3152 TreeColumn c = new TreeColumn(tree, toSWT(column.getAlignment()));
3155 c.setText(column.getLabel());
3156 c.setToolTipText(column.getTooltip());
3158 int cw = column.getWidth();
3160 // Try to keep previous widths
3161 Integer w = prevWidths.get(column.getKey());
3164 else if (cw != Column.DEFAULT_CONTROL_WIDTH)
3167 // Go for some kind of default settings then...
3168 if (ColumnKeys.PROPERTY.equals(column.getKey()))
3174 // if (!column.hasGrab() && !FILLER.equals(column.getKey())) {
3175 // c.addListener(SWT.Resize, resizeListener);
3176 // c.setResizable(true);
3178 // //c.setResizable(false);
3183 if(callback != null) callback.accept(map);
3185 // Make sure the explorer fits the columns properly after initialization.
3186 SWTUtils.asyncExec(tree, () -> {
3187 if (!tree.isDisposed())
3188 refreshColumnSizes();
3192 int toSWT(Align alignment) {
3193 switch (alignment) {
3194 case LEFT: return SWT.LEFT;
3195 case CENTER: return SWT.CENTER;
3196 case RIGHT: return SWT.RIGHT;
3197 default: throw new Error("unhandled alignment: " + alignment);
3202 public Column[] getColumns() {
3203 return Arrays.copyOf(columns, columns.length);
3206 private void detachPrimitiveProcessors() {
3207 for (PrimitiveQueryProcessor<?> p : primitiveProcessors.values()) {
3208 if (p instanceof ProcessorLifecycle) {
3209 ((ProcessorLifecycle) p).detached(this);
3214 private void clearPrimitiveProcessors() {
3215 for (PrimitiveQueryProcessor<?> p : primitiveProcessors.values()) {
3216 if (p instanceof ProcessorLifecycle) {
3217 ((ProcessorLifecycle) p).clear();
3222 Listener resizeListener = new Listener() {
3224 public void handleEvent(Event event) {
3225 // Prevent infinite recursion.
3226 if (refreshingColumnSizes)
3228 //TreeColumn column = (TreeColumn) event.widget;
3229 //Column c = (Column) column.getData();
3230 refreshColumnSizes();
3234 Listener itemDisposeListener = new Listener() {
3236 public void handleEvent(Event event) {
3237 if (event.type == SWT.Dispose) {
3238 if (event.widget instanceof TreeItem) {
3239 TreeItem ti = (TreeItem) event.widget;
3240 //NodeContext ctx = (NodeContext) ti.getData();
3241 // System.out.println("DISPOSE CONTEXT TO ITEM: " + ctx + " -> " + System.identityHashCode(ti));
3242 // System.out.println(" map size BEFORE: " + contextToItem.size());
3243 @SuppressWarnings("unused")
3244 NodeContext removed = contextToItem.removeWithRight(ti);
3245 // System.out.println(" REMOVED: " + removed);
3246 // System.out.println(" map size AFTER: " + contextToItem.size());
3255 LabelerListener labelListener = new LabelerListener() {
3257 public boolean columnModified(final NodeContext context, final String key, final String newLabel) {
3258 //System.out.println("column " + key + " modified for " + context + " to " + newLabel);
3259 if (tree.isDisposed())
3262 synchronized (labelRefreshRunnables) {
3263 Runnable refresher = new Runnable() {
3266 // Tree is guaranteed to be non-disposed if this is invoked.
3268 // contextToItem should be accessed only in the SWT thread to keep things thread-safe.
3269 final TreeItem item = contextToItem.getRight(context);
3270 if (item == null || item.isDisposed())
3273 final Integer index = columnKeyToIndex.get(key);
3277 //System.out.println(" found index: " + index);
3278 //System.out.println(" found item: " + item);
3280 GENodeQueryManager manager = new GENodeQueryManager(explorerContext, null, null, null);
3282 // FIXME: indexOf is quadratic
3284 TreeItem parentItem = item.getParentItem();
3285 if (parentItem == null) {
3286 itemIndex = tree.indexOf(item);
3287 //tree.clear(parentIndex, false);
3289 itemIndex = parentItem.indexOf(item);
3290 //item.clear(parentIndex, false);
3292 setTextAndImage(item, manager, context, itemIndex);
3293 } catch (SWTException e) {
3294 ErrorLogger.defaultLogError(e);
3298 //System.out.println(System.currentTimeMillis() + " queueing label refresher: " + refresher);
3299 labelRefreshRunnables.put(context, refresher);
3301 if (!refreshIsQueued) {
3302 refreshIsQueued = true;
3304 long now = System.currentTimeMillis();
3305 long elapsed = now - lastLabelRefreshScheduled;
3306 if (elapsed < DEFAULT_CONSECUTIVE_LABEL_REFRESH_DELAY)
3307 delay = DEFAULT_CONSECUTIVE_LABEL_REFRESH_DELAY - elapsed;
3308 //System.out.println("scheduling with delay: " + delay + " (" + lastLabelRefreshScheduled + " -> " + now + " = " + elapsed + ")");
3310 ThreadUtils.getNonBlockingWorkExecutor().schedule(new Runnable() {
3313 scheduleImmediateLabelRefresh();
3315 }, delay, TimeUnit.MILLISECONDS);
3317 scheduleImmediateLabelRefresh();
3319 lastLabelRefreshScheduled = now;
3326 public boolean columnsModified(final NodeContext context, final Map<String, String> columns) {
3327 System.out.println("TODO: implement GraphExplorerImpl.labelListener.columnsModified");
3332 private void scheduleImmediateLabelRefresh() {
3333 Runnable[] runnables = null;
3334 synchronized (labelRefreshRunnables) {
3335 if (labelRefreshRunnables.isEmpty())
3338 runnables = labelRefreshRunnables.values().toArray(new Runnable[labelRefreshRunnables.size()]);
3339 labelRefreshRunnables.clear();
3340 refreshIsQueued = false;
3342 final Runnable[] rs = runnables;
3344 if (tree.isDisposed())
3346 tree.getDisplay().asyncExec(new Runnable() {
3349 if (tree.isDisposed())
3351 //System.out.println(System.currentTimeMillis() + " EXECUTING " + rs.length + " label refresh runnables");
3352 tree.setRedraw(false);
3353 for (Runnable r : rs) {
3356 tree.setRedraw(true);
3361 long lastLabelRefreshScheduled = 0;
3362 boolean refreshIsQueued = false;
3363 Map<NodeContext, Runnable> labelRefreshRunnables = new HashMap<NodeContext, Runnable>();
3365 @SuppressWarnings("unchecked")
3367 public <T> T getAdapter(Class<T> adapter) {
3368 if(ISelectionProvider.class == adapter) return (T) postSelectionProvider;
3369 else if(IPostSelectionProvider.class == adapter) return (T) postSelectionProvider;
3373 @SuppressWarnings("unchecked")
3375 public <T> T getControl() {
3380 * @see org.simantics.browsing.ui.GraphExplorer#setAutoExpandLevel(int)
3383 public void setAutoExpandLevel(int level) {
3384 this.autoExpandLevel = level;
3388 public <T> NodeQueryProcessor<T> getProcessor(QueryKey<T> key) {
3389 return explorerContext.getProcessor(key);
3393 public <T> PrimitiveQueryProcessor<T> getPrimitiveProcessor(PrimitiveQueryKey<T> key) {
3394 return explorerContext.getPrimitiveProcessor(key);
3398 public boolean isEditable() {
3403 public void setEditable(boolean editable) {
3404 if (!thread.currentThreadAccess())
3405 throw new IllegalStateException("not in SWT display thread " + thread.getThread());
3407 this.editable = editable;
3408 Display display = tree.getDisplay();
3409 tree.setBackground(editable ? null : display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
3413 * For setting a more local service locator for the explorer than the global
3414 * workbench service locator. Sometimes required to give this implementation
3415 * access to local workbench services like IFocusService.
3418 * Must be invoked during right after construction.
3420 * @param serviceLocator
3421 * a specific service locator or <code>null</code> to use the
3422 * workbench global service locator
3424 public void setServiceLocator(IServiceLocator serviceLocator) {
3425 if (serviceLocator == null && PlatformUI.isWorkbenchRunning())
3426 serviceLocator = PlatformUI.getWorkbench();
3427 this.serviceLocator = serviceLocator;
3428 if (serviceLocator != null) {
3429 this.contextService = (IContextService) serviceLocator.getService(IContextService.class);
3430 this.focusService = (IFocusService) serviceLocator.getService(IFocusService.class);
3435 public Object getClicked(Object event) {
3436 MouseEvent e = (MouseEvent)event;
3437 final Tree tree = (Tree) e.getSource();
3438 Point point = new Point(e.x, e.y);
3439 TreeItem item = tree.getItem(point);
3441 // No selectable item at point?
3445 Object data = item.getData();