1 package org.simantics.sysdyn.ui.wizards.modules;
4 import java.util.ArrayList;
5 import java.util.Collection;
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;
57 public class WizardModulesExportPage extends WizardPage {
59 // dialog store id constants
60 private Text filePathField;
62 // Keep track of the archive that we browsed to last time
63 // the wizard was invoked.
64 private static String previouslyBrowsedFile = "";
66 private Button browseDirectoriesButton;
68 private Resource selectedModule;
70 GraphExplorerComposite modelExplorer;
72 private boolean selectionMade = false;
75 * Creates a new project creation wizard page.
78 public WizardModulesExportPage() {
79 this("wizardModulesExportPage", null, null); //$NON-NLS-1$
83 * Create a new instance of the receiver.
87 public WizardModulesExportPage(String pageName) {
88 this(pageName,null, null);
92 * More (many more) parameters.
96 * @param currentSelection
99 public WizardModulesExportPage(String pageName,String initialPath,
100 IStructuredSelection currentSelection) {
102 //this.currentSelection = currentSelection;
103 setPageComplete(false);
104 setTitle("Export Module");
105 setDescription("Choose the Module and the export location, then press Finish.");
108 public void createControl(Composite parent) {
110 initializeDialogUnits(parent);
112 Composite workArea = new Composite(parent, SWT.NONE);
113 setControl(workArea);
115 workArea.setLayout(new GridLayout());
116 workArea.setLayoutData(new GridData(GridData.FILL_BOTH
117 | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
119 createProjectsRoot(workArea);
120 createTree(workArea);
123 private void createProjectsRoot(Composite workArea) {
125 // set label for field
126 Label title = new Label(workArea, SWT.NONE);
127 title.setText("Select the export location for Module:");
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;
135 projectGroup.setLayout(layout);
136 projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
138 // module location entry field
139 this.filePathField = new Text(projectGroup, SWT.BORDER);
141 GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);
142 directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);
143 filePathField.setLayoutData(directoryPathData);
145 filePathField.addModifyListener(new ModifyListener(){
147 public void modifyText(ModifyEvent e) {
148 previouslyBrowsedFile = filePathField.getText();
151 if (previouslyBrowsedFile != null){
152 filePathField.setText(previouslyBrowsedFile);
157 browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);
158 browseDirectoriesButton.setText("Browse");
159 setButtonLayoutData(browseDirectoriesButton);
161 browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {
165 * @see org.eclipse.swt.events.SelectionAdapter#widgetS
166 * elected(org.eclipse.swt.events.SelectionEvent)
168 public void widgetSelected(SelectionEvent e) {
169 handleLocationDirectoryButtonPressed();
175 private void createTree(Composite workArea){
178 Label title = new Label(workArea, SWT.NONE);
179 title.setText("Select Module to export:");
181 Resource input = SimanticsUI.getProject().get();
183 modelExplorer = new GraphExplorerComposite(ArrayMap.keys(
184 "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);
187 .setBrowseContexts(SysdynResource.URIs.ExportModuleTree);
189 modelExplorer.finish();
191 modelExplorer.setInput(null, input);
193 GridDataFactory.fillDefaults().grab(true, true).applyTo(
196 ((Tree)modelExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {
199 public void widgetSelected(SelectionEvent e) {
201 selectionMade = true;
205 public void widgetDefaultSelected(SelectionEvent e) {
207 selectionMade = true;
213 //Set filePathField active
214 public void setVisible(boolean visible) {
215 super.setVisible(visible);
216 this.filePathField.setFocus();
219 //Open dialog for choosing the file
220 protected void handleLocationDirectoryButtonPressed() {
222 final Shell shell = filePathField.getShell();
224 FileDialog dialog = new FileDialog(shell, SWT.SAVE);
226 String[] ext = {"*.sysdynModule"};
227 dialog.setFilterExtensions(ext);
229 dialog.setText("Export Module");
231 String dirName = filePathField.getText().trim();
233 File path = new File(dirName);
235 dialog.setFilterPath(new Path(dirName).toOSString());
238 String selectedFile = dialog.open();
239 if (selectedFile != null) {
240 filePathField.setText(selectedFile);
246 //Get selection from the tree
247 @SuppressWarnings("unchecked")
248 public static <T> T getExplorerResource(GraphExplorerComposite explorer,
253 ISelection selection = ((ISelectionProvider) explorer
254 .getAdapter(ISelectionProvider.class)).getSelection();
255 if (selection == null)
257 IStructuredSelection iss = (IStructuredSelection) selection;
258 AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();
261 final T resource = (T) inc.getAdapter(clazz);
266 //Create export file when finish is pressed
267 public boolean createProjects() {
269 final String selected = previouslyBrowsedFile;
270 if(selected == null) return false;
272 selectedModule= getExplorerResource(modelExplorer, Resource.class);
273 if(selectedModule == null)
278 name = SimanticsUI.getSession().syncRequest(new Read<String>() {
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);
286 Resource component = selectedModule;
287 if (component == null || !graph.hasStatement(component, Layer0.getInstance(graph).PartOf))
290 Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);
291 if (configuration == null)
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);
302 if(dependencies != null && !dependencies.isEmpty())
303 throw new ContainsDependenciesException(dependencies);
305 String name = graph.getPossibleRelatedValue(component, l0.HasName, Bindings.STRING);
312 catch (DatabaseException e1) {
313 e1.printStackTrace();
315 if(name == null) return false;
317 SimanticsUI.getSession().asyncRequest(new ReadRequest() {
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))
326 graph.asyncRequest(new WriteRequest() {
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);
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);
346 export(graph, selected, component);
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);
354 export(graph, selected, component);
358 Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to export module, see exception for details.", e));
367 private void export(WriteGraph graph, String path, Resource component) throws DatabaseException {
368 // FIXME: Enumeration replacement handling like this is not suitable.
370 Layer0 l0 = Layer0.getInstance(graph);
371 SysdynResource sr = SysdynResource.getInstance(graph);
372 StructuralResource2 sr2 = StructuralResource2.getInstance(graph);
374 Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);
375 ArrayList<Pair<Resource, Resource>> replacements = new ArrayList<>();
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));
385 for(Pair<Resource,Resource> replacement : replacements)
386 graph.deny(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);
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));
396 } catch (DatabaseException e) {
398 } catch (Exception e) {
399 throw new DatabaseException(e);
401 for(Pair<Resource,Resource> replacement : replacements)
402 graph.claim(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);
406 class ContainsDependenciesException extends DatabaseException {
407 private static final long serialVersionUID = -1533706136673146020L;
409 private Collection<String> dependencies;
411 ContainsDependenciesException(Collection<String> dependencies) {
412 this.dependencies = dependencies;
415 public Collection<String> getDependencies() {
416 return this.dependencies;
421 void validatePage() {
423 if (previouslyBrowsedFile.isEmpty() || selectionMade == false){
424 setPageComplete(false);
428 if (modelExplorer != null){
429 final Resource selectedResource = getExplorerResource(modelExplorer, Resource.class);
433 root = SimanticsUI.getSession().syncRequest(new Read<String>() {
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);
445 if (root != null && root.equalsIgnoreCase("Development Project")){
446 setPageComplete(false);
447 setMessage("Select Module under the Model.");
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));
456 setPageComplete(true);