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