]> gerrit.simantics Code Review - simantics/sysdyn.git/blob
636fd688f1bee30f439de0cc0bed74f463da25d1
[simantics/sysdyn.git] /
1 package org.simantics.sysdyn.ui.wizards.models;\r
2 \r
3 import java.io.File;\r
4 \r
5 import org.eclipse.core.runtime.IStatus;\r
6 import org.eclipse.core.runtime.Platform;\r
7 import org.eclipse.core.runtime.Status;\r
8 import org.eclipse.jface.layout.PixelConverter;\r
9 import org.eclipse.jface.viewers.IStructuredSelection;\r
10 import org.eclipse.jface.wizard.WizardPage;\r
11 import org.eclipse.swt.SWT;\r
12 import org.eclipse.swt.events.ModifyEvent;\r
13 import org.eclipse.swt.events.ModifyListener;\r
14 import org.eclipse.swt.events.SelectionAdapter;\r
15 import org.eclipse.swt.events.SelectionEvent;\r
16 import org.eclipse.swt.layout.GridData;\r
17 import org.eclipse.swt.layout.GridLayout;\r
18 import org.eclipse.swt.widgets.Button;\r
19 import org.eclipse.swt.widgets.Composite;\r
20 import org.eclipse.swt.widgets.FileDialog;\r
21 import org.eclipse.swt.widgets.Label;\r
22 import org.eclipse.swt.widgets.Shell;\r
23 import org.eclipse.swt.widgets.Text;\r
24 import org.simantics.db.Resource;\r
25 import org.simantics.db.exception.DatabaseException;\r
26 import org.simantics.sysdyn.ui.Activator;\r
27 import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
28 import org.simantics.ui.SimanticsUI;\r
29 \r
30 public class WizardModelsImportPage extends WizardPage{\r
31         \r
32         private Text filePathField;\r
33         \r
34         // Keep track of the archive that we browsed to last time\r
35         // the wizard was invoked.\r
36         private static String previouslyBrowsedFile = "";\r
37 \r
38         private Button browseDirectoriesButton;\r
39 \r
40         private Shell shell;\r
41         \r
42         /**\r
43          * Creates a new project creation wizard page.\r
44          * \r
45          */\r
46         public WizardModelsImportPage() {\r
47                 this("wizardModelsImportPage", null, null); //$NON-NLS-1$\r
48         }\r
49 \r
50         /**\r
51          * Create a new instance of the receiver.\r
52          * \r
53          * @param pageName\r
54          */\r
55         public WizardModelsImportPage(String pageName) {\r
56                 this(pageName,null, null);\r
57         }\r
58                         \r
59         /**\r
60          * More (many more) parameters.\r
61          * \r
62          * @param pageName\r
63          * @param initialPath\r
64          * @param currentSelection\r
65          * @since 3.5\r
66          */\r
67         public WizardModelsImportPage(String pageName,String initialPath,\r
68                         IStructuredSelection currentSelection) {\r
69                 super(pageName);\r
70                 //this.initialPath = initialPath;\r
71                 //this.currentSelection = currentSelection;\r
72                 setPageComplete(false);\r
73                 setTitle("Import Model");\r
74                 setDescription("Choose the Model file, then press Finish.");\r
75         }\r
76 \r
77         \r
78         public void createControl(Composite parent) {\r
79 \r
80                 initializeDialogUnits(parent);\r
81 \r
82                 Composite workArea = new Composite(parent, SWT.NONE);\r
83                 setControl(workArea);\r
84 \r
85                 workArea.setLayout(new GridLayout());\r
86                 workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
87                                 | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
88 \r
89                 createProjectsRoot(workArea);\r
90         }\r
91         \r
92         private void createProjectsRoot(Composite workArea) {\r
93 \r
94                 // set label for field\r
95                 Label title = new Label(workArea, SWT.NONE);\r
96                 title.setText("Select Model source:");\r
97                 \r
98                 Composite projectGroup = new Composite(workArea, SWT.NONE);\r
99                 GridLayout layout = new GridLayout();\r
100                 layout.numColumns = 2;\r
101                 layout.makeColumnsEqualWidth = false;\r
102                 layout.marginWidth = 0;\r
103 \r
104                 projectGroup.setLayout(layout);\r
105                 projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
106 \r
107                 // model location entry field\r
108                 this.filePathField = new Text(projectGroup, SWT.BORDER);\r
109                 \r
110                 GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
111                 directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
112                 filePathField.setLayoutData(directoryPathData);\r
113                 filePathField.addModifyListener(new ModifyListener(){\r
114             @Override\r
115             public void modifyText(ModifyEvent e) {\r
116                 previouslyBrowsedFile = filePathField.getText();\r
117             }\r
118                 });\r
119                 if (previouslyBrowsedFile != null){\r
120                         filePathField.setText(previouslyBrowsedFile);\r
121                         validatePage();\r
122                 }\r
123                 \r
124                 // browse button\r
125                 browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
126                 browseDirectoriesButton.setText("Browse");\r
127                 setButtonLayoutData(browseDirectoriesButton);\r
128                         \r
129                 browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
130                         /*\r
131                          * (non-Javadoc)\r
132                          * \r
133                          * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
134                          * elected(org.eclipse.swt.events.SelectionEvent)\r
135                          */\r
136                         public void widgetSelected(SelectionEvent e) {\r
137                                 setErrorMessage(null);\r
138                                 handleLocationDirectoryButtonPressed();\r
139                         }\r
140                 });     \r
141         }\r
142 \r
143         \r
144         //Set filePathField active\r
145         public void setVisible(boolean visible) {\r
146                 super.setVisible(visible);\r
147                 this.filePathField.setFocus();\r
148         }\r
149         \r
150         \r
151         //Open dialog for choosing the file\r
152         protected void handleLocationDirectoryButtonPressed() {\r
153                 \r
154                 shell = filePathField.getShell();\r
155                 \r
156                 FileDialog dialog = new FileDialog(shell, SWT.OPEN);\r
157                 \r
158                 String[] ext = {"*.tg"};\r
159                 dialog.setFilterExtensions(ext);\r
160                 \r
161                 dialog.setText("Import Model");\r
162 \r
163                 String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODELTPATH);\r
164                 if(path.isEmpty() || !(new File(path).exists()))\r
165                         path = Platform.getLocation().toOSString();\r
166                 dialog.setFilterPath(path);\r
167                 \r
168                 String selectedFile = dialog.open();\r
169                 if (selectedFile != null) {\r
170                         filePathField.setText(selectedFile);\r
171                         validatePage();\r
172                 }\r
173                 \r
174         }\r
175 \r
176         //Create project after finish is pressed.\r
177         public boolean createProjects() {\r
178                 \r
179                 Resource project = SimanticsUI.getProject().get();\r
180                 if(project == null){\r
181                         setErrorMessage("Error when retrieving resource");\r
182                         return false;\r
183                 }\r
184                 \r
185                 final String selected = previouslyBrowsedFile;\r
186                 if(selected == null){\r
187                         setErrorMessage("No file selected");\r
188                         return false;\r
189                 }\r
190                 \r
191                 IStatus status = ImportUtilsUI.importModelFile(selected, null);\r
192                 \r
193         /*\r
194                 TransferableGraph1 tg = null;\r
195                 try {\r
196                         tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));\r
197                 } catch (RuntimeBindingConstructionException e) {\r
198                         e.printStackTrace();\r
199                 } catch (IOException e) {       \r
200                         try {\r
201                                 OldTransferableGraph1 otg = (OldTransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(OldTransferableGraph1.class));\r
202                                 tg = new TransferableGraph1(otg.resourceCount, otg.identities, otg.statements, otg.values);\r
203                         } catch (RuntimeBindingConstructionException e1) {\r
204                                 e1.printStackTrace();\r
205                         } catch (IOException e1) {\r
206                                 setErrorMessage("The imported file is not of type: System Dynamics Model");\r
207                                 return false;\r
208                         }\r
209                 }\r
210                 if(tg == null){ \r
211                         setErrorMessage("The imported file is not of type: System Dynamics Model");\r
212                         return false;\r
213                 }\r
214                 \r
215                 try {\r
216                         \r
217                         DefaultPasteImportAdvisor ia = new DefaultPasteImportAdvisor(project);\r
218                         DefaultPasteHandler.defaultExecute(tg, SimanticsUI.getProject().get(), ia);\r
219                         \r
220                         // Check that imported resource was actually a model \r
221                         //and fix changes made to old ontology versions\r
222                         final Resource root = ia.getRoot();\r
223                         SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
224                                 \r
225                                 @Override\r
226                                 public void perform(WriteGraph graph) throws DatabaseException {\r
227                                         \r
228                                         if(!graph.isInstanceOf(root, SysdynResource.getInstance(graph).SysdynModel)) {\r
229                                                 Resource instanceOf = graph.getPossibleObject(root, Layer0.getInstance(graph).InstanceOf);\r
230                                                 String type = "...";\r
231                                                 if(instanceOf != null)\r
232                                                         type = NameUtils.getSafeName(graph, instanceOf);\r
233                                                 else {\r
234                                                         Resource inheritedFrom = graph.getPossibleObject(root, Layer0.getInstance(graph).Inherits);\r
235                                                         if(inheritedFrom != null)\r
236                                                                 type = NameUtils.getSafeName(graph, inheritedFrom);\r
237                                                 }\r
238                                                 graph.deny(root, Layer0.getInstance(graph).PartOf);\r
239                                                 error = type;\r
240                                         } else {\r
241                                                 updateOldConfigurationToBaseRealization(graph, root);\r
242                                                 addDefaultOntologyLinks(graph, root);\r
243                                                 addURIsToDiagrams(graph, root);\r
244                                                 addSpreadSheetBook(graph, root);\r
245                                         }\r
246                                 }\r
247                         });\r
248                 } catch (DatabaseException e) {\r
249                         e.printStackTrace();\r
250                 } catch (Exception e) {\r
251                         e.printStackTrace();\r
252                 }\r
253     \r
254                 if (!error.isEmpty()){\r
255                         setErrorMessage("The imported file is not of type: System Dynamics Model (" + error +")");\r
256                         error = "";\r
257                         return false;\r
258                 }\r
259                 */\r
260                 if(status == null || !status.equals(Status.OK_STATUS)) {\r
261                     setErrorMessage(status.getMessage());\r
262                     return false;\r
263                 }\r
264                 return true;            \r
265         }\r
266         \r
267         /**\r
268          * In old versions base realization was separate. Newer versions use configuration as base realization. \r
269          * @param graph WriteGraph\r
270          * @param model Imported model\r
271          */\r
272         /*\r
273         private static void updateOldConfigurationToBaseRealization(WriteGraph graph, Resource model) {\r
274                 Layer0X L0X = Layer0X.getInstance(graph);\r
275                 try {\r
276                         Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
277                         if(configuration != null && !graph.hasStatement(configuration, L0X.IsBaseRealizationOf, model))\r
278                                 graph.claim(configuration, L0X.IsBaseRealizationOf, model);\r
279                 } catch (DatabaseException e) {\r
280                         e.printStackTrace();\r
281                 }\r
282                 \r
283         }\r
284         */\r
285         \r
286         /**\r
287          * Links should be exported and imported automatically. If it has failed, the \r
288          * default ontology links sysdyn and layer0 are added.\r
289          * \r
290          * @param graph WriteGraph\r
291          * @param model Imported model\r
292          */\r
293          /*\r
294         private static void addDefaultOntologyLinks(WriteGraph graph, Resource model) {\r
295                 try {\r
296                         Layer0 l0 = Layer0.getInstance(graph);\r
297                         // The links should be exported and imported automatically\r
298                         Resource sysdyn = graph.getResource("http://www.simantics.org/Sysdyn-1.1");\r
299                         Resource layer0 = graph.getResource("http://www.simantics.org/Layer0-1.1");\r
300                         if(!graph.hasStatement(model, l0.IsLinkedTo, sysdyn))\r
301                                 graph.claim(model, l0.IsLinkedTo, sysdyn);\r
302                         if(!graph.hasStatement(model, l0.IsLinkedTo, layer0))\r
303                                 graph.claim(model, l0.IsLinkedTo, layer0);\r
304                 } catch (DatabaseException e) {\r
305                         e.printStackTrace();\r
306                 }\r
307         }\r
308                 \r
309         private static void addURIsToDiagrams(WriteGraph graph, Resource model) {\r
310                 Layer0 l0 = Layer0.getInstance(graph);\r
311                 SimulationResource simu = SimulationResource.getInstance(graph);\r
312                 ModelingResources mr = ModelingResources.getInstance(graph);\r
313                 SysdynResource sr = SysdynResource.getInstance(graph);\r
314                 StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
315                 try {\r
316                         HashSet<Resource> configurations = new HashSet<Resource>();\r
317                 \r
318                         Resource configuration = graph.getPossibleObject(model, simu.HasConfiguration);\r
319                         if(configuration != null) \r
320                                 configurations.add(configuration);\r
321                         \r
322                         for(Resource r : graph.getObjects(model, l0.ConsistsOf)) {\r
323                                 if(graph.isInheritedFrom(r, sr.Module)) {\r
324                                         Resource moduleConfiguration = graph.getPossibleObject(r, sr2.IsDefinedBy);\r
325                                         if(moduleConfiguration != null)\r
326                                                 configurations.add(moduleConfiguration);\r
327                                 }\r
328                         }\r
329                         \r
330                         for(Resource conf : configurations) {\r
331                                 Resource configurationDiagram = graph.getPossibleObject(conf, mr.CompositeToDiagram);\r
332                                 if(configurationDiagram != null && !graph.hasStatement(configurationDiagram, l0.PartOf)) {\r
333                                         GraphUtils.create2(graph, l0.Library, \r
334                                                         l0.HasName, "__CONTAINER__",\r
335                                                         l0.PartOf, conf,\r
336                                                         l0.ConsistsOf, configurationDiagram);\r
337                                 }\r
338                         }\r
339                         \r
340                 } catch (DatabaseException e) {\r
341                         e.printStackTrace();\r
342                 }\r
343         }\r
344 */      \r
345         \r
346         /**\r
347          * Add a missing spreadsheet book to the model\r
348          * \r
349          * @param graph\r
350          * @param model\r
351          */\r
352         /*\r
353         private static void addSpreadSheetBook(WriteGraph graph, Resource model) {\r
354             try {\r
355                 Layer0 l0 = Layer0.getInstance(graph);\r
356                 SpreadsheetResource ssr = SpreadsheetResource.getInstance(graph);\r
357                 SimulationResource simu = SimulationResource.getInstance(graph);\r
358                 Resource conf = graph.getPossibleObject(model, simu.HasConfiguration);\r
359                 if(conf != null && graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, ssr.Book)).isEmpty()) {\r
360                     Resource book = graph.newResource();\r
361                     graph.claim(book, l0.InstanceOf, null, ssr.Book);\r
362                     graph.addLiteral(book, l0.HasName, l0.NameOf, l0.String, "Book" + UUID.randomUUID().toString(), Bindings.STRING);\r
363                     graph.claim(conf, l0.ConsistsOf, l0.PartOf, book);\r
364 \r
365                     createSheet(graph, book, "Sheet1", new String[] { }, new int[] { 50 });\r
366                 }\r
367             } catch (DatabaseException e) {\r
368                 e.printStackTrace();\r
369             }\r
370         }\r
371         */\r
372         /**\r
373          * Create a sheet (Copied from SysdynProject)\r
374          * \r
375          * @param graph\r
376          * @param book\r
377          * @param name\r
378          * @param colNames\r
379          * @param colWidths\r
380          * @return\r
381          * @throws DatabaseException\r
382          */\r
383         /*\r
384     private static Resource createSheet(WriteGraph graph, Resource book, String name, String[] colNames, int[] colWidths) throws DatabaseException {\r
385 \r
386         Layer0 L0 = Layer0.getInstance(graph);\r
387         Layer0X L0X = Layer0X.getInstance(graph);\r
388         SpreadsheetResource sr = SpreadsheetResource.getInstance(graph);\r
389 \r
390         Resource result = graph.newResource();\r
391         graph.claim(result, L0.InstanceOf, null, sr.Spreadsheet);\r
392 \r
393         if(name == null) {\r
394             name = NameUtils.findFreshEscapedName(graph, "Sheet", book, sr.HasSheet);\r
395         }\r
396         graph.claimLiteral(result, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);\r
397         graph.claim(book, L0.ConsistsOf, L0.PartOf, result);\r
398 \r
399         {\r
400             Resource newCell = graph.newResource();\r
401             graph.claim(newCell, L0.InstanceOf, null, sr.Dimensions);\r
402             graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Dimensions", Bindings.STRING);\r
403             graph.addLiteral(newCell, sr.Dimensions_fitColumns, sr.Dimensions_fitColumns_Inverse, L0.Boolean, false, Bindings.BOOLEAN);\r
404             graph.addLiteral(newCell, sr.Dimensions_fitRows, sr.Dimensions_fitRows_Inverse, L0.Boolean, false, Bindings.BOOLEAN);\r
405             graph.addLiteral(newCell, sr.Dimensions_columnCount, sr.Dimensions_columnCount_Inverse, L0.Integer, 128, Bindings.INTEGER);\r
406             graph.addLiteral(newCell, sr.Dimensions_rowCount, sr.Dimensions_rowCount_Inverse, L0.Integer, 256, Bindings.INTEGER);\r
407             graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);\r
408         }\r
409 \r
410         {\r
411             Resource newCell = graph.newResource();\r
412             graph.claim(newCell, L0.InstanceOf, null, sr.Dimensions);\r
413             graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Headers", Bindings.STRING);\r
414             graph.addLiteral(newCell, sr.Headers_columnLabels, sr.Headers_columnLabels_Inverse, L0.StringArray, colNames, Bindings.STRING_ARRAY);\r
415             graph.addLiteral(newCell, sr.Headers_columnWidths, sr.Headers_columnWidths_Inverse, L0.IntegerArray, colWidths, Bindings.INT_ARRAY);\r
416             graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);\r
417         }\r
418 \r
419         {\r
420             \r
421             double[] doubles = new double[10*2];\r
422             for(int i=0;i<10*2;i++) doubles[i] = i;\r
423             \r
424             Resource newCell = graph.newResource();\r
425             graph.claim(newCell, L0.InstanceOf, null, sr.DoubleArrayCell);\r
426             graph.addLiteral(newCell, sr.DoubleArrayCell_HasWidth, sr.DoubleArrayCell_HasWidth_Inverse, L0.Integer, 10, Bindings.INTEGER);\r
427             graph.addLiteral(newCell, sr.HasLocation, sr.HasLocation_Inverse, L0.String, "B2", Bindings.STRING);\r
428             graph.addLiteral(newCell, sr.DoubleArrayCell_HasDoubleArray, sr.DoubleArrayCell_HasDoubleArray_Inverse, L0.DoubleArray, doubles, Bindings.DOUBLE_ARRAY);\r
429             graph.claim(result, L0X.HasChildVariables, L0X.HasChildVariables_Inverse, newCell);\r
430             \r
431         }\r
432         \r
433         return result;\r
434 \r
435     }\r
436     */\r
437     void validatePage(){\r
438         \r
439                 if (previouslyBrowsedFile.isEmpty()){\r
440                         setPageComplete(false);\r
441                         return;\r
442                 }\r
443                 setErrorMessage(null);\r
444                 setPageComplete(true);\r
445     }\r
446 }