]> gerrit.simantics Code Review - simantics/sysdyn.git/blob
86f10c2c42b42a1ba3d002bd691ba381f45887d4
[simantics/sysdyn.git] /
1 package org.simantics.sysdyn.ui.wizards.functions;\r
2 \r
3 import java.io.File;\r
4 import java.io.IOException;\r
5 \r
6 import org.eclipse.core.runtime.Path;\r
7 import org.eclipse.jface.layout.GridDataFactory;\r
8 import org.eclipse.jface.layout.PixelConverter;\r
9 import org.eclipse.jface.viewers.ISelection;\r
10 import org.eclipse.jface.viewers.ISelectionProvider;\r
11 import org.eclipse.jface.viewers.IStructuredSelection;\r
12 import org.eclipse.jface.wizard.WizardPage;\r
13 import org.eclipse.swt.SWT;\r
14 import org.eclipse.swt.events.ModifyEvent;\r
15 import org.eclipse.swt.events.ModifyListener;\r
16 import org.eclipse.swt.events.SelectionAdapter;\r
17 import org.eclipse.swt.events.SelectionEvent;\r
18 import org.eclipse.swt.events.SelectionListener;\r
19 import org.eclipse.swt.layout.GridData;\r
20 import org.eclipse.swt.layout.GridLayout;\r
21 import org.eclipse.swt.widgets.Button;\r
22 import org.eclipse.swt.widgets.Composite;\r
23 import org.eclipse.swt.widgets.FileDialog;\r
24 import org.eclipse.swt.widgets.Label;\r
25 import org.eclipse.swt.widgets.Shell;\r
26 import org.eclipse.swt.widgets.Text;\r
27 import org.eclipse.swt.widgets.Tree;\r
28 import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
29 import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
30 import org.simantics.databoard.Bindings;\r
31 import org.simantics.databoard.Files;\r
32 import org.simantics.databoard.binding.error.RuntimeBindingConstructionException;\r
33 import org.simantics.db.ReadGraph;\r
34 import org.simantics.db.Resource;\r
35 import org.simantics.db.WriteGraph;\r
36 import org.simantics.db.WriteOnlyGraph;\r
37 import org.simantics.db.common.request.WriteRequest;\r
38 import org.simantics.db.common.utils.NameUtils;\r
39 import org.simantics.db.exception.DatabaseException;\r
40 import org.simantics.db.exception.ResourceNotFoundException;\r
41 import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
42 import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;\r
43 import org.simantics.db.request.Read;\r
44 import org.simantics.graph.representation.Root;\r
45 import org.simantics.graph.representation.TransferableGraph1;\r
46 import org.simantics.layer0.Layer0;\r
47 import org.simantics.layer0.utils.direct.GraphUtils;\r
48 import org.simantics.sysdyn.SysdynResource;\r
49 import org.simantics.sysdyn.manager.FunctionUtils;\r
50 import org.simantics.ui.SimanticsUI;\r
51 import org.simantics.utils.datastructures.ArrayMap;\r
52 \r
53 public class WizardFunctionsImportPage extends WizardPage{\r
54 \r
55         // dialog store id constants\r
56         private Text filePathField;\r
57 \r
58         // Keep track of the archive that we browsed to last time\r
59         // the wizard was invoked.\r
60         private static String previouslyBrowsedFile = "";\r
61 \r
62         private Button browseDirectoriesButton;\r
63 \r
64         private Shell shell;\r
65 \r
66         //private IStructuredSelection currentSelection;\r
67 \r
68         private Resource selectedModel;\r
69 \r
70         GraphExplorerComposite functionLibraryExplorer;\r
71         \r
72         private String error = "";\r
73         \r
74         private boolean selectionMade = false;\r
75         \r
76         /**\r
77          * Creates a new project creation wizard page.\r
78          * \r
79          */\r
80         public WizardFunctionsImportPage() {\r
81                 this("wizardFunctionsImportPage", null, null); //$NON-NLS-1$\r
82         }\r
83 \r
84         /**\r
85          * Create a new instance of the receiver.\r
86          * \r
87          * @param pageName\r
88          */\r
89         public WizardFunctionsImportPage(String pageName) {\r
90                 this(pageName,null, null);\r
91         }\r
92 \r
93         /**\r
94          * More (many more) parameters.\r
95          * \r
96          * @param pageName\r
97          * @param initialPath\r
98          * @param currentSelection\r
99          * @since 3.5\r
100          */\r
101         public WizardFunctionsImportPage(String pageName,String initialPath,\r
102                         IStructuredSelection currentSelection) {\r
103                 super(pageName);\r
104                 setPageComplete(false);\r
105                 //this.currentSelection = currentSelection;\r
106                 setTitle("Import Function Library");\r
107                 setDescription("Choose the Function Library file and the import location, then press Finish.");\r
108         }\r
109 \r
110         public void createControl(Composite parent) {\r
111 \r
112                 initializeDialogUnits(parent);\r
113 \r
114                 Composite workArea = new Composite(parent, SWT.NONE);\r
115                 setControl(workArea);\r
116 \r
117                 workArea.setLayout(new GridLayout());\r
118                 workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
119                                 | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
120 \r
121                 createProjectsRoot(workArea);\r
122 \r
123                 createTree(workArea);\r
124                 \r
125                 \r
126         }\r
127 \r
128         private void createProjectsRoot(Composite workArea) {\r
129 \r
130                 //set label for field\r
131                 Label title = new Label(workArea, SWT.NONE);\r
132                 title.setText("Select Function Library source:");\r
133 \r
134                 Composite projectGroup = new Composite(workArea, SWT.NONE);\r
135                 GridLayout layout = new GridLayout();\r
136                 layout.numColumns = 2;\r
137                 layout.makeColumnsEqualWidth = false;\r
138                 layout.marginWidth = 0;\r
139 \r
140                 projectGroup.setLayout(layout);\r
141                 projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
142 \r
143                 // module location entry field\r
144                 this.filePathField = new Text(projectGroup, SWT.BORDER);\r
145 \r
146                 GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
147                 directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
148                 filePathField.setLayoutData(directoryPathData);\r
149                 \r
150 \r
151                 filePathField.addModifyListener(new ModifyListener(){\r
152                         @Override\r
153                         public void modifyText(ModifyEvent e) {\r
154                                 previouslyBrowsedFile = filePathField.getText();        \r
155                         }\r
156                 });\r
157                 if (previouslyBrowsedFile != null){\r
158                         filePathField.setText(previouslyBrowsedFile);\r
159                         validatePage();\r
160                 }\r
161 \r
162                 // browse button\r
163                 browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
164                 browseDirectoriesButton.setText("Browse");\r
165                 setButtonLayoutData(browseDirectoriesButton);\r
166 \r
167                 browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
168                         /*\r
169                          * (non-Javadoc)\r
170                          * \r
171                          * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
172                          * elected(org.eclipse.swt.events.SelectionEvent)\r
173                          */\r
174                         public void widgetSelected(SelectionEvent e) {\r
175                                 handleLocationDirectoryButtonPressed();\r
176                         }\r
177                 });\r
178 \r
179         }\r
180 \r
181         private void createTree(Composite workArea){\r
182                 \r
183                 //set label for tree\r
184                 Label title = new Label(workArea, SWT.NONE);\r
185                 title.setText("Select import location:");\r
186 \r
187                 try {\r
188                         Resource input = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
189 \r
190                                 @Override\r
191                                 public Resource perform(ReadGraph graph)\r
192                                                 throws DatabaseException {\r
193                                         Resource model = SimanticsUI.getProject().get();\r
194                                         return model;\r
195                                 }\r
196 \r
197                         });\r
198 \r
199                         functionLibraryExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
200                                         "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);\r
201 \r
202                         functionLibraryExplorer\r
203                         .setBrowseContexts(SysdynResource.URIs.FunctionTree);\r
204 \r
205                         functionLibraryExplorer.finish();\r
206 \r
207                         functionLibraryExplorer.setInput(null, input);\r
208 \r
209                         GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
210                                         functionLibraryExplorer);\r
211                         \r
212                         ((Tree)functionLibraryExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {\r
213                                 \r
214                                 @Override\r
215                                 public void widgetSelected(SelectionEvent e) {\r
216                                         selectionMade = true;\r
217                                         validatePage();\r
218                                 }\r
219                                 @Override\r
220                                 public void widgetDefaultSelected(SelectionEvent e) {\r
221                                         selectionMade = true;\r
222                                         validatePage();\r
223                                 }\r
224                         });\r
225 \r
226                 } catch (DatabaseException e) {\r
227                         e.printStackTrace();\r
228                 }\r
229 \r
230         }\r
231 \r
232         //Set filePathField active\r
233         public void setVisible(boolean visible) {\r
234                 super.setVisible(visible);\r
235                 this.filePathField.setFocus();\r
236         }\r
237 \r
238         //Open dialog for choosing the file\r
239         protected void handleLocationDirectoryButtonPressed() {\r
240 \r
241                 shell = filePathField.getShell();\r
242 \r
243                 FileDialog dialog = new FileDialog(shell, SWT.OPEN);\r
244 \r
245                 String[] ext = {"*.tg"};\r
246                 dialog.setFilterExtensions(ext);\r
247 \r
248                 dialog.setText("Import Function Library");\r
249 \r
250                 String dirName = filePathField.getText().trim();\r
251 \r
252                 File path = new File(dirName);\r
253                 if (path.exists()) {\r
254                         dialog.setFilterPath(new Path(dirName).toOSString());   \r
255                 }\r
256 \r
257                 String selectedFile = dialog.open();\r
258                 if (selectedFile != null) {\r
259                         filePathField.setText(selectedFile);\r
260                         validatePage();\r
261                 }       \r
262         }\r
263 \r
264         //Get selection from the tree\r
265         @SuppressWarnings("unchecked")\r
266         public static <T> T getExplorerResource(GraphExplorerComposite explorer,\r
267                         Class<T> clazz) {\r
268                 \r
269                 if(explorer == null)\r
270                         return null;\r
271                 ISelection selection = ((ISelectionProvider) explorer\r
272                                 .getAdapter(ISelectionProvider.class)).getSelection();\r
273                 if (selection == null)\r
274                         return null;\r
275                 IStructuredSelection iss = (IStructuredSelection) selection;\r
276                 AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();\r
277                 if (inc == null)\r
278                         return null;\r
279                 final T resource = (T) inc.getAdapter(clazz);\r
280 \r
281                 return resource;\r
282         }\r
283 \r
284         //Create project after finish is pressed.\r
285         public boolean createProjects() {\r
286                 \r
287                 selectedModel= getExplorerResource(functionLibraryExplorer, Resource.class);\r
288                 if(selectedModel == null){\r
289                         setErrorMessage("Error when retrieving resource");\r
290                         return false;\r
291                 }\r
292                         \r
293                 String selected = previouslyBrowsedFile;\r
294                 if(selected == null){\r
295                         setErrorMessage("No file selected");\r
296                         return false;\r
297                 }\r
298 \r
299                 TransferableGraph1 tg = null;\r
300                 try {\r
301                         tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));\r
302                 } catch (RuntimeBindingConstructionException e) {\r
303                         e.printStackTrace();\r
304                         return false;\r
305                 } catch (IOException e) {\r
306                         setErrorMessage("The imported file is not of type: Function Library");\r
307                         return false;\r
308                 } \r
309                 if(tg == null){\r
310                         setErrorMessage("The imported file is not of type: Function Library");\r
311                         return false;\r
312                 }\r
313 \r
314 \r
315                 try {\r
316                         Boolean hasSharedOntologies;\r
317                         hasSharedOntologies = SimanticsUI.getSession().syncRequest(new Read<Boolean>() {\r
318 \r
319                                 @Override\r
320                                 public Boolean perform(ReadGraph graph) throws DatabaseException {\r
321                                         try {\r
322                                                 graph.getResource("http://SharedOntologies");\r
323                                         } catch (ResourceNotFoundException e) {\r
324                                                 return false;\r
325                                         }               \r
326                                         return true;\r
327                                 }\r
328                         });\r
329 \r
330                         if(!hasSharedOntologies) {\r
331                                 SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
332 \r
333                                         @Override\r
334                                         public void perform(WriteGraph graph) throws DatabaseException {\r
335                                                 Layer0 l0 = Layer0.getInstance(graph);\r
336                                                 GraphUtils.create2(graph, l0.Library, \r
337                                                                 l0.HasName, "SharedOntologies",\r
338                                                                 l0.PartOf, graph.getResource("http:/"));\r
339                                         }\r
340                                 });\r
341 \r
342                         }\r
343                 } catch (DatabaseException e) {\r
344                         e.printStackTrace();\r
345                         return false;\r
346                 }\r
347 \r
348 \r
349                 SysdynFunctionLibraryImportAdvisor ia = new SysdynFunctionLibraryImportAdvisor(selectedModel);\r
350                 try {\r
351                         DefaultPasteHandler.defaultExecute(tg, selectedModel, ia);\r
352                 } catch (Exception e) {\r
353                         e.printStackTrace();\r
354                 }\r
355 \r
356                 final Resource root = ia.getRoot();\r
357 \r
358                 try {\r
359                         SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
360 \r
361                                 @Override\r
362                                 public void perform(WriteGraph graph) throws DatabaseException {\r
363                                         Layer0 l0 = Layer0.getInstance(graph);\r
364                                         if(graph.isInstanceOf(root, SysdynResource.getInstance(graph).SharedFunctionOntology)) {\r
365                                                 Resource library = graph.getResource("http://SharedOntologies");\r
366                                                 if(!graph.hasStatement(library, l0.ConsistsOf, root)) {\r
367                                                         graph.claim(library, l0.ConsistsOf, root);\r
368                                                 }\r
369 \r
370                                                 SysdynResource sr = SysdynResource.getInstance(graph);\r
371                                                 Resource model = selectedModel;\r
372                                                 while(!graph.isInstanceOf(model, sr.SysdynModel) && graph.isInstanceOf(model, l0.Ontology))\r
373                                                         model = graph.getSingleObject(model, l0.PartOf);\r
374                                                 if(graph.isInstanceOf(model, sr.SysdynModel)) {\r
375                                                         graph.claim(model, l0.IsLinkedTo, l0.IsLinkedTo_Inverse, root);\r
376                                                 }\r
377 \r
378                                         } else if(!graph.isInstanceOf(root, SysdynResource.getInstance(graph).SysdynModelicaFunctionLibrary)) {\r
379                                                 Resource instanceOf = graph.getPossibleObject(root,l0.InstanceOf);\r
380                                                 String type = "...";\r
381                                                 if(instanceOf != null)\r
382                                                         type = NameUtils.getSafeName(graph, instanceOf);\r
383                                                 else {\r
384                                                         Resource inheritedFrom = graph.getPossibleObject(root, l0.Inherits);\r
385                                                         if(inheritedFrom != null)\r
386                                                                 type = NameUtils.getSafeName(graph, inheritedFrom);\r
387                                                 } \r
388                                                 graph.deny(root, l0.PartOf);\r
389                                                 error = type;\r
390                                         } else {\r
391                                                 FunctionUtils.updateFunctionFileForLibrary(graph, selectedModel);\r
392                                         }\r
393 \r
394                                 }\r
395                         });\r
396                 } catch (DatabaseException e) {\r
397                         e.printStackTrace();\r
398                 }\r
399                 if (!error.isEmpty()){\r
400                         setErrorMessage("The imported file is not of type: Function Library (" + error +")");\r
401                         error = "";\r
402                         return false;\r
403                 }\r
404                 return true;\r
405         }\r
406 \r
407         private class SysdynFunctionLibraryImportAdvisor extends DefaultPasteImportAdvisor {\r
408 \r
409                 public SysdynFunctionLibraryImportAdvisor(Resource library) {\r
410                         super(library);\r
411                 }\r
412 \r
413                 @Override\r
414                 public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {\r
415                         if(root.type.equals(SysdynResource.URIs.SharedFunctionOntology)) {\r
416                                 try {\r
417                                         library = graph.getResource("http://SharedOntologies");\r
418                                 } catch (ResourceNotFoundException e) {\r
419                                         e.printStackTrace();\r
420                                 }\r
421                         }\r
422                 }\r
423 \r
424                 @Override\r
425                 public Resource createRoot(WriteOnlyGraph graph, Root root) throws DatabaseException {\r
426                         Layer0 l0 = graph.getService(Layer0.class);\r
427                         this.root = graph.newResource();\r
428                         graph.claim(library, l0.ConsistsOf, l0.PartOf, this.root);\r
429                         String name = root.name;\r
430                         String newName = nameMappings.get(name);\r
431                         graph.addLiteral(this.root, l0.HasName, l0.NameOf, l0.String, newName, Bindings.STRING);\r
432                         return this.root;\r
433 \r
434                 }\r
435 \r
436         }\r
437         void validatePage() {\r
438 \r
439                 if (previouslyBrowsedFile.isEmpty() || selectionMade == false){\r
440                         setPageComplete(false);\r
441                         return;\r
442                 }\r
443                 setErrorMessage(null);\r
444                 setPageComplete(true);\r
445 \r
446         }\r
447 \r
448 }