]> gerrit.simantics Code Review - simantics/sysdyn.git/blob
b20206c43b08102b72e9f0aa61576ed3b37101c3
[simantics/sysdyn.git] /
1 /*******************************************************************************\r
2  * Copyright (c) 2007, 2011 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.imports;\r
13 \r
14 import java.io.File;\r
15 import java.io.IOException;\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.viewers.ISelection;\r
22 import org.eclipse.swt.SWT;\r
23 import org.eclipse.swt.widgets.FileDialog;\r
24 import org.eclipse.swt.widgets.MessageBox;\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.databoard.Files;\r
29 import org.simantics.databoard.binding.error.RuntimeBindingConstructionException;\r
30 import org.simantics.db.ReadGraph;\r
31 import org.simantics.db.Resource;\r
32 import org.simantics.db.WriteGraph;\r
33 import org.simantics.db.WriteOnlyGraph;\r
34 import org.simantics.db.common.request.WriteRequest;\r
35 import org.simantics.db.common.utils.NameUtils;\r
36 import org.simantics.db.exception.DatabaseException;\r
37 import org.simantics.db.exception.ResourceNotFoundException;\r
38 import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
39 import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;\r
40 import org.simantics.db.request.Read;\r
41 import org.simantics.graph.representation.Root;\r
42 import org.simantics.graph.representation.TransferableGraph1;\r
43 import org.simantics.layer0.Layer0;\r
44 import org.simantics.layer0.utils.direct.GraphUtils;\r
45 import org.simantics.sysdyn.SysdynResource;\r
46 import org.simantics.sysdyn.manager.FunctionUtils;\r
47 import org.simantics.sysdyn.ui.Activator;\r
48 import org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder;\r
49 import org.simantics.ui.SimanticsUI;\r
50 import org.simantics.ui.utils.AdaptionUtils;\r
51 import org.simantics.ui.utils.ResourceAdaptionUtils;\r
52 \r
53 /**\r
54  * Imports an exported function library (or shared function library) transferable graph. \r
55  * @author Teemu Lempinen\r
56  *\r
57  */\r
58 public class ImportFunctionLibrary  extends AbstractHandler {\r
59         \r
60         public static String IMPORTFUNCTIONLIBRARYPATH = "IMPORT_FUNCTION_LIBRARY_PATH";\r
61 \r
62         /**\r
63          * Called from a functions folder node\r
64          */\r
65         @Override\r
66         public Object execute(ExecutionEvent event) throws ExecutionException {\r
67         ISelection sel = HandlerUtil.getCurrentSelection(event);\r
68         Resource r = ResourceAdaptionUtils.toSingleResource(sel);\r
69         if(r == null) {\r
70                 FunctionsFolder mn = AdaptionUtils.adaptToSingle(sel, FunctionsFolder.class);\r
71                 r = mn.data;\r
72         }\r
73         if(r == null) return null;\r
74         \r
75         final Resource functionLibrary = r;\r
76         \r
77         \r
78         // Get a transferable graph file\r
79                 final Shell shell = HandlerUtil.getActiveShellChecked(event);\r
80                 FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
81                 fd.setText("Import Function Library");\r
82                 \r
83                 String path = Activator.getDefault().getPreferenceStore().getString(IMPORTFUNCTIONLIBRARYPATH);\r
84                 if(path.isEmpty() || !(new File(path).exists()))\r
85                         path = Platform.getLocation().toOSString();\r
86                 fd.setFilterPath(path);\r
87                 String[] filterExt = {"*.tg"};\r
88                 fd.setFilterExtensions(filterExt);\r
89                 String selected = fd.open();\r
90                 if(selected == null) return null;\r
91 \r
92                 Activator.getDefault().getPreferenceStore().setValue(IMPORTFUNCTIONLIBRARYPATH, (new File(selected)).getParent());\r
93                 \r
94                 // Load the transferable graph\r
95                 TransferableGraph1 tg = null;\r
96                 try {\r
97                         tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));\r
98                 } catch (RuntimeBindingConstructionException e) {\r
99                         e.printStackTrace();\r
100                         return null;\r
101                 } catch (IOException e) {\r
102                         MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ERROR);\r
103                         mb.setText("Error");\r
104                         mb.setMessage("The imported file is not of type: Function Library");\r
105                         mb.open();\r
106                         return null;\r
107                 } \r
108                 if(tg == null) return null;\r
109 \r
110                 // Make sure the "http://SharedOntologies resource exists\r
111                 try {\r
112                         Boolean hasSharedOntologies;\r
113                         hasSharedOntologies = SimanticsUI.getSession().syncRequest(new Read<Boolean>() {\r
114 \r
115                                 @Override\r
116                                 public Boolean perform(ReadGraph graph) throws DatabaseException {\r
117                                         try {\r
118                                                 graph.getResource("http://SharedOntologies");\r
119                                         } catch (ResourceNotFoundException e) {\r
120                                                 return false;\r
121                                         }               \r
122                                         return true;\r
123                                 }\r
124                         });\r
125 \r
126                         if(!hasSharedOntologies) {\r
127                                 SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
128 \r
129                                         @Override\r
130                                         public void perform(WriteGraph graph) throws DatabaseException {\r
131                                                 Layer0 l0 = Layer0.getInstance(graph);\r
132                                                 GraphUtils.create2(graph, l0.Library, \r
133                                                                 l0.HasName, "SharedOntologies",\r
134                                                                 l0.PartOf, graph.getResource("http:/"));\r
135                                         }\r
136                                 });\r
137 \r
138                         }\r
139                 } catch (DatabaseException e) {\r
140                         e.printStackTrace();\r
141                         return null;\r
142                 }\r
143 \r
144                 \r
145                 // Import a function library from the transferable graph\r
146                 SysdynFunctionLibraryImportAdvisor ia = new SysdynFunctionLibraryImportAdvisor(functionLibrary);\r
147                 try {\r
148                         DefaultPasteHandler.defaultExecute(tg, functionLibrary, ia);\r
149                 } catch (Exception e) {\r
150                         e.printStackTrace();\r
151                 }\r
152                 \r
153                 final Resource root = ia.getRoot(); // Root of the library\r
154                 \r
155                 // Link the imported library to the selected resource (functionLibrary)\r
156                 SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
157                         \r
158                     /**\r
159                      * Link the imported library to the selected resource (functionLibrary)\r
160                      * The imported library can be either SysdynModelicaFunctionLibrary or SysdynFunctionOntology\r
161                      */\r
162                         @Override\r
163                         public void perform(WriteGraph graph) throws DatabaseException {\r
164                             Layer0 l0 = Layer0.getInstance(graph);\r
165                             // Case: SharedFunctionOntology. Link to SharedOntologies\r
166                             if(graph.isInstanceOf(root, SysdynResource.getInstance(graph).SharedFunctionOntology)) {\r
167                                 Resource library = graph.getResource("http://SharedOntologies");\r
168                                 if(!graph.hasStatement(library, l0.ConsistsOf, root)) {\r
169                                     graph.claim(library, l0.ConsistsOf, root);\r
170                                 }\r
171 \r
172                                 // Link model to the shared library\r
173                                 SysdynResource sr = SysdynResource.getInstance(graph);\r
174                                 Resource model = functionLibrary;\r
175                                 while(!graph.isInstanceOf(model, sr.SysdynModel) && graph.isInstanceOf(model, l0.Ontology))\r
176                                     model = graph.getSingleObject(model, l0.PartOf);\r
177                                 if(graph.isInstanceOf(model, sr.SysdynModel)) {\r
178                                     graph.claim(model, l0.IsLinkedTo, l0.IsLinkedTo_Inverse, root);\r
179                                 }\r
180 \r
181                                 // Case: not SharedFunctionOntology or SysdynModelicaFunctionLibrary. \r
182                             } else if(!graph.isInstanceOf(root, SysdynResource.getInstance(graph).SysdynModelicaFunctionLibrary)) {\r
183                                         Resource instanceOf = graph.getPossibleObject(root,l0.InstanceOf);\r
184                                         String type = "...";\r
185                                         if(instanceOf != null)\r
186                                                 type = NameUtils.getSafeName(graph, instanceOf);\r
187                                         else {\r
188                                                 Resource inheritedFrom = graph.getPossibleObject(root, l0.Inherits);\r
189                                                 if(inheritedFrom != null)\r
190                                                         type = NameUtils.getSafeName(graph, inheritedFrom);\r
191                                         }\r
192                                         final String ft = type; \r
193                                         \r
194                                         // Remove the functionLibrary ConsistsOf root relation\r
195                                         graph.deny(root, l0.PartOf);\r
196                                         \r
197                                         // Display error message\r
198                                         shell.getDisplay().asyncExec(new Runnable() {\r
199                                                 \r
200                                                 @Override\r
201                                                 public void run() {\r
202                                                         MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ERROR);\r
203                                                         mb.setText("Error");\r
204                                                         mb.setMessage("The imported file is not of type: Function Library (" + ft +")");\r
205                                                         mb.open();                                                              \r
206                                                 }\r
207                                         });\r
208                                 } else {\r
209                                     // imported library is already in the right place. Update function library files.\r
210                                         FunctionUtils.updateFunctionFileForLibrary(graph, functionLibrary);\r
211                                 }\r
212 \r
213                         }\r
214                 });\r
215                 return null;\r
216         }\r
217         \r
218         /**\r
219          * Import advisor for importing function libraries to SysDyn\r
220          * \r
221          * @author Teemu Lempinen\r
222          *\r
223          */\r
224         private class SysdynFunctionLibraryImportAdvisor extends DefaultPasteImportAdvisor {\r
225                 \r
226                 public SysdynFunctionLibraryImportAdvisor(Resource library) {\r
227                         super(library);\r
228                 }\r
229                 \r
230                 @Override\r
231                 public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {\r
232                     // Change the library to http://SharedOntologies, if the imported library is of type SharedFunctionOntology\r
233                         if(root.type.equals(SysdynResource.URIs.SharedFunctionOntology)) {\r
234                                 try {\r
235                                         library = graph.getResource("http://SharedOntologies");\r
236                                 } catch (ResourceNotFoundException e) {\r
237                                         e.printStackTrace();\r
238                                 }\r
239                         }\r
240                 }\r
241                 \r
242                 @Override\r
243                 public Resource createRoot(WriteOnlyGraph graph, Root root) throws DatabaseException {\r
244                         Layer0 l0 = graph.getService(Layer0.class);\r
245                         this.root = graph.newResource();\r
246                         graph.claim(library, l0.ConsistsOf, l0.PartOf, this.root);\r
247                         String name = root.name;\r
248                         String newName = nameMappings.get(name);\r
249                         graph.addLiteral(this.root, l0.HasName, l0.NameOf, l0.String, newName, Bindings.STRING);\r
250                         return this.root;\r
251 \r
252                 }\r
253                         \r
254         }\r
255 \r
256 }\r