]> gerrit.simantics Code Review - simantics/sysdyn.git/blob
92a5ac8e2e73be774c7a64c71ee94ca2c5b6c263
[simantics/sysdyn.git] /
1 /*******************************************************************************\r
2  * Copyright (c) 2010 Association for Decentralized Information Management in\r
3  * Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.sysdyn.ui.handlers.exports;\r
13 \r
14 import java.io.File;\r
15 import java.util.HashMap;\r
16 \r
17 import org.eclipse.core.commands.AbstractHandler;\r
18 import org.eclipse.core.commands.ExecutionEvent;\r
19 import org.eclipse.core.commands.ExecutionException;\r
20 import org.eclipse.core.runtime.Platform;\r
21 import org.eclipse.jface.action.IStatusLineManager;\r
22 import org.eclipse.jface.viewers.ISelection;\r
23 import org.eclipse.swt.SWT;\r
24 import org.eclipse.swt.widgets.FileDialog;\r
25 import org.eclipse.swt.widgets.Shell;\r
26 import org.eclipse.ui.handlers.HandlerUtil;\r
27 import org.simantics.databoard.Bindings;\r
28 import org.simantics.db.ReadGraph;\r
29 import org.simantics.db.Resource;\r
30 import org.simantics.db.WriteGraph;\r
31 import org.simantics.db.common.primitiverequest.PossibleRelatedValue;\r
32 import org.simantics.db.common.request.ReadRequest;\r
33 import org.simantics.db.common.request.WriteRequest;\r
34 import org.simantics.db.exception.DatabaseException;\r
35 import org.simantics.db.layer0.adapter.SubgraphExtent.ExtentStatus;\r
36 import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;\r
37 import org.simantics.db.layer0.util.TransferableGraphConfiguration2;\r
38 import org.simantics.db.request.Read;\r
39 import org.simantics.graph.db.TransferableGraphSource;\r
40 import org.simantics.graph.db.TransferableGraphs;\r
41 import org.simantics.layer0.Layer0;\r
42 import org.simantics.sysdyn.SysdynResource;\r
43 import org.simantics.sysdyn.ui.Activator;\r
44 import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
45 import org.simantics.ui.SimanticsUI;\r
46 import org.simantics.ui.utils.ResourceAdaptionUtils;\r
47 import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
48 \r
49 /**\r
50  * Exports a selected model\r
51  * Model determination is based on the very Resource of the model.\r
52  * \r
53  * @author Teemu Lempinen\r
54  * @author Tuomas Miettinen\r
55  *\r
56  */\r
57 public class ExportModelHandler extends AbstractHandler {\r
58 \r
59         protected static IStatusLineManager status;\r
60 \r
61         @Override\r
62         public Object execute(ExecutionEvent event) throws ExecutionException {\r
63 \r
64                 status = WorkbenchUtils.getStatusLine( HandlerUtil.getActiveSite(event) );\r
65         \r
66                 final Resource model = determineModel(event);\r
67         if (model == null)\r
68                 return null;\r
69         \r
70         String selected = getAbsolutePath(model, event, true);\r
71         \r
72         if (selected != null) {\r
73                 createFile(model, selected);\r
74                 setExportStatus(model, selected);\r
75         }\r
76 \r
77         return null;\r
78         }\r
79         \r
80         /**\r
81          * Create the export file.\r
82          * @param model Model which is exported.\r
83          * @param fileName Full name of the file.\r
84          */\r
85         protected void setExportStatus(final Resource model, final String fileName) {\r
86                 try {\r
87                         String modelName = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
88         \r
89                                 @Override\r
90                                 public String perform(ReadGraph graph) throws DatabaseException {\r
91                                         if (!graph.hasStatement(model, Layer0.getInstance(graph).PartOf))\r
92                                                 return null;\r
93                                         Layer0 l0 = Layer0.getInstance(graph);\r
94                                         return graph.syncRequest(new PossibleRelatedValue<String>(model, l0.HasName, Bindings.STRING ));\r
95                                 }\r
96                                 \r
97                         });\r
98         \r
99                         if (modelName != null)\r
100                                 setStatus("Saved model \"" + modelName + "\" to " + fileName);\r
101                 \r
102                 } catch (DatabaseException e) {\r
103                         // TODO Auto-generated catch block\r
104                         e.printStackTrace();\r
105                 }\r
106         }\r
107         \r
108         /**\r
109          * Create the export file.\r
110          * @param model Model which is exported.\r
111          * @param fileName Full name of the file.\r
112          */\r
113         protected void createFile(final Resource model, final String fileName) {\r
114                 \r
115                 // Asynchronously create the file using transferable graph\r
116                 SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
117 \r
118                     @Override\r
119                     public void run(ReadGraph graph) throws DatabaseException {\r
120                         HashMap<Resource, ExtentStatus> map = new HashMap<Resource, ExtentStatus>();\r
121                         \r
122                         Resource relation = graph.getPossibleResource("http://www.simantics.org/Documentation-1.1/createdBy");\r
123                         if(relation != null) {\r
124                             Resource createdBy = graph.getPossibleObject(model, relation);\r
125                             if(createdBy != null)\r
126                                 map.put(createdBy, ExtentStatus.EXCLUDED);\r
127                         }\r
128                         \r
129                         TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, model);\r
130                         conf.preStatus.putAll(map);\r
131                         \r
132                         TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));\r
133                         try {\r
134                             TransferableGraphs.writeTransferableGraph(graph, "sysdynModel", 1, s,new File(fileName));\r
135                         } catch (Exception e) {\r
136                             e.printStackTrace();\r
137                         }\r
138                         }\r
139                 });\r
140         }\r
141         \r
142         /**\r
143          * Get the model Resource based on the event.\r
144          * @param event\r
145          * @return model Resource which the event refers to.\r
146          */\r
147         protected Resource determineModel(ExecutionEvent event) {\r
148                 // Just get the selected model.\r
149             ISelection sel = HandlerUtil.getCurrentSelection(event);\r
150             final Resource model = ResourceAdaptionUtils.toSingleResource(sel);\r
151             return model;\r
152         }\r
153         \r
154         /**\r
155          * Get the absolute save path for the export file and save it to the database.\r
156          * @param model Model Resource which is exported.\r
157          * @param event\r
158          * @param saveAs true if save as... functionality is used; otherwise save \r
159          * functionality is used. \r
160          * @return The full path name of the exported model.\r
161          * @throws ExecutionException\r
162          */\r
163         protected String getAbsolutePath(final Resource model, ExecutionEvent event, boolean saveAs) throws ExecutionException {\r
164 \r
165                 // Determine the default path.\r
166                 String path = null;\r
167                 try {\r
168                         //If the model has been exported earlier, use that path.\r
169                         path = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
170 \r
171                                 @Override\r
172                                 public String perform(ReadGraph graph) throws DatabaseException {\r
173                                         if (!graph.hasStatement(model, Layer0.getInstance(graph).PartOf))\r
174                                                 return null;\r
175                                         SysdynResource SR = SysdynResource.getInstance(graph);\r
176                                         String path = graph.syncRequest(new PossibleRelatedValue<String>(model, SR.SysdynModel_lastExportFilePath, Bindings.STRING ));\r
177                                         return path;\r
178                                         \r
179                                 }\r
180                                 \r
181                         });\r
182                 } catch (DatabaseException e1) {\r
183                         e1.printStackTrace();\r
184                 }\r
185                 // If this is the initial save:\r
186                 if (path == null) {\r
187                         if (saveAs == false) {\r
188                                 // Save == Save as... when there has been no earlier save. \r
189                                 return getAbsolutePath(model, event, true);\r
190                         }\r
191                         // Use import default path.\r
192                         path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODELTPATH);\r
193                 }\r
194                 if(path.isEmpty() || !(new File(path).exists()))\r
195                         path = Platform.getLocation().toOSString();\r
196                                 \r
197         // Determine the default name\r
198                 // FIXME: Model browser doesn't change its selection even if the selected object is removed,\r
199         // so you can try to export a removed model \r
200                 String name = null;\r
201                 try {\r
202                         name = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
203 \r
204                                 @Override\r
205                                 public String perform(ReadGraph graph) throws DatabaseException {\r
206                                         if (!graph.hasStatement(model, Layer0.getInstance(graph).PartOf))\r
207                                                 return null;\r
208                                         Layer0 l0 = Layer0.getInstance(graph);\r
209                                         SysdynResource SR = SysdynResource.getInstance(graph);\r
210                                         // If the model has been exported earlier, use that name.\r
211                                         // When mere Save has progressed here, there is always be the name in the database.  \r
212                                         String name = graph.syncRequest(new PossibleRelatedValue<String>(model, SR.SysdynModel_lastExportFileName, Bindings.STRING ));\r
213                                         if (name == null) {\r
214                                                 // If not, use the model name.\r
215                                                 name = graph.syncRequest(new PossibleRelatedValue<String>(model, l0.HasName, Bindings.STRING ));\r
216                                         }\r
217                                         return name;\r
218                                         \r
219                                 }\r
220                                 \r
221                         });\r
222                 } catch (DatabaseException e1) {\r
223                         e1.printStackTrace();\r
224                 }\r
225                 // Do not export if the resource has no name\r
226                 if(name == null) return null;\r
227                 \r
228                 final String selected;\r
229                 String fullPath = null;\r
230                 if (saveAs == true) {\r
231                 // Find a location (and name) for the exported library using FileDialog\r
232                         Shell shell = HandlerUtil.getActiveShellChecked(event);\r
233                         FileDialog fd = new FileDialog(shell, SWT.SAVE);\r
234                         fd.setText("Export Model");\r
235                         fd.setFileName(name);\r
236                         \r
237                         fd.setFilterPath(path);\r
238                         String[] filterExt = {"*.sysdyn"};\r
239                         fd.setFilterExtensions(filterExt);\r
240                         fd.setOverwrite(true);\r
241                         fullPath = fd.open();\r
242                 }\r
243                 else {\r
244                         // Save to the earlier location. \r
245                         fullPath = path;\r
246                         if (path.charAt(path.length() - 1) != '\\')\r
247                                 fullPath += "\\"; // Saving to C:\ would otherwise add excess backslashes.\r
248                         fullPath += name;\r
249                 }\r
250                 selected = fullPath;\r
251                 \r
252                 if(selected == null) return null;\r
253 \r
254                 // Save location to preference store\r
255                 try {\r
256                         SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
257 \r
258                                 @Override\r
259                                 public void perform(WriteGraph graph) throws DatabaseException {\r
260                                         Layer0 l0 = Layer0.getInstance(graph);\r
261                                         SysdynResource SR = SysdynResource.getInstance(graph);\r
262                                         graph.deny(model, SR.SysdynModel_lastExportFilePath);\r
263                                         graph.deny(model, SR.SysdynModel_lastExportFileName);\r
264                                         graph.addLiteral(model, SR.SysdynModel_lastExportFilePath, SR.SysdynModel_lastExportFilePath_Inverse, l0.String, new File(selected).getParent(), Bindings.STRING);\r
265                                         graph.addLiteral(model, SR.SysdynModel_lastExportFileName, SR.SysdynModel_lastExportFilePath_Inverse, l0.String, new File(selected).getName(), Bindings.STRING); \r
266                                 }\r
267                         });\r
268                 } catch (DatabaseException e1) {\r
269                         e1.printStackTrace();\r
270                 }\r
271                 \r
272                 return selected;\r
273 \r
274         }\r
275         \r
276     protected static void setStatus(final String message) {\r
277         if (status != null)\r
278             status.setMessage(message);\r
279     }\r
280 \r
281 }\r