]> gerrit.simantics Code Review - simantics/sysdyn.git/blob
f007253eec1ce13c9c2aff53e20da16c5739f590
[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.databoard.Bindings;
32 import org.simantics.db.ReadGraph;
33 import org.simantics.db.Resource;
34 import org.simantics.db.common.primitiverequest.PossibleRelatedValue;
35 import org.simantics.db.common.request.ReadRequest;
36 import org.simantics.db.common.utils.NameUtils;
37 import org.simantics.db.exception.DatabaseException;
38 import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;
39 import org.simantics.db.layer0.util.TransferableGraphConfiguration2;
40 import org.simantics.db.request.Read;
41 import org.simantics.graph.db.TGStatusMonitor;
42 import org.simantics.graph.db.TransferableGraphSource;
43 import org.simantics.graph.db.TransferableGraphs;
44 import org.simantics.layer0.Layer0;
45 import org.simantics.sysdyn.SysdynResource;
46 import org.simantics.sysdyn.ui.Activator;
47 import org.simantics.ui.SimanticsUI;
48 import org.simantics.utils.datastructures.ArrayMap;
49
50 public class WizardFunctionsExportPage extends WizardPage {
51         
52         // dialog store id constants
53         private Text filePathField;
54         
55         // Keep track of the archive that we browsed to last time
56         // the wizard was invoked.
57         private static String previouslyBrowsedFile = "";
58
59         private Button browseDirectoriesButton;
60         
61         //private IStructuredSelection currentSelection;
62         
63         GraphExplorerComposite functionLibraryExplorer;
64         
65         private boolean selectionMade = false;
66         
67         /**
68          * Creates a new project creation wizard page.
69          * 
70          */
71         public WizardFunctionsExportPage() {
72                 this("wizardFunctionsExportPage", null, null); //$NON-NLS-1$
73         }
74
75         /**
76          * Create a new instance of the receiver.
77          * 
78          * @param pageName
79          */
80         public WizardFunctionsExportPage(String pageName) {
81                 this(pageName,null, null);
82         }
83                         
84         /**
85          * More (many more) parameters.
86          * 
87          * @param pageName
88          * @param initialPath
89          * @param currentSelection
90          * @since 3.5
91          */
92         public WizardFunctionsExportPage(String pageName,String initialPath,
93                         IStructuredSelection currentSelection) {
94                 super(pageName);
95                 //this.currentSelection = currentSelection;
96                 setPageComplete(false);
97                 setTitle("Export Function Library");
98                 setDescription("Choose the Function Library and the export location, then press Finish.");
99         }
100         
101         public void createControl(Composite parent) {
102                 
103                 initializeDialogUnits(parent);
104
105                 Composite workArea = new Composite(parent, SWT.NONE);
106                 setControl(workArea);
107
108                 workArea.setLayout(new GridLayout());
109                 workArea.setLayoutData(new GridData(GridData.FILL_BOTH
110                                 | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
111
112                 createProjectsRoot(workArea);
113                 createTree(workArea);
114                 
115         }
116         
117         private void createProjectsRoot(Composite workArea) {
118                 
119                 // set label for field
120                 Label title = new Label(workArea, SWT.NONE);
121                 title.setText("Select the export location for Function Library:");
122                 
123                 Composite projectGroup = new Composite(workArea, SWT.NONE);
124                 GridLayout layout = new GridLayout();
125                 layout.numColumns = 2;
126                 layout.makeColumnsEqualWidth = false;
127                 layout.marginWidth = 0;
128
129                 projectGroup.setLayout(layout);
130                 projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
131                 
132                 // function library location entry field
133                 this.filePathField = new Text(projectGroup, SWT.BORDER);
134
135                 GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);
136                 directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);
137                 filePathField.setLayoutData(directoryPathData);
138                 
139                 filePathField.addModifyListener(new ModifyListener(){
140             @Override
141             public void modifyText(ModifyEvent e) {
142                 previouslyBrowsedFile = filePathField.getText();        
143             }
144                 });
145                 if (previouslyBrowsedFile != null){
146                         filePathField.setText(previouslyBrowsedFile);
147                         validatePage();
148                 }
149                 
150                 // browse button
151                 browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);
152                 browseDirectoriesButton.setText("Browse");
153                 setButtonLayoutData(browseDirectoriesButton);
154                 
155                 browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {
156                         /*
157                          * (non-Javadoc)
158                          * 
159                          * @see org.eclipse.swt.events.SelectionAdapter#widgetS
160                          * elected(org.eclipse.swt.events.SelectionEvent)
161                          */
162                         public void widgetSelected(SelectionEvent e) {
163                                 handleLocationDirectoryButtonPressed();
164                         }
165                 });
166                 
167         }
168         
169         private void createTree(Composite workArea){
170                 
171                 //set label for tree
172                 Label title = new Label(workArea, SWT.NONE);
173                 title.setText("Select Function Library to export:");
174
175                 Resource input = SimanticsUI.getProject().get();
176
177                 functionLibraryExplorer = new GraphExplorerComposite(ArrayMap.keys(
178                                 "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);
179
180                 functionLibraryExplorer
181                 .setBrowseContexts(SysdynResource.URIs.FunctionTree);
182
183                 functionLibraryExplorer.finish();
184
185                 functionLibraryExplorer.setInput(null, input);
186
187                 GridDataFactory.fillDefaults().grab(true, true).applyTo(
188                                 functionLibraryExplorer);
189
190                 ((Tree)functionLibraryExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {
191
192                         @Override
193                         public void widgetSelected(SelectionEvent e) {
194                                 setMessage(null);
195                                 selectionMade = true;
196                                 validatePage();
197                         }
198                         @Override
199                         public void widgetDefaultSelected(SelectionEvent e) {
200                                 setMessage(null);
201                                 selectionMade = true;
202                                 validatePage();
203                         }
204                 });
205         }
206     
207         //Set filePathField active
208         public void setVisible(boolean visible) {
209                 super.setVisible(visible);
210                 this.filePathField.setFocus();
211         }
212         
213         
214         //Open dialog for choosing the file
215         protected void handleLocationDirectoryButtonPressed() {
216                 
217                 final Shell shell = filePathField.getShell();
218                 
219                 FileDialog dialog = new FileDialog(shell, SWT.SAVE);
220                 
221                 String[] ext = {"*.sysdynFunctions"};
222                 dialog.setFilterExtensions(ext);
223                 
224                 dialog.setText("Export Function Library");
225
226                 String dirName = filePathField.getText().trim();
227                 
228                 File path = new File(dirName);
229                 if (path.exists()) {
230                         dialog.setFilterPath(new Path(dirName).toOSString());   
231                 }
232                 
233                 String selectedFile = dialog.open();
234                 if (selectedFile != null) {
235                         filePathField.setText(selectedFile);
236                         validatePage();
237                 }               
238
239         }
240         
241         //Get selection from the tree
242         @SuppressWarnings("unchecked")
243         public static <T> T getExplorerResource(GraphExplorerComposite explorer,
244                         Class<T> clazz) {
245                 if(explorer == null)
246                         return null;
247                 ISelection selection = ((ISelectionProvider) explorer
248                                 .getAdapter(ISelectionProvider.class)).getSelection();
249                 if (selection == null)
250                         return null;
251                 IStructuredSelection iss = (IStructuredSelection) selection;
252                 AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();
253                 if (inc == null)
254                         return null;
255                 final T resource = (T) inc.getAdapter(clazz);
256
257                 return resource;
258         }
259         
260         public boolean createProjects(Resource selection) {
261                 
262                 final String selected = previouslyBrowsedFile;
263                 if(selected == null) return false;
264                 
265         final Resource functionLibrary = getExplorerResource(functionLibraryExplorer, Resource.class);
266         if(functionLibrary == null) return false;
267         
268                 String name = null;
269                 try {
270                         name = SimanticsUI.getSession().syncRequest(new Read<String>() {
271
272                                 @Override
273                                 public String perform(ReadGraph graph) throws DatabaseException {
274                                         if (!graph.hasStatement(functionLibrary, Layer0.getInstance(graph).PartOf))
275                                                 return null;
276                                         Layer0 l0 = Layer0.getInstance(graph);
277                                         String name = graph.syncRequest(new PossibleRelatedValue<String>(functionLibrary, l0.HasName, Bindings.STRING ));
278                                         return name;
279                                         
280                                 }
281                                 
282                         });
283                 } catch (DatabaseException ex) {
284                         Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
285                                         "Failed to read name of function library " + functionLibrary + ", see exception for details.", ex));
286                 }
287                 if(name == null) return false;
288
289                 SimanticsUI.getSession().asyncRequest(new ReadRequest() {
290                         @Override
291                         public void run(ReadGraph graph) throws DatabaseException {
292                                 TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, functionLibrary);
293                                 try (TransferableGraphSource tgs = graph.syncRequest( new ModelTransferableGraphSourceRequest(conf) )) {
294                                         TransferableGraphs.writeTransferableGraph(graph, tgs, new File(selected), TGStatusMonitor.NULL_MONITOR);
295                                 } catch (Exception e) {
296                                         Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
297                                                         "Failed to export function library, see exception for details.", e));
298                                 }
299                         }
300                 });
301         
302         return true;
303         }
304         
305         void validatePage() {
306                 
307                 if (previouslyBrowsedFile.isEmpty() || selectionMade == false){
308                         setPageComplete(false);
309                         return;
310                 }
311                 
312                 if (functionLibraryExplorer != null){
313                         final Resource selectedResource = getExplorerResource(functionLibraryExplorer, Resource.class);
314
315                         String root = null;
316                         try {
317                                 root = SimanticsUI.getSession().syncRequest(new Read<String>() {
318
319                                         @Override
320                                         public String perform(ReadGraph graph) throws DatabaseException {
321                                                 Layer0 l0 = Layer0.getInstance(graph);
322                                                 Resource model = graph.getPossibleObject(selectedResource, l0.PartOf);
323                                                 String rootName = NameUtils.getSafeName(graph, model);
324
325                                                 return rootName;
326                                         }
327
328                                 });
329                                 if (root != null && root.equalsIgnoreCase("Development Project")){
330                                         setPageComplete(false);
331                                         setMessage("Select Function Library folder under the Model or from the Shared Functions folder.");
332                                         return;
333                                 }
334                         } catch (DatabaseException e) {
335                                 Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
336                                                 "Failed to validate wizard page contents, see exception for details.", e));
337                         }
338                 }
339                 
340                 setPageComplete(true);
341                 
342         }
343         
344 }