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