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