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