6609ba24b155d1be1b508a566812274779432819
[simantics/platform.git] / bundles / org.simantics.diagram / src / org / simantics / diagram / ui / WorkbenchSelectionProvider.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.diagram.ui;
13
14 import java.util.ArrayList;
15 import java.util.Collections;
16 import java.util.Optional;
17 import java.util.concurrent.CopyOnWriteArrayList;
18 import java.util.concurrent.TimeUnit;
19
20 import org.eclipse.jface.viewers.IPostSelectionProvider;
21 import org.eclipse.jface.viewers.ISelection;
22 import org.eclipse.jface.viewers.ISelectionChangedListener;
23 import org.eclipse.jface.viewers.SelectionChangedEvent;
24 import org.eclipse.jface.viewers.StructuredSelection;
25 import org.eclipse.ui.IWorkbenchPartSite;
26 import org.simantics.db.exception.DatabaseException;
27 import org.simantics.diagram.elements.AdaptableImmutableProxyElement;
28 import org.simantics.g2d.canvas.ICanvasContext;
29 import org.simantics.g2d.canvas.impl.AbstractCanvasParticipant;
30 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
31 import org.simantics.g2d.canvas.impl.HintReflection.HintListener;
32 import org.simantics.g2d.diagram.participant.ElementJSON;
33 import org.simantics.g2d.diagram.participant.Selection;
34 import org.simantics.g2d.element.ElementHints;
35 import org.simantics.g2d.element.IElement;
36 import org.simantics.ui.selection.WorkbenchSelectionUtils;
37 import org.simantics.utils.datastructures.hints.IHintContext.Key;
38 import org.simantics.utils.datastructures.hints.IHintObservable;
39 import org.simantics.utils.threads.IThreadWorkQueue;
40 import org.simantics.utils.threads.ThreadUtils;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * A canvas participant that listens to the #0 mouse selection and provides it
46  * forward through the {@link IPostSelectionProvider} interface.
47  * 
48  * @author Tuukka Lehtonen
49  */
50 public class WorkbenchSelectionProvider extends AbstractCanvasParticipant implements IPostSelectionProvider, ElementJSON {
51
52     private static final Logger LOGGER = LoggerFactory.getLogger(WorkbenchSelectionProvider.class);
53
54     private static final long                                 POST_SELECTION_DELAY = 300;
55
56     @Dependency protected Selection selection;
57
58     protected IThreadWorkQueue                                swt;
59     protected IWorkbenchPartSite                              site;
60     protected ISelection                                      currentSelection = StructuredSelection.EMPTY;
61     protected CopyOnWriteArrayList<ISelectionChangedListener> listeners        = new CopyOnWriteArrayList<ISelectionChangedListener>();
62     protected CopyOnWriteArrayList<ISelectionChangedListener> postListeners    = new CopyOnWriteArrayList<ISelectionChangedListener>();
63
64     public WorkbenchSelectionProvider(IThreadWorkQueue swt) {
65         this(swt, null);
66     }
67
68     public WorkbenchSelectionProvider(IThreadWorkQueue swt, IWorkbenchPartSite site) {
69         this.swt = swt;
70         this.site = site;
71         if (site != null)
72             site.setSelectionProvider(this);
73     }
74
75     @Override
76     public void addedToContext(ICanvasContext ctx) {
77         super.addedToContext(ctx);
78         if (site != null && site.getSelectionProvider() != this) {
79             swt.asyncExec(new Runnable() {
80                 @Override
81                 public void run() {
82                     if (site.getSelectionProvider() != WorkbenchSelectionProvider.this)
83                         site.setSelectionProvider(WorkbenchSelectionProvider.this);
84                 }
85             });
86         }
87     }
88
89     @Override
90     public void removedFromContext(ICanvasContext ctx) {
91         if (site != null && site.getSelectionProvider() == this) {
92             swt.asyncExec(new Runnable() {
93                 @Override
94                 public void run() {
95                     if (site.getSelectionProvider() == WorkbenchSelectionProvider.this)
96                         site.setSelectionProvider(null);
97                 }
98             });
99         }
100         super.removedFromContext(ctx);
101     }
102     
103     public void fireSelection(Iterable<?> selection) {
104         final ISelection s = constructAdaptableSelection(selection);
105         swt.asyncExec(new Runnable() {
106             @Override
107             public void run() {
108                 currentSelection = s;
109                 fireSelectionChanged(s);
110                 schedulePostSelectionChanged(s);
111             }
112         });
113     }
114
115     @HintListener(Class = Selection.class, Field = "SELECTION0")
116     public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {
117         Iterable<?> selection = (Iterable<?>) newValue;
118         fireSelection(selection);
119     }
120     
121     @HintListener(Class = Selection.class, Field = "SELECTION0")
122     public void hintRemoved(IHintObservable sender, Key key, Object oldValue) {
123         //System.out.println("selection removed: " + oldValue);
124         fireSelection(Collections.emptyList());
125     }
126
127     // Post selection changed scheduling helper.
128     private int modCount = 0;
129
130     protected void schedulePostSelectionChanged(final ISelection s) {
131         final int count = ++modCount;
132         ThreadUtils.getNonBlockingWorkExecutor().schedule(new Runnable() {
133             @Override
134             public void run() {
135                 int newCount = modCount;
136                 if (count != newCount)
137                     return;
138                 if (isRemoved())
139                     return;
140                 swt.asyncExec(new Runnable() {
141                     @Override
142                     public void run() {
143                         if (isRemoved())
144                             return;
145                         firePostSelectionChanged(s);
146                     }
147                 });
148             }
149         }, POST_SELECTION_DELAY, TimeUnit.MILLISECONDS);
150     }
151
152     protected ISelection constructAdaptableSelection(Iterable<?> selection) {
153         ArrayList<Object> objects = new ArrayList<Object>();
154         for (Object o : selection) {
155             if (o instanceof IElement) {
156                 IElement e = (IElement) o;
157                 Object object = e.getHint(ElementHints.KEY_OBJECT);
158                 if (object != null) {
159                     objects.add(new AdaptableImmutableProxyElement(e));
160                 } else {
161                     System.out.println("  discarding element from selection, null object for " + e);
162                 }
163             } else {
164                 System.out.println("  unrecognized selection: " + o.getClass() + ": " + o);
165             }
166         }
167         return new StructuredSelection(objects);
168     }
169
170     void fireSelectionChanged(ISelection selection) {
171         SelectionChangedEvent e = new SelectionChangedEvent(this, selection);
172         for (ISelectionChangedListener l : listeners)
173             l.selectionChanged(e);
174     }
175
176     void firePostSelectionChanged(ISelection selection) {
177         SelectionChangedEvent e = new SelectionChangedEvent(this, selection);
178         for (ISelectionChangedListener l : postListeners)
179             l.selectionChanged(e);
180     }
181
182     @Override
183     public void addPostSelectionChangedListener(ISelectionChangedListener listener) {
184         postListeners.add(listener);
185     }
186
187     @Override
188     public void removePostSelectionChangedListener(ISelectionChangedListener listener) {
189         postListeners.remove(listener);
190     }
191
192     @Override
193     public void addSelectionChangedListener(ISelectionChangedListener listener) {
194         listeners.add(listener);
195     }
196
197     @Override
198     public void removeSelectionChangedListener(ISelectionChangedListener listener) {
199         listeners.remove(listener);
200     }
201
202     @Override
203     public ISelection getSelection() {
204         return currentSelection;
205     }
206
207     @Override
208     public void setSelection(ISelection selection) {
209         System.out.println("WorkbenchSelectionProvider: TODO: set selection: " + selection);
210     }
211
212     @Override
213     public Optional<String> getJSON(IElement element) {
214         ISelection sel = constructAdaptableSelection(Collections.singleton(element));
215         try {
216             return Optional.ofNullable( WorkbenchSelectionUtils.getPossibleJSON(sel) );
217         } catch (DatabaseException e) {
218             LOGGER.error("Unexpected failure while constructing JSON from element " + element, e);
219             return Optional.empty();
220         }
221     }
222
223 }