]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.diagram/src/org/simantics/diagram/synchronization/graph/layer/GraphLayerManager.java
Even more fixes to layers
[simantics/platform.git] / bundles / org.simantics.diagram / src / org / simantics / diagram / synchronization / graph / layer / GraphLayerManager.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.synchronization.graph.layer;
13
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.HashSet;
17 import java.util.Set;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.ConcurrentMap;
20 import java.util.concurrent.atomic.AtomicInteger;
21
22 import org.simantics.databoard.Bindings;
23 import org.simantics.db.AsyncReadGraph;
24 import org.simantics.db.ReadGraph;
25 import org.simantics.db.Resource;
26 import org.simantics.db.WriteGraph;
27 import org.simantics.db.common.procedure.adapter.AsyncProcedureAdapter;
28 import org.simantics.db.common.request.ResourceRead;
29 import org.simantics.db.exception.CancelTransactionException;
30 import org.simantics.db.exception.DatabaseException;
31 import org.simantics.db.exception.ServiceException;
32 import org.simantics.db.layer0.util.RemoverUtil;
33 import org.simantics.db.procedure.AsyncProcedure;
34 import org.simantics.db.procedure.Listener;
35 import org.simantics.diagram.stubs.DiagramResource;
36 import org.simantics.diagram.synchronization.IModificationQueue;
37 import org.simantics.diagram.synchronization.ModificationAdapter;
38 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
39 import org.simantics.g2d.diagram.DiagramHints;
40 import org.simantics.g2d.diagram.IDiagram;
41 import org.simantics.g2d.element.ElementHints;
42 import org.simantics.g2d.element.IElement;
43 import org.simantics.g2d.layers.IEditableLayer;
44 import org.simantics.g2d.layers.IEditableLayer.ILayerListener;
45 import org.simantics.g2d.layers.IEditableLayer.LayerChangeEvent;
46 import org.simantics.g2d.layers.ILayer;
47 import org.simantics.g2d.layers.ILayers;
48 import org.simantics.g2d.layers.ILayersEditor;
49 import org.simantics.g2d.layers.ILayersEditor.ILayersEditorListener;
50 import org.simantics.g2d.layers.SimpleLayers;
51 import org.simantics.layer0.Layer0;
52
53 /**
54  * @author Tuukka Lehtonen
55  */
56 public class GraphLayerManager {
57
58     class LayerListener implements ILayersEditorListener, ILayerListener {
59         @Override
60         public void layerAdded(final ILayer layer) {
61             modificationQueue.offer(new CreateLayer(layer, getDiagramResource()), null);
62             modificationQueue.flush();
63         }
64
65         @Override
66         public void layerRemoved(final ILayer layer) {
67             modificationQueue.offer(new RemoveLayer(layer, getDiagramResource()), null);
68             modificationQueue.flush();
69         }
70
71         @Override
72         public void layerActivated(ILayer layer) {
73             postActivation(layer, true);
74         }
75
76         @Override
77         public void layerDeactivated(ILayer layer) {
78             postActivation(layer, false);
79         }
80
81         @Override
82         public void ignoreFocusChanged(boolean value) {
83             // Ignore, not written to graph.
84         }
85
86         @Override
87         public void ignoreVisibilityChanged(boolean value) {
88             // Ignore, not written to graph.
89         }
90
91         void postActivation(ILayer layer, boolean activated) {
92             modificationQueue.offer(new LayerActivation(layer, activated), null);
93             modificationQueue.flush();
94         }
95
96         @Override
97         public void layerChanged(LayerChangeEvent event) {
98             LayerChange change = null;
99             if (IEditableLayer.PROP_NAME.equals(event.getProperty())) {
100                 String oldName = (String) event.getOldValue();
101                 String newName = (String) event.getNewValue();
102                 synchronized (layers) {
103                     GraphLayer gl = layers.remove(oldName);
104                     if (gl == null)
105                         return;
106                     layers.put(newName, gl.withName(newName));
107                     change = new LayerChange(event, gl);
108                 }
109             }
110             if (change != null) {
111                 modificationQueue.offer(change, null);
112                 modificationQueue.flush();
113             }
114         }
115     }
116
117     public static final boolean       DEBUG_LAYERS  = false;
118
119     IModificationQueue                modificationQueue;
120     Resource                          diagram;
121     Layer0                            l0;
122     DiagramResource                   dia;
123
124     /**
125      * All the layers currently loaded from the diagram.
126      */
127     ConcurrentMap<String, GraphLayer> layers        = new ConcurrentHashMap<String, GraphLayer>();
128
129     SimpleLayers                      layerEditor;
130
131     /**
132      * The listener for ILayersEditor and all IEditableLayer.
133      */
134     LayerListener                     layerListener = new LayerListener();
135
136     boolean disposed = false;
137
138     public GraphLayerManager(ReadGraph graph, IModificationQueue modificationQueue, Resource diagram) {
139         this.modificationQueue = modificationQueue;
140         this.diagram = diagram;
141         this.l0 = Layer0.getInstance(graph);
142         this.dia = DiagramResource.getInstance(graph);
143     }
144
145     public void dispose() {
146         for (ILayer layer : layerEditor.getLayers()) {
147             if (layer instanceof IEditableLayer) {
148                 ((IEditableLayer) layer).removeLayerListener(layerListener);
149             }
150         }
151         layers.clear();
152         disposed = true;
153     }
154
155     Resource getDiagramResource() {
156         return diagram;
157     }
158
159     // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
160     // LAYERS BEGIN
161     // ------------------------------------------------------------------------
162
163     class CreateLayer extends ModificationAdapter {
164         final ILayer   layer;
165
166         final Resource diagram;
167
168         public CreateLayer(ILayer layer, Resource diagram) {
169             super(LOW_PRIORITY);
170             assert layer != null;
171             this.layer = layer;
172             this.diagram = diagram;
173
174             if (layer instanceof IEditableLayer) {
175                 ((IEditableLayer) layer).addLayerListener(layerListener);
176             }
177         }
178
179         @Override
180         public void perform(WriteGraph g) throws Exception {
181             String newName = layer.getName();
182             for (Resource layer : g.getObjects(diagram, dia.HasLayer)) {
183                 String name = g.getRelatedValue(layer, l0.HasName);
184                 if (newName.equals(name)) {
185                     return;
186                 }
187             }
188             
189             IGraphLayerUtil util = g.adapt(DiagramResource.getInstance(g).Layer, IGraphLayerUtil.class);
190             GraphLayer layer = util.createLayer(g, newName, false);
191             g.claim(diagram, dia.HasLayer, layer.getLayer());
192             layers.put(newName, layer);
193         }
194     }
195
196     class RemoveLayer extends ModificationAdapter {
197         final ILayer   layer;
198
199         final Resource diagram;
200
201         public RemoveLayer(ILayer layer, Resource diagram) {
202             super(LOW_PRIORITY);
203             assert layer != null;
204             this.layer = layer;
205             this.diagram = diagram;
206
207             if (layer instanceof IEditableLayer) {
208                 ((IEditableLayer) layer).removeLayerListener(layerListener);
209             }
210         }
211
212         @Override
213         public void perform(WriteGraph g) throws Exception {
214             String removedName = layer.getName();
215             for (Resource l : g.getObjects(diagram, dia.HasLayer)) {
216                 String name = g.getRelatedValue(l, l0.HasName);
217                 if (removedName.equals(name)) {
218                     g.denyStatement(diagram, dia.HasLayer, l);
219                     deleteLayer(g, l);
220                     layers.remove(name);
221                     return;
222                 }
223             }
224         }
225
226         void deleteLayer(WriteGraph g, Resource layer) throws DatabaseException {
227             RemoverUtil.remove(g, layer);
228         }
229     }
230
231     class LayerActivation extends ModificationAdapter {
232         final ILayer  layer;
233
234         final boolean activated;
235
236         public LayerActivation(ILayer layer, boolean activated) {
237             super(LOW_PRIORITY);
238             assert layer != null;
239             this.layer = layer;
240             this.activated = activated;
241         }
242
243         @Override
244         public void perform(WriteGraph g) throws Exception {
245             GraphLayer gl = layers.get(layer.getName());
246             if (gl == null)
247                 throw new CancelTransactionException("Diagram has no matching layer description: " + layer.getName());
248
249             g.claimLiteral(gl.getLayer(), dia.IsActive, Boolean.valueOf(activated));
250         }
251     }
252
253     class LayerChange extends ModificationAdapter {
254         final LayerChangeEvent event;
255
256         final GraphLayer       gl;
257
258         public LayerChange(LayerChangeEvent event, GraphLayer gl) {
259             super(LOW_PRIORITY);
260             assert event != null;
261             assert gl != null;
262             this.event = event;
263             this.gl = gl;
264         }
265
266         @Override
267         public void perform(WriteGraph g) throws Exception {
268 //            Resource name = g.getSingleObject(gl.getLayer(), b.HasName);
269 //            g.claimValue(name, event.getSource().getName());
270             g.claimLiteral(gl.getLayer(), l0.HasName, event.getSource().getName(), Bindings.STRING);
271         }
272     }
273
274     void deleteTag(WriteGraph g, Resource tag) throws DatabaseException {
275         g.deny(tag);
276     }
277
278     Collection<GraphLayer> getActiveLayers(ReadGraph g) throws DatabaseException {
279         Collection<GraphLayer> result = new ArrayList<GraphLayer>();
280         for (GraphLayer gl : layers.values()) {
281             Boolean active = g.getPossibleRelatedValue(gl.getLayer(), dia.IsActive);
282             if (Boolean.TRUE.equals(active)) {
283                 result.add(gl);
284             }
285         }
286         return result;
287     }
288
289     void tagElementWithActiveLayers(WriteGraph g, Resource element) throws DatabaseException {
290         Collection<GraphLayer> activeLayers = getActiveLayers(g);
291         for (GraphLayer activeLayer : activeLayers) {
292             DiagramGraphUtil.tag(g, element, activeLayer.getVisible(), true);
293             DiagramGraphUtil.tag(g, element, activeLayer.getFocusable(), true);
294         }
295     }
296
297     public ILayersEditor loadLayers(IDiagram diagram, ReadGraph g, Resource diagramResource) throws DatabaseException {
298         
299         layerEditor = new SimpleLayers();
300         layerEditor.addLayerEditorListener(layerListener);
301         
302         String[] fixed = diagram.getHint(DiagramHints.KEY_FIXED_LAYERS);
303
304         g.syncRequest(new ResourceRead<LayersSpec>(diagramResource) {
305
306             @Override
307             public LayersSpec perform(ReadGraph g) throws DatabaseException {
308                 Collection<GraphLayer> gls = new ArrayList<>();
309                 for (Resource layer : g.getObjects(resource, dia.HasLayer)) {
310                     IGraphLayerUtil layerUtil = g.adapt(g.getSingleObject(layer, Layer0.getInstance(g).InstanceOf), IGraphLayerUtil.class);
311                     GraphLayer gl = layerUtil.loadLayer(g, layer);
312                     gls.add(gl);
313                 }
314                 return new LayersSpec(gls);
315             }
316             
317         }, new Listener<LayersSpec>() {
318
319             @Override
320             public void execute(LayersSpec layersSpec) {
321                 ConcurrentMap<String, GraphLayer> newLayers = new ConcurrentHashMap<String, GraphLayer>();
322                 Set<ILayer> visibleLayers = new HashSet<>();
323                 Set<ILayer> allLayers = new HashSet<>();
324                 
325                 if (fixed != null) {
326                     for (GraphLayer gl : layersSpec.getGraphLayers()) {
327                         for (String name : fixed) {
328                             if (name.equals(gl.getName())) {
329                                 ILayer l = gl.getILayer();
330                                 newLayers.put(gl.getName(), gl);
331                                 allLayers.add(l);
332                                 visibleLayers.add(l);
333                             }
334                         }  
335                     }
336                     
337                 } else {
338
339                     if (DEBUG_LAYERS)
340                         System.out.println("Loading layers");
341
342                     for (GraphLayer gl : layersSpec.getGraphLayers()) {
343                         ILayer l = gl.getILayer();
344
345                         newLayers.put(gl.getName(), gl);
346
347                         if (DEBUG_LAYERS)
348                             System.out.println("    Loaded " + (gl.isActive() ? "active" : "inactive") + " layer '" + gl.getName() + "'");
349
350                         if (l instanceof IEditableLayer)
351                             ((IEditableLayer) l).addLayerListener(layerListener);
352
353                         allLayers.add(l);
354                         if (gl.isActive())
355                             visibleLayers.add(l);
356                         
357                     }
358                 }
359                 // Show all and focus all by default if there are no layers
360                 
361                 
362                 if (newLayers.isEmpty()) {
363                     layerEditor.setIgnoreVisibilitySettings(true);
364                     layerEditor.setIgnoreFocusSettings(true);
365                 }
366
367                 if (DEBUG_LAYERS)
368                     System.out.println("Loaded " + newLayers.size() + " layers");
369
370                 layerEditor.update(allLayers, visibleLayers);
371                 
372                 layers = newLayers;
373             }
374
375             @Override
376             public void exception(Throwable t) {
377                 t.printStackTrace();
378             }
379
380             @Override
381             public boolean isDisposed() {
382                 return disposed;
383             }
384             
385         });
386
387
388         return layerEditor;
389     }
390
391     public void loadLayersForElement(ReadGraph graph, ILayersEditor layersEditor, IElement e, Resource element)
392     throws DatabaseException {
393         if (DEBUG_LAYERS)
394             System.out.println("Loading layers for element " + element + " - " + e);
395
396         Set<ILayer> visible = null;
397         Set<ILayer> focusable = null;
398
399         for (ILayer l : layersEditor.getLayers()) {
400             GraphLayer gl = layers.get(l.getName());
401             if (gl != null) {
402                 if (graph.hasStatement(element, gl.getVisible(), element)) {
403                     if (visible == null)
404                         visible = new HashSet<ILayer>(4);
405                     visible.add(l);
406                     if (DEBUG_LAYERS)
407                         System.out.println("    Visible on layer '" + gl.getName() + "'");
408                 }
409                 if (graph.hasStatement(element, gl.getFocusable(), element)) {
410                     if (focusable == null)
411                         focusable = new HashSet<ILayer>(4);
412                     focusable.add(l);
413                     if (DEBUG_LAYERS)
414                         System.out.println("    Focusable on layer '" + gl.getName() + "'");
415                 }
416             }
417         }
418
419         if (visible == null)
420             visible = new HashSet<ILayer>(1);
421         if (focusable == null)
422             focusable = new HashSet<ILayer>(1);
423
424         e.setHint(ElementHints.KEY_VISIBLE_LAYERS, visible);
425         e.setHint(ElementHints.KEY_FOCUS_LAYERS, focusable);
426     }
427
428     /**
429      * @param graph
430      * @param layersEditor
431      * @param e
432      * @param element
433      * @param procedure a procedure whose exception method may be called 0 to
434      *        many times depending on how many errors occur during layer loading
435      * @throws DatabaseException
436      */
437     public void loadLayersForElement(AsyncReadGraph graph, ILayers layers2, final IElement e,
438             Resource element, final AsyncProcedure<IElement> callback) {
439         if (DEBUG_LAYERS)
440             System.out.println("Loading layers for element " + element + " - " + e);
441
442         final Set<ILayer> visible = new HashSet<ILayer>(2);
443         final Set<ILayer> focusable = new HashSet<ILayer>(2);
444
445         // NOTE: must not set layer hints into element until the layer sets have
446         // been properly loaded.
447
448         Set<ILayer> allLayers = layers2.getLayers();
449         if (allLayers.isEmpty()) {
450             e.setHint(ElementHints.KEY_VISIBLE_LAYERS, visible);
451             e.setHint(ElementHints.KEY_FOCUS_LAYERS, focusable);
452             callback.execute(graph, e);
453             return;
454         }
455
456         final AtomicInteger ready = new AtomicInteger(allLayers.size() * 2);
457
458         for (final ILayer l : allLayers) {
459             final GraphLayer gl = layers.get(l.getName());
460             if (gl != null) {
461                 graph.forHasStatement(element, gl.getVisible(), element, new AsyncProcedureAdapter<Boolean>() {
462                     @Override
463                     public void execute(AsyncReadGraph graph, Boolean result) {
464                         if (result) {
465                             synchronized (visible) {
466                                 visible.add(l);
467                             }
468                         }
469                         if (DEBUG_LAYERS)
470                             System.out.println("    Visible on layer '" + gl.getName() + "'");
471                         if (ready.decrementAndGet() == 0) {
472                             e.setHint(ElementHints.KEY_VISIBLE_LAYERS, visible);
473                             e.setHint(ElementHints.KEY_FOCUS_LAYERS, focusable);
474                             callback.execute(graph, e);
475                         }
476                     }
477                     @Override
478                     public void exception(AsyncReadGraph graph, Throwable t) {
479                         callback.exception(graph, t);
480                     }
481                 });
482                 graph.forHasStatement(element, gl.getFocusable(), element, new AsyncProcedureAdapter<Boolean>() {
483                     @Override
484                     public void execute(AsyncReadGraph graph, Boolean result) {
485                         if (result) {
486                             synchronized (focusable) {
487                                 focusable.add(l);
488                             }
489                         }
490                         if (DEBUG_LAYERS)
491                             System.out.println("    Focusable on layer '" + gl.getName() + "'");
492                         if (ready.decrementAndGet() == 0) {
493                             e.setHint(ElementHints.KEY_VISIBLE_LAYERS, visible);
494                             e.setHint(ElementHints.KEY_FOCUS_LAYERS, focusable);
495                             callback.execute(graph, e);
496                         }
497                     }
498                     @Override
499                     public void exception(AsyncReadGraph graph, Throwable t) {
500                         callback.exception(graph, t);
501                     }
502                 });
503
504             } else {
505
506                 if (ready.addAndGet(-2) == 0) {
507                     e.setHint(ElementHints.KEY_VISIBLE_LAYERS, visible);
508                     e.setHint(ElementHints.KEY_FOCUS_LAYERS, focusable);
509                     callback.execute(graph, e);
510                 }
511
512             }
513         }
514     }
515
516     public void putElementOnVisibleLayers(IDiagram diagram, WriteGraph g, Resource element) throws DatabaseException {
517         // Make the new element visible and focusable on all currently
518         // active layers.
519         ILayers diagramLayers = diagram.getHint(DiagramHints.KEY_LAYERS);
520         if (diagramLayers != null) {
521             Set<ILayer> visibleLayers = diagramLayers.getVisibleLayers();
522
523             if (DEBUG_LAYERS)
524                 System.out.println("Marking element visible and focusable in the graph on visible layers: "
525                         + visibleLayers);
526
527             for (ILayer layer : visibleLayers) {
528                 GraphLayer gl = layers.get(layer.getName());
529                 if (gl != null) {
530                     gl.forEachTag(tag -> DiagramGraphUtil.tag(g, element, tag, true));
531                 }
532             }
533         }
534     }
535
536     public void removeFromAllLayers(WriteGraph graph, Resource element) throws ServiceException {
537         // Remove element from all layers.
538         graph.deny(element, dia.IsVisible);
539         graph.deny(element, dia.IsFocusable);
540     }
541
542     public GraphLayer getGraphLayer(String name) {
543         return layers.get(name);
544     }
545
546 }