931bfdf3d60d073c0b63c271dbda2c163f060c41
[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.db.ReadGraph;
32 import org.simantics.db.Resource;
33 import org.simantics.db.WriteGraph;
34 import org.simantics.db.common.ResourceArray;
35 import org.simantics.db.common.request.IndexRoot;
36 import org.simantics.db.common.request.WriteRequest;
37 import org.simantics.db.exception.DatabaseException;
38 import org.simantics.db.request.Read;
39 import org.simantics.g2d.canvas.ICanvasContext;
40 import org.simantics.g2d.participant.MouseUtil;
41 import org.simantics.g2d.participant.MouseUtil.MouseInfo;
42 import org.simantics.modeling.ModelingResources;
43 import org.simantics.scl.commands.Commands;
44 import org.simantics.structural.stubs.StructuralResource2;
45 import org.simantics.ui.SimanticsUI;
46 import org.simantics.ui.workbench.IResourceEditorInput;
47 import org.simantics.ui.workbench.ResourceEditorInput;
48 import org.simantics.utils.FileUtils;
49 import org.simantics.utils.ui.ErrorLogger;
50 import org.simantics.utils.ui.workbench.WorkbenchUtils;
51
52 public class ImportSVGPNG {
53
54     @Execute
55     public void execute(@Named(IServiceConstants.ACTIVE_PART) MPart part) {
56         if (part == null)
57             return;
58         
59         IWorkbenchPart ap;
60         Object possibleEditor = part.getObject();
61         if (possibleEditor != null && possibleEditor instanceof CompatibilityEditor) {
62             CompatibilityEditor editor = (CompatibilityEditor) possibleEditor;
63             ap = editor.getPart();
64         } else {
65             // Fallback for getting active editor part
66             ap = WorkbenchUtils.getActiveWorkbenchPart();
67         }
68         
69         IEditorPart viewer = null;
70         if (ap instanceof MultiPageEditorPart) {
71             MultiPageEditorPart rfe = (MultiPageEditorPart) ap;
72             IResourceEditorInput in = (ResourceEditorInput) rfe.getEditorInput();
73             final ResourceArray ra = in.getResourceArray();
74             ResourceArray symbolEditorInput;
75             try {
76                 symbolEditorInput = SimanticsUI.getSession().syncRequest(new Read<ResourceArray>() {
77                     @Override
78                     public ResourceArray perform(ReadGraph graph) throws DatabaseException {
79                         StructuralResource2 sr = StructuralResource2.getInstance(graph);
80                         ModelingResources mr = ModelingResources.getInstance(graph);
81                         Resource symbol = graph.getPossibleObject(ra.resources[0], mr.ComponentTypeToSymbol);
82                         Resource definedBy = symbol != null ? graph.getPossibleObject(symbol, sr.IsDefinedBy) : null;
83                         ResourceArray result = definedBy != null ? new ResourceArray(definedBy) : ResourceArray.EMPTY;
84                         return result;
85                     }
86                 });
87
88                 IEditorPart[] eps = rfe.findEditors(new ResourceEditorInput("org.simantics.modeling.ui.symbolEditor", symbolEditorInput));
89                 if (eps.length == 0) {
90                     System.out.println("symbol editor part not found from multi page editor part: " + ap);
91                     return;
92                 }
93                 viewer = eps[0];
94             } catch (DatabaseException e) {
95                 e.printStackTrace();
96                 return;
97             }
98         } else if (ap instanceof IEditorPart) {
99             viewer = (IEditorPart) ap;
100         }
101         ICanvasContext ctx = (ICanvasContext) viewer.getAdapter(ICanvasContext.class);
102         if (ctx == null) {
103             System.out.println("No canvas context");
104             return;
105         }
106         MouseInfo minfo = ctx.getSingleItem(MouseUtil.class).getMousePressedInfo(0);
107         if(minfo == null) {
108             System.out.println("No mouse info");
109             return;
110         }
111         final Point2D mpos = minfo.canvasPosition;
112         IResourceEditorInput input = (IResourceEditorInput)viewer.getEditorInput();
113         Resource composite = input.getResource();
114
115         addSVG(mpos.getX(), mpos.getY(), composite);
116     }
117
118     public static void addSVG(final double mposX, final double mposY, final Resource composite) {
119
120         Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
121
122         FileDialog dialog = new FileDialog(shell);
123         dialog.setText("Choose an image to be imported");
124         dialog.setFilterExtensions(new String[] {"*.svg", "*.png"});
125
126         final String filename = dialog.open();
127         if(filename == null)
128             return;
129
130         File file = new File(filename);
131         try {
132             final byte[] data = FileUtils.readFile(file);
133
134             SimanticsUI.getSession().asyncRequest(new WriteRequest() {
135
136                 @Override
137                 public void perform(WriteGraph g) throws DatabaseException {
138                     Commands.get(g, "Simantics/Diagram/createSVGElement")
139                             .execute(g, g.syncRequest(new IndexRoot(composite)),
140                                      composite, suffix(filename), data, mposX, mposY);
141                 }
142
143             });
144         } catch (FileNotFoundException e) {
145             ErrorLogger.defaultLogError(e);
146         } catch (IOException e) {
147             ErrorLogger.defaultLogError(e);
148         }
149
150         return;
151
152     }
153
154     private static String suffix(String fileName) {
155         int len = fileName.length();
156         if(len < 3) return null;
157         else return fileName.substring(len-3,len).toLowerCase();
158     }
159
160 }