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