]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.diagram.svg/src/org/simantics/diagram/svg/export/DiagramToSVG.java
Added mechanism to diagram IFlagType to prevent graph modifications
[simantics/platform.git] / bundles / org.simantics.diagram.svg / src / org / simantics / diagram / svg / export / DiagramToSVG.java
1 package org.simantics.diagram.svg.export;
2
3
4 import java.awt.Point;
5 import java.util.concurrent.Semaphore;
6 import java.util.concurrent.atomic.AtomicReference;
7
8 import org.apache.batik.svggen.SVGGraphics2D;
9 import org.simantics.Simantics;
10 import org.simantics.db.ReadGraph;
11 import org.simantics.db.Resource;
12 import org.simantics.db.common.ResourceArray;
13 import org.simantics.db.common.request.PossibleIndexRoot;
14 import org.simantics.db.common.request.UniqueRead;
15 import org.simantics.db.common.utils.NameUtils;
16 import org.simantics.db.exception.DatabaseException;
17 import org.simantics.db.exception.ValidationException;
18 import org.simantics.db.management.ISessionContext;
19 import org.simantics.db.request.Read;
20 import org.simantics.diagram.elements.DiagramNodeUtil;
21 import org.simantics.diagram.export.ImagePrinter;
22 import org.simantics.diagram.stubs.DiagramResource;
23 import org.simantics.g2d.canvas.Hints;
24 import org.simantics.g2d.canvas.impl.CanvasContext;
25 import org.simantics.g2d.scenegraph.ICanvasSceneGraphProvider;
26 import org.simantics.layer0.Layer0;
27 import org.simantics.modeling.ModelingResources;
28 import org.simantics.structural.stubs.StructuralResource2;
29 import org.simantics.structural2.StructuralVariables;
30 import org.simantics.utils.DataContainer;
31 import org.simantics.utils.datastructures.Pair;
32 import org.simantics.utils.page.MarginUtils.Margins;
33 import org.simantics.utils.threads.IThreadWorkQueue;
34 import org.simantics.utils.threads.ThreadUtils;
35 import org.simantics.utils.threads.WorkerThread;
36
37
38 public class DiagramToSVG {
39         
40         
41         public static String diagramToSVG(Resource diagram) {
42
43                 try {
44                         ImagePrinter.ImageExportPlan exportPlan = new ImagePrinter.ImageExportPlan();
45                         exportPlan.margin = 0.05;
46                         exportPlan.dpi = 96.0;
47                         exportPlan.diagram = diagram;
48                         return render(diagram,exportPlan);
49                 } catch (Exception e) {
50                         e.printStackTrace();
51                         return "<b>error</b> "+ e.getMessage();
52                 }
53  
54                 
55         }
56         
57         public static String diagramToSVG(Resource diagram, int width, int height) {
58
59                 try {
60                         ImagePrinter.ImageExportPlan exportPlan = new ImagePrinter.ImageExportPlan();
61                         exportPlan.margin = 0.05;
62                         exportPlan.size = new Point(width, height);
63                         exportPlan.diagram = diagram;
64                         return render(diagram,exportPlan);
65                 } catch (Exception e) {
66                         e.printStackTrace();
67                         return "<b>error</b> "+ e.getMessage();
68                 }
69  
70                 
71         }
72         
73         public static String diagramToSVG(Resource diagram, double dpi) {
74
75                 try {
76                         ImagePrinter.ImageExportPlan exportPlan = new ImagePrinter.ImageExportPlan();
77                         exportPlan.margin = 0.05;
78                         exportPlan.dpi = dpi;
79                         exportPlan.diagram = diagram;
80                         return render(diagram,exportPlan);
81                 } catch (Exception e) {
82                         e.printStackTrace();
83                         return "<b>error</b> "+ e.getMessage();
84                 }
85  
86                 
87         }
88         
89         public static String diagramToSVG(Resource diagram, ImagePrinter.ImageExportPlan exportPlan, Margins margins, SVGGraphics2D svgGenerator) {
90
91                 try {
92                         return render(diagram,exportPlan,margins,svgGenerator);
93                 } catch (Exception e) {
94                         e.printStackTrace();
95                         return "<b>error</b> "+ e.getMessage();
96                 }
97                 
98         }
99         
100         private static String render(final Resource input, final ImagePrinter.ImageExportPlan exportPlan) throws Exception {
101                 return render(input, exportPlan, null, SVGBuilder.defaultSVGGenerator()); 
102         }
103         
104         private static String render(final Resource input, final ImagePrinter.ImageExportPlan exportPlan, Margins margins, SVGGraphics2D svgExporter) throws Exception {
105                 Resource diagram = Simantics.getSession().syncRequest(new Read<Resource>() {
106                         @Override
107                         public Resource perform(ReadGraph graph) throws DatabaseException {
108                                 DiagramResource DIA = DiagramResource.getInstance(graph);
109                                 if (graph.isInstanceOf(input, DIA.Diagram))
110                                         return input;
111                                 StructuralResource2 SR = StructuralResource2.getInstance(graph);
112                                 ModelingResources MOD = ModelingResources.getInstance(graph);
113                                 Layer0 L0 = Layer0.getInstance(graph);
114                                 if (graph.isInstanceOf(input, SR.Composite)) {
115                                         Resource possibleDiagram = graph.getPossibleObject(input, MOD.CompositeToDiagram);
116                                         if (possibleDiagram != null)
117                                                 return possibleDiagram;
118                                         for (Resource r : graph.getObjects(input, L0.ConsistsOf)) {
119                                                 if (graph.isInstanceOf(r, SR.Composite)) {
120                                                         possibleDiagram = graph.getPossibleObject(input, MOD.CompositeToDiagram);
121                                                         if (possibleDiagram != null)
122                                                                 return possibleDiagram;
123                                                 }
124                                         }
125                                 }
126                                 return null;
127                         }
128                 });
129                 if (diagram == null)
130                         throw new DatabaseException("Input " + input + " cannot be resolved as diagram");
131                 
132                 final WorkerThread thread = new WorkerThread("Diagram Image Painter");
133                 thread.start();
134                 
135         final CanvasContext ctx = new CanvasContext(thread);
136         ctx.getDefaultHintContext().setHint(Hints.KEY_DISABLE_GRAPH_MODIFICATIONS, Boolean.TRUE);
137         final AtomicReference<ICanvasSceneGraphProvider> sgProvider = new AtomicReference<ICanvasSceneGraphProvider>();
138                 final ISessionContext sessionContext = Simantics.getSessionContext();
139                 final DataContainer<String> result = new DataContainer<String>(null);
140                 final DataContainer<Exception> exception = new DataContainer<Exception>(null);
141         try {
142             final Semaphore done = new Semaphore(0);
143             // IMPORTANT: Load diagram in a different thread than the canvas context thread!
144             ThreadUtils.getBlockingWorkExecutor().execute(new Runnable() {
145                 @Override
146                 public void run() {
147                     try {
148                         Pair<Resource, String> modelAndRVI = sessionContext.getSession().syncRequest(new UniqueRead<Pair<Resource, String>>() {
149                             @Override
150                             public Pair<Resource, String> perform(ReadGraph graph) throws DatabaseException {
151                                 return new Pair<Resource, String>( resolveModel(graph, exportPlan.diagram ), resolveRVI(graph, exportPlan.diagram) );
152                             }
153                         });
154
155                         ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(ctx, modelAndRVI.first, exportPlan.diagram, modelAndRVI.second);
156                         sgProvider.set( provider );
157                         
158                         ThreadUtils.asyncExec(thread, new Runnable() {
159                             @Override
160                             public void run() {
161                                 try {
162                                     SVGBuilder chassis = margins != null ?
163                                                 new SVGBuilder(exportPlan.dpi,exportPlan.size,margins) :
164                                                 new SVGBuilder(exportPlan.dpi,exportPlan.size,exportPlan.margin);
165                                     
166                                     result.set(chassis.paint(ctx, svgExporter));
167                                 } catch (Exception e) {
168                                         exception.set(e);
169                                 } finally {
170                                     done.release();
171                                 }
172                             }
173                         });
174                     } catch (DatabaseException e) {
175                         exception.set(e);
176                         done.release();
177                     } catch (Throwable e) {
178                         exception.set(new DatabaseException(e));
179                         done.release();
180                     } finally {
181                         done.release();
182                     }
183                 }
184             });
185
186             done.acquire(2);
187             if (exception.get() != null)
188                 throw exception.get();
189             return result.get();
190         } finally {
191             if (sgProvider.get() != null)
192                 sgProvider.get().dispose();
193             ctx.dispose();
194         }
195         }
196         
197         private static Resource resolveModel(ReadGraph graph, Resource diagram) throws DatabaseException {
198         ModelingResources mod = ModelingResources.getInstance(graph);
199         Resource composite = graph.getSingleObject(diagram, mod.DiagramToComposite);
200         Resource model = graph.syncRequest(new PossibleIndexRoot(composite));
201         if (model == null)
202             throw new ValidationException("no model found for composite " + NameUtils.getSafeName(graph, composite));
203         return model;
204     }
205
206     private static String resolveRVI(ReadGraph graph, Resource diagram) throws DatabaseException {
207         ModelingResources mod = ModelingResources.getInstance(graph);
208         Resource composite = graph.getSingleObject(diagram, mod.DiagramToComposite);
209         final ResourceArray compositePath = StructuralVariables.getCompositeArray(graph, composite);
210         final ResourceArray variablePath = compositePath.removeFromBeginning(1);
211         return StructuralVariables.getRVI(graph, variablePath);
212     }
213
214         public static String renderWithLoader(final Resource input, final ImagePrinter.ImageExportPlan exportPlan,
215                         Margins margins, SVGGraphics2D svgExporter,
216                         IThreadWorkQueue loaderThread,
217                         IThreadWorkQueue painterThread) throws Exception {
218
219                 if(!painterThread.currentThreadAccess()) throw new IllegalStateException("The callable should be called from the contextThread");
220
221                 final CanvasContext ctx = new CanvasContext(loaderThread);
222                 ctx.getDefaultHintContext().setHint(Hints.KEY_DISABLE_GRAPH_MODIFICATIONS, Boolean.TRUE);
223                 final AtomicReference<ICanvasSceneGraphProvider> sgProvider = new AtomicReference<ICanvasSceneGraphProvider>();
224                 final DataContainer<String> result = new DataContainer<String>(null);
225                 final DataContainer<Exception> exception = new DataContainer<Exception>(null);
226
227                 try {
228                         
229                         final ISessionContext sessionContext = Simantics.getSessionContext();
230
231                         Pair<Resource, String> modelAndRVI = sessionContext.getSession().syncRequest(new UniqueRead<Pair<Resource, String>>() {
232                                 @Override
233                                 public Pair<Resource, String> perform(ReadGraph graph) throws DatabaseException {
234                                         return new Pair<Resource, String>( resolveModel(graph, exportPlan.diagram ), resolveRVI(graph, exportPlan.diagram) );
235                                 }
236                         });
237
238                         ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(ctx, modelAndRVI.first, exportPlan.diagram, modelAndRVI.second);
239                         sgProvider.set( provider );
240
241                         final Semaphore done = new Semaphore(0);
242
243                         ThreadUtils.asyncExec(loaderThread, new Runnable() {
244                                 @Override
245                                 public void run() {
246                                         try {
247                                                 SVGBuilder chassis = margins != null ?
248                                                                 new SVGBuilder(exportPlan.dpi,exportPlan.size,margins) :
249                                                                         new SVGBuilder(exportPlan.dpi,exportPlan.size,exportPlan.margin);
250                                                                 result.set(chassis.paint(ctx, svgExporter));
251                                         } catch (DatabaseException e) {
252                                                 exception.set(e);
253                                                 done.release();
254                                         } catch (Throwable e) {
255                                                 exception.set(new DatabaseException(e));
256                                                 done.release();
257                                         } finally {
258                                                 done.release();
259                                         }
260                                 }
261                         });
262
263                         done.acquire();
264
265                 } catch (DatabaseException e) {
266                         exception.set(e);
267                 } catch (Throwable e) {
268                         exception.set(new DatabaseException(e));
269                 } finally {
270
271                         if (sgProvider.get() != null)
272                                 sgProvider.get().dispose();
273                         ctx.dispose();
274
275                 }
276
277                 if(exception.get() != null) 
278                         throw exception.get();
279
280                 return result.get();
281                 
282         }
283         
284 }