]> gerrit.simantics Code Review - simantics/sysdyn.git/blob
a4c69b9c9fb612d025c18c9ad77c17b56ce7ce5e
[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 = {"*.sysdyn; *.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                 try {\r
192                         IStatus status = ImportUtilsUI.importModelFile(selected, null);\r
193                         if(status == null || !status.equals(Status.OK_STATUS)) {\r
194                             setErrorMessage(status.getMessage());\r
195                             return false;\r
196                         }\r
197                         return true;\r
198                 } catch (Exception e) {\r
199                         e.printStackTrace();\r
200                         return false;\r
201                 }\r
202                 \r
203         /*\r
204                 TransferableGraph1 tg = null;\r
205                 try {\r
206                         tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));\r
207                 } catch (RuntimeBindingConstructionException e) {\r
208                         e.printStackTrace();\r
209                 } catch (IOException e) {       \r
210                         try {\r
211                                 OldTransferableGraph1 otg = (OldTransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(OldTransferableGraph1.class));\r
212                                 tg = new TransferableGraph1(otg.resourceCount, otg.identities, otg.statements, otg.values);\r
213                         } catch (RuntimeBindingConstructionException e1) {\r
214                                 e1.printStackTrace();\r
215                         } catch (IOException e1) {\r
216                                 setErrorMessage("The imported file is not of type: System Dynamics Model");\r
217                                 return false;\r
218                         }\r
219                 }\r
220                 if(tg == null){ \r
221                         setErrorMessage("The imported file is not of type: System Dynamics Model");\r
222                         return false;\r
223                 }\r
224                 \r
225                 try {\r
226                         \r
227                         DefaultPasteImportAdvisor ia = new DefaultPasteImportAdvisor(project);\r
228                         DefaultPasteHandler.defaultExecute(tg, SimanticsUI.getProject().get(), ia);\r
229                         \r
230                         // Check that imported resource was actually a model \r
231                         //and fix changes made to old ontology versions\r
232                         final Resource root = ia.getRoot();\r
233                         SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
234                                 \r
235                                 @Override\r
236                                 public void perform(WriteGraph graph) throws DatabaseException {\r
237                                         \r
238                                         if(!graph.isInstanceOf(root, SysdynResource.getInstance(graph).SysdynModel)) {\r
239                                                 Resource instanceOf = graph.getPossibleObject(root, Layer0.getInstance(graph).InstanceOf);\r
240                                                 String type = "...";\r
241                                                 if(instanceOf != null)\r
242                                                         type = NameUtils.getSafeName(graph, instanceOf);\r
243                                                 else {\r
244                                                         Resource inheritedFrom = graph.getPossibleObject(root, Layer0.getInstance(graph).Inherits);\r
245                                                         if(inheritedFrom != null)\r
246                                                                 type = NameUtils.getSafeName(graph, inheritedFrom);\r
247                                                 }\r
248                                                 graph.deny(root, Layer0.getInstance(graph).PartOf);\r
249                                                 error = type;\r
250                                         } else {\r
251                                                 updateOldConfigurationToBaseRealization(graph, root);\r
252                                                 addDefaultOntologyLinks(graph, root);\r
253                                                 addURIsToDiagrams(graph, root);\r
254                                                 addSpreadSheetBook(graph, root);\r
255                                         }\r
256                                 }\r
257                         });\r
258                 } catch (DatabaseException e) {\r
259                         e.printStackTrace();\r
260                 } catch (Exception e) {\r
261                         e.printStackTrace();\r
262                 }\r
263     \r
264                 if (!error.isEmpty()){\r
265                         setErrorMessage("The imported file is not of type: System Dynamics Model (" + error +")");\r
266                         error = "";\r
267                         return false;\r
268                 }\r
269                 */\r
270 //              if(status == null || !status.equals(Status.OK_STATUS)) {\r
271 //                  setErrorMessage(status.getMessage());\r
272 //                  return false;\r
273 //              }\r
274 //              return true;            \r
275         }\r
276         \r
277         /**\r
278          * In old versions base realization was separate. Newer versions use configuration as base realization. \r
279          * @param graph WriteGraph\r
280          * @param model Imported model\r
281          */\r
282         /*\r
283         private static void updateOldConfigurationToBaseRealization(WriteGraph graph, Resource model) {\r
284                 Layer0X L0X = Layer0X.getInstance(graph);\r
285                 try {\r
286                         Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
287                         if(configuration != null && !graph.hasStatement(configuration, L0X.IsBaseRealizationOf, model))\r
288                                 graph.claim(configuration, L0X.IsBaseRealizationOf, model);\r
289                 } catch (DatabaseException e) {\r
290                         e.printStackTrace();\r
291                 }\r
292                 \r
293         }\r
294         */\r
295         \r
296         /**\r
297          * Links should be exported and imported automatically. If it has failed, the \r
298          * default ontology links sysdyn and layer0 are added.\r
299          * \r
300          * @param graph WriteGraph\r
301          * @param model Imported model\r
302          */\r
303          /*\r
304         private static void addDefaultOntologyLinks(WriteGraph graph, Resource model) {\r
305                 try {\r
306                         Layer0 l0 = Layer0.getInstance(graph);\r
307                         // The links should be exported and imported automatically\r
308                         Resource sysdyn = graph.getResource("http://www.simantics.org/Sysdyn-1.1");\r
309                         Resource layer0 = graph.getResource("http://www.simantics.org/Layer0-1.1");\r
310                         if(!graph.hasStatement(model, l0.IsLinkedTo, sysdyn))\r
311                                 graph.claim(model, l0.IsLinkedTo, sysdyn);\r
312                         if(!graph.hasStatement(model, l0.IsLinkedTo, layer0))\r
313                                 graph.claim(model, l0.IsLinkedTo, layer0);\r
314                 } catch (DatabaseException e) {\r
315                         e.printStackTrace();\r
316                 }\r
317         }\r
318                 \r
319         private static void addURIsToDiagrams(WriteGraph graph, Resource model) {\r
320                 Layer0 l0 = Layer0.getInstance(graph);\r
321                 SimulationResource simu = SimulationResource.getInstance(graph);\r
322                 ModelingResources mr = ModelingResources.getInstance(graph);\r
323                 SysdynResource sr = SysdynResource.getInstance(graph);\r
324                 StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
325                 try {\r
326                         HashSet<Resource> configurations = new HashSet<Resource>();\r
327                 \r
328                         Resource configuration = graph.getPossibleObject(model, simu.HasConfiguration);\r
329                         if(configuration != null) \r
330                                 configurations.add(configuration);\r
331                         \r
332                         for(Resource r : graph.getObjects(model, l0.ConsistsOf)) {\r
333                                 if(graph.isInheritedFrom(r, sr.Module)) {\r
334                                         Resource moduleConfiguration = graph.getPossibleObject(r, sr2.IsDefinedBy);\r
335                                         if(moduleConfiguration != null)\r
336                                                 configurations.add(moduleConfiguration);\r
337                                 }\r
338                         }\r
339                         \r
340                         for(Resource conf : configurations) {\r
341                                 Resource configurationDiagram = graph.getPossibleObject(conf, mr.CompositeToDiagram);\r
342                                 if(configurationDiagram != null && !graph.hasStatement(configurationDiagram, l0.PartOf)) {\r
343                                         GraphUtils.create2(graph, l0.Library, \r
344                                                         l0.HasName, "__CONTAINER__",\r
345                                                         l0.PartOf, conf,\r
346                                                         l0.ConsistsOf, configurationDiagram);\r
347                                 }\r
348                         }\r
349                         \r
350                 } catch (DatabaseException e) {\r
351                         e.printStackTrace();\r
352                 }\r
353         }\r
354 */      \r
355         \r
356         /**\r
357          * Add a missing spreadsheet book to the model\r
358          * \r
359          * @param graph\r
360          * @param model\r
361          */\r
362         /*\r
363         private static void addSpreadSheetBook(WriteGraph graph, Resource model) {\r
364             try {\r
365                 Layer0 l0 = Layer0.getInstance(graph);\r
366                 SpreadsheetResource ssr = SpreadsheetResource.getInstance(graph);\r
367                 SimulationResource simu = SimulationResource.getInstance(graph);\r
368                 Resource conf = graph.getPossibleObject(model, simu.HasConfiguration);\r
369                 if(conf != null && graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, ssr.Book)).isEmpty()) {\r
370                     Resource book = graph.newResource();\r
371                     graph.claim(book, l0.InstanceOf, null, ssr.Book);\r
372                     graph.addLiteral(book, l0.HasName, l0.NameOf, l0.String, "Book" + UUID.randomUUID().toString(), Bindings.STRING);\r
373                     graph.claim(conf, l0.ConsistsOf, l0.PartOf, book);\r
374 \r
375                     createSheet(graph, book, "Sheet1", new String[] { }, new int[] { 50 });\r
376                 }\r
377             } catch (DatabaseException e) {\r
378                 e.printStackTrace();\r
379             }\r
380         }\r
381         */\r
382         /**\r
383          * Create a sheet (Copied from SysdynProject)\r
384          * \r
385          * @param graph\r
386          * @param book\r
387          * @param name\r
388          * @param colNames\r
389          * @param colWidths\r
390          * @return\r
391          * @throws DatabaseException\r
392          */\r
393         /*\r
394     private static Resource createSheet(WriteGraph graph, Resource book, String name, String[] colNames, int[] colWidths) throws DatabaseException {\r
395 \r
396         Layer0 L0 = Layer0.getInstance(graph);\r
397         Layer0X L0X = Layer0X.getInstance(graph);\r
398         SpreadsheetResource sr = SpreadsheetResource.getInstance(graph);\r
399 \r
400         Resource result = graph.newResource();\r
401         graph.claim(result, L0.InstanceOf, null, sr.Spreadsheet);\r
402 \r
403         if(name == null) {\r
404             name = NameUtils.findFreshEscapedName(graph, "Sheet", book, sr.HasSheet);\r
405         }\r
406         graph.claimLiteral(result, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);\r
407         graph.claim(book, L0.ConsistsOf, L0.PartOf, result);\r
408 \r
409         {\r
410             Resource newCell = graph.newResource();\r
411             graph.claim(newCell, L0.InstanceOf, null, sr.Dimensions);\r
412             graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Dimensions", Bindings.STRING);\r
413             graph.addLiteral(newCell, sr.Dimensions_fitColumns, sr.Dimensions_fitColumns_Inverse, L0.Boolean, false, Bindings.BOOLEAN);\r
414             graph.addLiteral(newCell, sr.Dimensions_fitRows, sr.Dimensions_fitRows_Inverse, L0.Boolean, false, Bindings.BOOLEAN);\r
415             graph.addLiteral(newCell, sr.Dimensions_columnCount, sr.Dimensions_columnCount_Inverse, L0.Integer, 128, Bindings.INTEGER);\r
416             graph.addLiteral(newCell, sr.Dimensions_rowCount, sr.Dimensions_rowCount_Inverse, L0.Integer, 256, Bindings.INTEGER);\r
417             graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);\r
418         }\r
419 \r
420         {\r
421             Resource newCell = graph.newResource();\r
422             graph.claim(newCell, L0.InstanceOf, null, sr.Dimensions);\r
423             graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Headers", Bindings.STRING);\r
424             graph.addLiteral(newCell, sr.Headers_columnLabels, sr.Headers_columnLabels_Inverse, L0.StringArray, colNames, Bindings.STRING_ARRAY);\r
425             graph.addLiteral(newCell, sr.Headers_columnWidths, sr.Headers_columnWidths_Inverse, L0.IntegerArray, colWidths, Bindings.INT_ARRAY);\r
426             graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);\r
427         }\r
428 \r
429         {\r
430             \r
431             double[] doubles = new double[10*2];\r
432             for(int i=0;i<10*2;i++) doubles[i] = i;\r
433             \r
434             Resource newCell = graph.newResource();\r
435             graph.claim(newCell, L0.InstanceOf, null, sr.DoubleArrayCell);\r
436             graph.addLiteral(newCell, sr.DoubleArrayCell_HasWidth, sr.DoubleArrayCell_HasWidth_Inverse, L0.Integer, 10, Bindings.INTEGER);\r
437             graph.addLiteral(newCell, sr.HasLocation, sr.HasLocation_Inverse, L0.String, "B2", Bindings.STRING);\r
438             graph.addLiteral(newCell, sr.DoubleArrayCell_HasDoubleArray, sr.DoubleArrayCell_HasDoubleArray_Inverse, L0.DoubleArray, doubles, Bindings.DOUBLE_ARRAY);\r
439             graph.claim(result, L0X.HasChildVariables, L0X.HasChildVariables_Inverse, newCell);\r
440             \r
441         }\r
442         \r
443         return result;\r
444 \r
445     }\r
446     */\r
447     void validatePage(){\r
448         \r
449                 if (previouslyBrowsedFile.isEmpty()){\r
450                         setPageComplete(false);\r
451                         return;\r
452                 }\r
453                 setErrorMessage(null);\r
454                 setPageComplete(true);\r
455     }\r
456 }