]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/actions/e4/ImportSVGPNG.java
Fixed multiple issues causing dangling references to discarded queries
[simantics/platform.git] / bundles / org.simantics.modeling.ui / src / org / simantics / modeling / ui / actions / e4 / ImportSVGPNG.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.modeling.ui.actions.e4;
13
14 import java.awt.geom.Point2D;
15 import java.io.File;
16 import java.io.FileNotFoundException;
17 import java.io.IOException;
18
19 import javax.inject.Named;
20
21 import org.eclipse.e4.core.di.annotations.Execute;
22 import org.eclipse.e4.ui.model.application.ui.basic.MPart;
23 import org.eclipse.e4.ui.services.IServiceConstants;
24 import org.eclipse.swt.widgets.FileDialog;
25 import org.eclipse.swt.widgets.Shell;
26 import org.eclipse.ui.IEditorPart;
27 import org.eclipse.ui.IWorkbenchPart;
28 import org.eclipse.ui.PlatformUI;
29 import org.eclipse.ui.internal.e4.compatibility.CompatibilityEditor;
30 import org.eclipse.ui.part.MultiPageEditorPart;
31 import org.simantics.Simantics;
32 import org.simantics.db.ReadGraph;
33 import org.simantics.db.Resource;
34 import org.simantics.db.WriteGraph;
35 import org.simantics.db.common.ResourceArray;
36 import org.simantics.db.common.request.IndexRoot;
37 import org.simantics.db.common.request.WriteRequest;
38 import org.simantics.db.exception.DatabaseException;
39 import org.simantics.db.request.Read;
40 import org.simantics.diagram.synchronization.IModifiableSynchronizationContext;
41 import org.simantics.diagram.synchronization.SynchronizationHints;
42 import org.simantics.diagram.synchronization.graph.GraphSynchronizationHints;
43 import org.simantics.diagram.synchronization.graph.layer.GraphLayerManager;
44 import org.simantics.g2d.canvas.ICanvasContext;
45 import org.simantics.g2d.diagram.IDiagram;
46 import org.simantics.g2d.participant.MouseUtil;
47 import org.simantics.g2d.participant.MouseUtil.MouseInfo;
48 import org.simantics.modeling.ModelingResources;
49 import org.simantics.scl.commands.Commands;
50 import org.simantics.structural.stubs.StructuralResource2;
51 import org.simantics.ui.workbench.IResourceEditorInput;
52 import org.simantics.ui.workbench.ResourceEditorInput;
53 import org.simantics.utils.FileUtils;
54 import org.simantics.utils.ui.ErrorLogger;
55 import org.simantics.utils.ui.workbench.WorkbenchUtils;
56
57 public class ImportSVGPNG {
58
59     @Execute
60     public void execute(@Named(IServiceConstants.ACTIVE_PART) MPart part) {
61         if (part == null)
62             return;
63         
64         IWorkbenchPart ap;
65         Object possibleEditor = part.getObject();
66         if (possibleEditor != null && possibleEditor instanceof CompatibilityEditor) {
67             CompatibilityEditor editor = (CompatibilityEditor) possibleEditor;
68             ap = editor.getPart();
69         } else {
70             // Fallback for getting active editor part
71             ap = WorkbenchUtils.getActiveWorkbenchPart();
72         }
73         
74         IEditorPart viewer = null;
75         if (ap instanceof MultiPageEditorPart) {
76             MultiPageEditorPart rfe = (MultiPageEditorPart) ap;
77             IResourceEditorInput in = (ResourceEditorInput) rfe.getEditorInput();
78             final ResourceArray ra = in.getResourceArray();
79             ResourceArray symbolEditorInput;
80             try {
81                 symbolEditorInput = Simantics.getSession().syncRequest(new Read<ResourceArray>() {
82                     @Override
83                     public ResourceArray perform(ReadGraph graph) throws DatabaseException {
84                         StructuralResource2 sr = StructuralResource2.getInstance(graph);
85                         ModelingResources mr = ModelingResources.getInstance(graph);
86                         Resource symbol = graph.getPossibleObject(ra.resources[0], mr.ComponentTypeToSymbol);
87                         Resource definedBy = symbol != null ? graph.getPossibleObject(symbol, sr.IsDefinedBy) : null;
88                         ResourceArray result = definedBy != null ? new ResourceArray(definedBy) : ResourceArray.EMPTY;
89                         return result;
90                     }
91                 });
92
93                 IEditorPart[] eps = rfe.findEditors(new ResourceEditorInput("org.simantics.modeling.ui.symbolEditor", symbolEditorInput)); //$NON-NLS-1$
94                 if (eps.length == 0) {
95                     System.out.println("symbol editor part not found from multi page editor part: " + ap); //$NON-NLS-1$
96                     return;
97                 }
98                 viewer = eps[0];
99             } catch (DatabaseException e) {
100                 e.printStackTrace();
101                 return;
102             }
103         } else if (ap instanceof IEditorPart) {
104             viewer = (IEditorPart) ap;
105         }
106         ICanvasContext ctx = (ICanvasContext) viewer.getAdapter(ICanvasContext.class);
107         if (ctx == null) {
108             System.out.println("No canvas context"); //$NON-NLS-1$
109             return;
110         }
111         MouseInfo minfo = ctx.getSingleItem(MouseUtil.class).getMousePressedInfo(0);
112         if(minfo == null) {
113             System.out.println("No mouse info"); //$NON-NLS-1$
114             return;
115         }
116         final Point2D mpos = minfo.canvasPosition;
117         IResourceEditorInput input = (IResourceEditorInput)viewer.getEditorInput();
118         Resource composite = input.getResource();
119
120         IDiagram idiagram = viewer.getAdapter(IDiagram.class);
121
122         addSVG(mpos.getX(), mpos.getY(), composite, idiagram);
123     }
124
125     public static void addSVG(final double mposX, final double mposY, final Resource composite, IDiagram idiagram) {
126
127         Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
128
129         FileDialog dialog = new FileDialog(shell);
130         dialog.setText(Messages.ImportSVGPNG_ChooseImportImage);
131         dialog.setFilterExtensions(new String[] {"*.svg", "*.png"}); //$NON-NLS-1$ //$NON-NLS-2$
132
133         final String filename = dialog.open();
134         if(filename == null)
135             return;
136
137         File file = new File(filename);
138         try {
139             final byte[] data = FileUtils.readFile(file);
140
141             Simantics.getSession().asyncRequest(new WriteRequest() {
142
143                 @Override
144                 public void perform(WriteGraph g) throws DatabaseException {
145                     Object svg = Commands.get(g, "Simantics/Diagram/createSVGElementR") //$NON-NLS-1$
146                             .execute(g, g.syncRequest(new IndexRoot(composite)),
147                                      composite, suffix(filename), data, mposX, mposY);
148
149                     if (svg != null && svg instanceof Resource) {
150                         Resource resource = (Resource) svg;
151                         // 7. Put the element on all the currently active layers if possible.
152                         IModifiableSynchronizationContext context = idiagram.getHint(SynchronizationHints.CONTEXT);
153                         GraphLayerManager glm = context.get(GraphSynchronizationHints.GRAPH_LAYER_MANAGER);
154                         if (glm != null) {
155                             glm.removeFromAllLayers(g, resource);
156                             glm.putElementOnVisibleLayers(idiagram, g, resource);
157                         }
158                     }
159                 }
160
161             });
162         } catch (FileNotFoundException e) {
163             ErrorLogger.defaultLogError(e);
164         } catch (IOException e) {
165             ErrorLogger.defaultLogError(e);
166         }
167
168         return;
169
170     }
171
172     private static String suffix(String fileName) {
173         int len = fileName.length();
174         if(len < 3) return null;
175         else return fileName.substring(len-3,len).toLowerCase();
176     }
177
178 }